hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
e7c4ebbe14a784f4261405740b2ba92b14834800
1,005
h
C
Prisoner's Dilemma/game.h
aceisnotmycard/Object-Oriented-Programming-I
137717513132261809faec6c56881ac6425cb306
[ "MIT" ]
null
null
null
Prisoner's Dilemma/game.h
aceisnotmycard/Object-Oriented-Programming-I
137717513132261809faec6c56881ac6425cb306
[ "MIT" ]
null
null
null
Prisoner's Dilemma/game.h
aceisnotmycard/Object-Oriented-Programming-I
137717513132261809faec6c56881ac6425cb306
[ "MIT" ]
null
null
null
// // game.h // Prisoners Dilemma II // // Created by Sergey Bogolepov on 11/24/14. // Copyright (c) 2014 Sergey Bogolepov. All rights reserved. // #ifndef __Prisoners_Dilemma_II__game__ #define __Prisoners_Dilemma_II__game__ #include "options_parser.h" #include "strategy.h" #include "factory.h" #include "view.h" #include "prisoner.h" #include "input_handler.h" #include "rule_matrix.h" //TODO: Switch from Singleton pattern to usual class class Game { public: Game() {} void run(std::shared_ptr<OptionsParser> parser, std::shared_ptr<View> view, std::shared_ptr<InputHandler> handler); private: // Strategies names and points std::vector<Prisoner*> _prisoners; std::vector<Prisoner*> _participants; GameMode _mode; int _steps; std::shared_ptr<View> _view; std::shared_ptr<InputHandler> _handler; RuleMatrix _matrix; void _play_round(); void _play(int times); }; #endif /* defined(__Prisoners_Dilemma_II__game__) */
21.847826
119
0.699502
[ "vector" ]
e7c606a1097c241100c2d18e7e4c1cfd25ba4c1f
4,163
h
C
arduino/lib/BLE/src/CurrentTimeService.h
glsubri/morninglight
b5b73a22d79784c6e9090e03a0cf933e24bd856d
[ "MIT" ]
1
2021-09-05T19:04:04.000Z
2021-09-05T19:04:04.000Z
arduino/lib/BLE/src/CurrentTimeService.h
glsubri/morninglight
b5b73a22d79784c6e9090e03a0cf933e24bd856d
[ "MIT" ]
null
null
null
arduino/lib/BLE/src/CurrentTimeService.h
glsubri/morninglight
b5b73a22d79784c6e9090e03a0cf933e24bd856d
[ "MIT" ]
null
null
null
#ifndef CURRENT_TIME_SERVICE_H #define CURRENT_TIME_SERVICE_H #include <ArduinoBLE.h> #include <TimeManager.h> #include <TimeSubscriber.h> /** * @brief CurrentTimeService is a singleton class used to setup the BLE Current Time Service. * * Note that this is a singleton class because there cannot be more thant one CurrentTimeService as * it is defined by the Bluetooth group. * */ class CurrentTimeService : public TimeSubscriber { public: /** * @brief Returns the current instance. If no instance exists, it will create one. * * @return CurrentTimeService& The singleton instance */ static CurrentTimeService& getInstance(); // Singleton pattern CurrentTimeService& operator=(const CurrentTimeService&) = delete; CurrentTimeService(const CurrentTimeService&) = delete; /** * @brief Set the Time Manager object * * @param timeManager The timeManager object to set */ void setTimeManager(TimeManager& timeManager); // Subscriber void updateDatetime(tm& datetime) override; private: // Private constructor is necessary for singleton CurrentTimeService(); /** * @brief A pointer to the TimeManager used to know the time. * */ TimeManager* timeManager; /** * @brief The UUID of the Current Time Service. * * This is regulated by the Bluetooth specification, see the Assigned Numbers document. * https://btprodspecificationrefs.blob.core.windows.net/assigned-values/16-bit%20UUID%20Numbers%20Document.pdf */ static constexpr const char* SERVICE_UUID = "1805"; /** * @brief The UUID of the Current Time Characteristic. * * This is regulated by the Bluetooth specification, see the Assigned Numbers document. * https://btprodspecificationrefs.blob.core.windows.net/assigned-values/16-bit%20UUID%20Numbers%20Document.pdf */ static constexpr const char* CURRENT_TIME_UUID = "2A2B"; /** * @brief The properties of the Current Time Characteristic. * * This is regulated by the Bluetooth specification, see the Current Time Service document. * https://www.bluetooth.com/specifications/specs/current-time-service-1-1/ */ static constexpr uint8_t CURRENT_TIME_PROPERTIES = BLERead | BLEWrite | BLENotify; BLEService service; BLECharacteristic currentTime; /** * @brief This method is called just before the currentTime characteristic is read from. * * @param central Is the central device writing our characteristic * @param characteristic Is the BLECharacteristic being read */ static void onRead(BLEDevice central, BLECharacteristic characteristic); /** * @brief This method is called when the currentTime characteristic is written to. * * @param central Is the central device writing our characteristic * @param characteristic Is the BLECharacteristic being written to */ static void onWrite(BLEDevice central, BLECharacteristic characteristic); /** * @brief This method is called when the currentTime characteristic is subscribed to. * * @param central Is the central device writing our characteristic * @param characteristic Is the BLECharacteristic being subscribed to */ static void onSubscribe(BLEDevice central, BLECharacteristic characteristic); /** * @brief This method is called when the currentTime characteristic is unsubscribed from. * * @param central Is the central device writing our characteristic * @param characteristic Is the BLECharacteristic being unsubscribed from */ static void onUnsubscribe(BLEDevice central, BLECharacteristic characteristic); /** * @brief This static method is used to transform a datetime to it's BLE * representation * * @param datetime The time to transform * @param bytes The array of bytes where the BLE representation will be * stored. */ static void timeToBytes(const tm& datetime, uint8_t* bytes); // The TestWrapper class is used to test CurrentTimeService friend class TestWrapper; }; #endif
34.122951
115
0.709825
[ "object", "transform" ]
e7c8b6a99e82e8aec4905e7eaae6ecc307ae8340
7,625
h
C
S3DWrapper9/BaseSwapChain.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
27
2020-11-12T19:24:54.000Z
2022-03-27T23:10:45.000Z
S3DWrapper9/BaseSwapChain.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
2
2020-11-02T06:30:39.000Z
2022-02-23T18:39:55.000Z
S3DWrapper9/BaseSwapChain.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
3
2021-08-16T00:21:08.000Z
2022-02-23T19:19:36.000Z
/* * Project : iZ3D Stereo Driver * Copyright (C) iZ3D Inc. 2002 - 2010 */ #pragma once #include <boost/shared_ptr.hpp> #include <sstream> #include "VertexType.h" #include "MonoSwapChain.h" #include "DX9AutoShift.h" #include "DX9LaserSight.h" #include "..\UILIB\WizardSCData.h" #include "Presenter.h" class CBaseStereoRenderer; class ScalingHook; class MouseHook; typedef boost::shared_ptr<ScalingHook> ScalingHookPtrT; typedef boost::shared_ptr<MouseHook> MouseHookPtrT; class CBaseSwapChain : public CMonoSwapChain { public: CBaseStereoRenderer* GetBaseDevice() { return (CBaseStereoRenderer*)m_pD3D9Device; }; //--- RouterType = ROUTER_TYPE_HOOK case functions ---- void HookIDirect3DSwapChain9All(); void UnHookIDirect3DSwapChain9All(); D3DPRESENT_PARAMETERS m_PresentationParameters[2]; D3DDISPLAYMODEEX m_FullscreenDisplayMode[2]; SIZE m_BackBufferSizeBeforeScaling; SIZE m_BackBufferSize; D3DMULTISAMPLE_TYPE m_MultiSampleType; DWORD m_MultiSampleQuality; HWND m_hDestWindowOverride; CComPtr<IDirect3DSwapChain9>m_pAdditionalSwapChain; UINT m_iAdditionalSwapChain; CComPtr<IDirect3DSurface9> m_pPrimaryBackBuffer; // Saved Original BackBuffer CComPtr<IDirect3DSurface9> m_pSecondaryBackBuffer; // Saved Original CComPtr<IDirect3DSurface9> m_pPrimaryDepthStencil; // Saved Original DepthStencil CComPtr<IDirect3DSurface9> m_pSecondaryDepthStencil; // Saved Original CComPtr<IDirect3DSurface9> m_pWidePresenterSurface; bool m_bDepthBufferFounded; DWORD m_PrevDrawCountAfterClearDepthBuffer; DWORD m_DrawCountAfterClearDepthBuffer; CComPtr<IDirect3DTexture9> m_pLeftDepthStencilTexture; CComPtr<IDirect3DTexture9> m_pRightDepthStencilTexture; CComPtr<IDirect3DSurface9> m_pMainDepthStencilSurface; CComPtr<IDirect3DTexture9> m_pLeftDepthStencilCorrectTexture; CComPtr<IDirect3DTexture9> m_pRightDepthStencilCorrectTexture; bool m_bLockableBackBuffer; bool m_bScalingEnabled; IDirect3DSurface9* m_pLeftBackBufferBeforeScaling; IDirect3DSurface9* m_pRightBackBufferBeforeScaling; IDirect3DSurface9* m_pLeftBackBuffer; IDirect3DSurface9* m_pRightBackBuffer; SIZE m_BBOffsetBeforeScaling; SIZE m_BBOffset; CComPtr<IDirect3DTexture9> m_pLeftMethodTexture; CComPtr<IDirect3DTexture9> m_pRightMethodTexture; RECT m_LeftViewRect; // left image coordinates on image render target RECT m_RightViewRect; // right image coordinates on image render target RECT m_LeftViewRectBeforeScaling; // left image coordinates on image render target before scaling RECT m_RightViewRectBeforeScaling; // right image coordinates on image render target before scaling //--- rect's for stretching in DoScaling() --- RECT m_SrcLeft, m_DstLeft; RECT m_SrcRight, m_DstRight; //--- gamma correction --- bool m_CurrentRAMPisIdentity; D3DGAMMARAMP m_IdentityRAMP; D3DGAMMARAMP m_SavedGammaRamp; // always keep actual ramp for GammaTexture restoring D3DGAMMARAMP m_CurrentRAMP; // RAMP for CBaseSwapChain::GetGammaRamp() function CComPtr<IDirect3DTexture9> m_GammaRAMPTexture; HRESULT UpdateGammaRampTexture(CONST D3DGAMMARAMP *pRamp); void SetGammaRamp(CONST D3DGAMMARAMP* pRamp, bool bUpdateCurrentGamma); void GetGammaRamp(D3DGAMMARAMP* pRamp); // output D3DTVERTEX_2T m_Vertex[4 * 2]; D3DTVERTEX_2T* m_VertexSinglePass1Pass; D3DTVERTEX_2T* m_VertexSinglePass2Pass; bool m_bUseSwapChains; CONST RECT * m_pSourceRect; CONST RECT * m_pDestRect; CONST RGNDATA * m_pDirtyRegion; DWORD m_dwFlags; POINT m_DstMonitorPoint; void SetPresentParams( CONST RECT * pSourceRect, CONST RECT * pDestRect, HWND hDestWindowOverride, CONST RGNDATA * pDirtyRegion, DWORD dwFlags = 0 ); // presenter resources HANDLE m_SharedHandle [SHARED_TEXTURE_COUNT]; IDirect3DTexture9* m_pSharedTexture[SHARED_TEXTURE_COUNT]; IDirect3DSurface9* m_pStagingSurface[SHARED_TEXTURE_COUNT]; CPresenterSCData* m_pPresenterData; CBasePresenterSCData* m_pBasePresenterData; ULONG m_nPresentCounter; //--- statistics variables --- LARGE_INTEGER m_nScreensLagTime; LARGE_INTEGER m_nFrameTimeDelta; LARGE_INTEGER m_nLastFrameTime; //--- time when previous frame was completed --- //--- draw FPS related variables --- std::wostringstream m_szFPS; DOUBLE m_fFPS; LARGE_INTEGER m_nFPSTimeDelta; LARGE_INTEGER m_nLastDropTime; DOUBLE m_fLastMonoFPS; LARGE_INTEGER m_nFPSDropShowTimeLeft; ULONG m_nSessionFrameCount; float m_fMinDepthValue; float m_fMaxDepthValue; std::vector<float> m_MiniHistogram; int m_CurrentGap; // side-by-side ShiftFinder9 m_ShiftFinder; LaserSightData m_LaserSightData; #ifndef DISABLE_WIZARD uilib::WizardSCData m_WizardData; #endif CBaseSwapChain(CMonoRenderer* pDirect3DDevice9, UINT index); ~CBaseSwapChain(void); HRESULT InitWindows(); HRESULT ModifyPresentParameters(); virtual HRESULT Initialize(IDirect3DSwapChain9* pSwapChain); virtual HRESULT InitializeMode(D3DSURFACE_DESC &RenderTargetDesc) = 0; HRESULT PostInitialize(); virtual void Clear(); void ReleaseSC(); virtual void CheckDepthBuffer() {} void ModifyParamsByOutput(); BOOL SendOrPostMessage(WPARAM wParam); void CheckSecondWindowPosition(); void GetSecondaryWindowRect(RECT* rcWindow, RECT* rcClient); void RestoreDeviceMode( ); HMONITOR GetMonitorHandle(int n); void SendImageToPresenter(); HRESULT CreateSharedResources(); void ClearSharedTextures(); HRESULT DoScaling(); HRESULT Compose(); HRESULT CallPresent(); HRESULT PresentData(); void PrepareFPSMessage(); void ProcessDepthBuffer(); bool IsStereoActive(); bool IsSwapEyes(); void DrawOSD( float fFrameTimeDelta ); void WriteJPSScreenshot(bool applyGammaCorrection = false); IDirect3DSurface9* GetLeftBackBufferRT(); IDirect3DTexture9* GetLeftBackBufferTex(); IDirect3DTexture9* GetLeftDepthStencilTex(); RECT* GetLeftBackBufferRect(); IDirect3DSurface9* GetRightBackBufferRT(); IDirect3DTexture9* GetRightBackBufferTex(); IDirect3DTexture9* GetRightDepthStencilTex(); RECT* GetRightBackBufferRect(); IDirect3DSurface9* GetViewRT(bool bLeft); RECT* GetViewRect(bool bLeft); IDirect3DSurface9* GetPresenterBackBuffer(); STDMETHOD(Present)(CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion,DWORD dwFlags); STDMETHOD(GetBackBuffer)(UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer); STDMETHOD(GetDisplayMode)(D3DDISPLAYMODE* pMode); STDMETHOD(GetDisplayModeEx)(D3DDISPLAYMODEEX* pMode, D3DDISPLAYROTATION* pRotation); friend LRESULT CALLBACK S3DWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); protected: SIZE m_DevScreen1; SIZE m_DevScreen2; bool m_bWorkInWindow; // for DeviceMode == DEVICE_MODE_FORCEWINDOWED ScalingHookPtrT m_ScalingHook; MouseHookPtrT m_MouseHook; HRESULT m_hPreviousPresentResult; // second window bool m_bClassWasRegistered; WNDCLASS m_S3DWindowClass; HWND m_hS3DSecondWindow; RECT m_S3DSecondWindowRect; bool m_bS3DSecondWindowVisible; AsyncButton m_StopPresentButton; AsyncButton m_StopRenderButton; ProxyDevice9& GetD3D9Device(); int WINAPI D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ); int WINAPI D3DPERF_EndEvent( void ); };
35.465116
134
0.764328
[ "render", "vector" ]
e7caf44ade95a3e4daeebcb7b32f9d8cd9474825
428
h
C
dupes.h
stoben/dupes
65b85d61884a2d0cceb1a42fea31399d4cdf438d
[ "MIT" ]
null
null
null
dupes.h
stoben/dupes
65b85d61884a2d0cceb1a42fea31399d4cdf438d
[ "MIT" ]
null
null
null
dupes.h
stoben/dupes
65b85d61884a2d0cceb1a42fea31399d4cdf438d
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <stdio.h> #include <cstring> #include <list> #include <vector> #include <set> #include <ctime> //#include <wincrypt.h> #include "md5gen.h" //#define _STL_COMPILER_PREPROCESSOR 1 //#include <windows.h> //#define _HAS_CXX17 1 //#include <string> //#include <iostream> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <filesystem>
19.454545
39
0.686916
[ "vector" ]
e7d8e07399c3430566a5ff3b8429f2502a04bc0c
169,351
c
C
sdk-6.5.20/src/appl/diag/ltsw/l3.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/appl/diag/ltsw/l3.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/appl/diag/ltsw/l3.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/*! \file l3.c * * LTSW L3 CLI commands. */ /* * 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. */ #if defined(BCM_LTSW_SUPPORT) #include <bsl/bsl.h> #include <appl/diag/system.h> #include <appl/diag/bslcons.h> #include <appl/diag/ltsw/cmdlist.h> #include <bcm/l3.h> #include <bcm/tunnel.h> #include <bcm/nat.h> #include <bcm/ipmc.h> #include <bcm/stack.h> #include <bcm_int/ltsw/dev.h> #include <bcm_int/ltsw/util.h> #include <bcm_int/ltsw/l3_fib.h> #include <bcm_int/ltsw/l3_fib_int.h> #include <bcm_int/ltsw/property.h> #include <bcm_int/ltsw/tunnel.h> #include <bcm_int/ltsw/feature.h> #include <bcmlt/bcmlt.h> #include <bcmltd/chip/bcmltd_str.h> #include <sal/sal_types.h> /****************************************************************************** * Local definitions */ /* The maximum count of member can be inputted by one CLI call. */ #define ECMP_MEMBER_MAX 32 #define ROUTE_PERF_VRF 100 typedef struct route_perf_data_s { int count; /* Number of times the functions is called. */ int max; /* Maximum call time. */ int min; /* Minimum call time. */ int total; /* Total duration time. */ } route_perf_data_t; static int egr_obj_id[BCM_MAX_NUM_UNITS]; static int egr_obj_id2[BCM_MAX_NUM_UNITS]; static int alpm_dmode[3][2] = {{-1, -1},{-1, -1},{-1, -1}}; static const char *alpm_route_grp_str[] = { "IPv4 (Private) ", "IPv4 (Global) ", "IPv4 (Override)", "IPv6 (Private) ", "IPv6 (Global) ", "IPv6 (Override)", NULL }; static const char *alpm_route_comb_str[] = { "IPv4 (Prv+Glo) ", "IPv4 (Prv+Glo) ", "IPv4 (Override)", "IPv6 (Prv+Glo) ", "IPv6 (Prv+Glo) ", "IPv6 (Override)", NULL }; /****************************************************************************** * Private functions */ /* * Function: * cmd_ltsw_l3_tunnel_init_print * Description: * Internal function to print out tunnel initiator info. * Parameters: * unit - (IN) Device number. * interface - (IN) L3 egress interface. * info - (IN) Pointer to bcm_tunnel_initiator_t data structure. */ STATIC int cmd_ltsw_l3_tunnel_init_print(int unit, bcm_if_t interface, bcm_tunnel_initiator_t *info) { char ip_str[IP6ADDR_STR_LEN + 3]; cli_out("Tunnel initiator:\n"); cli_out("\tUnit = %d\n", unit); if (interface != 0) { cli_out("\tInterface = %d\n", interface); } cli_out("\tTUNNEL_TYPE = %d\n", info->type); cli_out("\tTTL = %d\n", info->ttl); if (BCMI_LTSW_TUNNEL_OUTER_HEADER_IPV6(info->type)) { format_ip6addr(ip_str, info->dip6); cli_out("\tDIP = 0x%-s\n", ip_str); format_ip6addr(ip_str, info->sip6); cli_out("\tSIP = 0x%-s\n", ip_str); } else { cli_out("\tDIP = 0x%08x\n", info->dip); cli_out("\tSIP = 0x%08x\n", info->sip); if (info->flags & BCM_TUNNEL_INIT_USE_INNER_DF) { cli_out("\tCopy DF from inner header.\n"); } else if (info->flags & BCM_TUNNEL_INIT_IPV4_SET_DF) { cli_out("\tForce DF to 1 for ipv4 payload.\n"); } if (info->flags & BCM_TUNNEL_INIT_IPV6_SET_DF) { cli_out("\tForce DF to 1 for ipv6 payload.\n"); } } cli_out("\tDSCP_ECN_SEL = 0x%x\n", info->dscp_ecn_sel); cli_out("\tDSCP = 0x%x\n", info->dscp); cli_out("\tDSCP_ECN_MAP = 0x%x\n", info->dscp_ecn_map); return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init_create * Description: * Service routine used to create a tunnel initiator. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_create(int unit, args_t *a) { bcm_tunnel_initiator_t tunnel_init; bcm_gport_t tnl_id = 0; bcm_tunnel_type_t type = 0; parse_table_t pt; cmd_result_t retCode; bcm_ip6_t sip6_addr; bcm_ip6_t ip6_addr; bcm_ip_t sip_addr = 0; bcm_ip_t ip_addr = 0; int ip4_df_sel = 0; int ip6_df_sel = 0; int dscp_val = 0; int dscp_ecn_sel = 0; int dscp_ecn_map = 0; int ttl = 0; int rv; /* Stack variables initialization. */ sal_memset(sip6_addr, 0, sizeof(bcm_ip6_t)); sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "TnlId", PQ_DFL|PQ_INT, 0, (void*)&tnl_id, 0); parse_table_add(&pt, "TYpe", PQ_DFL|PQ_INT, 0, (void*)&type, 0); parse_table_add(&pt, "TTL", PQ_DFL|PQ_INT, 0, (void*)&ttl, 0); parse_table_add(&pt, "DIP", PQ_DFL|PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "SIP", PQ_DFL|PQ_IP, 0, (void *)&sip_addr, 0); parse_table_add(&pt, "DIP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "SIP6", PQ_DFL | PQ_IP6, 0, (void *)&sip6_addr, 0); parse_table_add(&pt, "DSCPEcnSel", PQ_DFL|PQ_INT, 0, (void *)&dscp_ecn_sel, 0); parse_table_add(&pt, "DSCPV", PQ_DFL|PQ_INT, 0, (void *)&dscp_val, 0); parse_table_add(&pt, "DFSEL4", PQ_DFL|PQ_INT, 0, (void *)&ip4_df_sel, 0); parse_table_add(&pt, "DFSEL6", PQ_DFL|PQ_BOOL, 0, (void *)&ip6_df_sel, 0); parse_table_add(&pt, "DSCPEcnMap", PQ_DFL|PQ_INT, 0, (void *)&dscp_ecn_map, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_tunnel_initiator_t_init(&tunnel_init); /* Fill tunnel info. */ tunnel_init.type = type; tunnel_init.ttl = ttl; if (ip4_df_sel) { tunnel_init.flags |= (ip4_df_sel > 1) ? BCM_TUNNEL_INIT_USE_INNER_DF : BCM_TUNNEL_INIT_IPV4_SET_DF; } if (ip6_df_sel) { tunnel_init.flags |= BCM_TUNNEL_INIT_IPV6_SET_DF; } sal_memcpy(tunnel_init.dip6, ip6_addr, sizeof(bcm_ip6_t)); sal_memcpy(tunnel_init.sip6, sip6_addr, sizeof(bcm_ip6_t)); tunnel_init.dip = ip_addr; tunnel_init.sip = sip_addr; tunnel_init.dscp_ecn_sel = dscp_ecn_sel; tunnel_init.dscp = dscp_val; tunnel_init.dscp_ecn_map = dscp_ecn_map; if (tnl_id != 0) { tunnel_init.tunnel_id = tnl_id; tunnel_init.flags |= BCM_TUNNEL_WITH_ID | BCM_TUNNEL_REPLACE; } if ((rv = bcm_tunnel_initiator_create(unit, NULL, &tunnel_init)) < 0) { cli_out("ERROR %s: creating tunnel initiator %s.\n", ARG_CMD(a), bcm_errmsg(rv)); return CMD_FAIL; } cli_out("New tunnel initiator ID: 0x%x.\n", tunnel_init.tunnel_id); return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init_get * Description: * Service routine used to get & show tunnel initiator info. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_get(int unit, args_t *a) { bcm_tunnel_initiator_t tunnel_init; parse_table_t pt; cmd_result_t retCode; bcm_gport_t tnl_id; int rv; parse_table_init(unit, &pt); parse_table_add(&pt, "TnlId", PQ_DFL|PQ_INT, 0, (void*)&tnl_id, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } bcm_tunnel_initiator_t_init(&tunnel_init); tunnel_init.tunnel_id = tnl_id; if ((rv = bcm_tunnel_initiator_get(unit, NULL, &tunnel_init)) < 0) { cli_out("ERROR %s: getting tunnel initiator tnl_id 0x%x %s\n", ARG_CMD(a), tnl_id, bcm_errmsg(rv)); return CMD_FAIL; } cmd_ltsw_l3_tunnel_init_print(unit, 0, &tunnel_init); return CMD_OK; } /* * Function: * cmd_ltsw_l3tunnel_init_destroy * Description: * Service routine used to remove tunnel initiator from an interface. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_destroy(int unit, args_t *a) { cmd_result_t retCode; parse_table_t pt; int rv; bcm_gport_t tnl_id; parse_table_init(unit, &pt); parse_table_add(&pt, "TnlId", PQ_DFL|PQ_INT, 0, (void*)&tnl_id, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } if ((rv = bcm_tunnel_initiator_destroy(unit, tnl_id)) < 0) { cli_out("ERROR %s: destroying tunnel initiator 0x%x %s\n", ARG_CMD(a), tnl_id, bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init_set * Description: * Service routine used to set the tunnel property for the given L3 interface.. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_set(int unit, args_t *a) { bcm_tunnel_initiator_t tunnel_init; bcm_l3_intf_t intf; bcm_tunnel_type_t type = 0; parse_table_t pt; cmd_result_t retCode; bcm_ip6_t sip6_addr; bcm_ip6_t ip6_addr; bcm_mac_t mac; bcm_if_t interface = 0; bcm_ip_t sip_addr = 0; bcm_ip_t ip_addr = 0; int ip4_df_sel = 0; int ip6_df_sel = 0; int dscp_val = 0; int dscp_sel = 0; int dscp_map = 0; int ttl = 0; int rv; /* Stack variables initialization. */ sal_memset(&intf, 0, sizeof(bcm_l3_intf_t)); sal_memset(sip6_addr, 0, sizeof(bcm_ip6_t)); sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); sal_memset(mac, 0, sizeof(bcm_mac_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL|PQ_INT, 0, (void*)&interface, 0); parse_table_add(&pt, "TYpe", PQ_DFL|PQ_INT, 0, (void*)&type, 0); parse_table_add(&pt, "TTL", PQ_DFL|PQ_INT, 0, (void*)&ttl, 0); parse_table_add(&pt, "Mac", PQ_DFL|PQ_MAC, 0, (void *)mac, 0); parse_table_add(&pt, "DIP", PQ_DFL|PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "SIP", PQ_DFL|PQ_IP, 0, (void *)&sip_addr, 0); parse_table_add(&pt, "DIP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "SIP6", PQ_DFL | PQ_IP6, 0, (void *)&sip6_addr, 0); parse_table_add(&pt, "DSCPSel", PQ_DFL|PQ_INT, 0, (void *)&dscp_sel, 0); parse_table_add(&pt, "DSCPV", PQ_DFL|PQ_INT, 0, (void *)&dscp_val, 0); parse_table_add(&pt, "DFSEL4", PQ_DFL|PQ_INT, 0, (void *)&ip4_df_sel, 0); parse_table_add(&pt, "DFSEL6", PQ_DFL|PQ_BOOL, 0, (void *)&ip6_df_sel, 0); parse_table_add(&pt, "DSCPMap", PQ_DFL|PQ_INT, 0, (void *)&dscp_map, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_intf_t_init(&intf); bcm_tunnel_initiator_t_init(&tunnel_init); /* Fill tunnel info. */ intf.l3a_intf_id = interface; tunnel_init.type = type; tunnel_init.ttl = ttl; sal_memcpy(tunnel_init.dmac, mac, sizeof(mac)); if (ip4_df_sel) { tunnel_init.flags |= (ip4_df_sel > 1) ? BCM_TUNNEL_INIT_USE_INNER_DF : BCM_TUNNEL_INIT_IPV4_SET_DF; } if (ip6_df_sel) { tunnel_init.flags |= BCM_TUNNEL_INIT_IPV6_SET_DF; } sal_memcpy(tunnel_init.dip6, ip6_addr, sizeof(bcm_ip6_t)); sal_memcpy(tunnel_init.sip6, sip6_addr, sizeof(bcm_ip6_t)); tunnel_init.dip = ip_addr; tunnel_init.sip = sip_addr; tunnel_init.dscp_sel = dscp_sel; tunnel_init.dscp = dscp_val; tunnel_init.dscp_map = dscp_map; if ((rv = bcm_tunnel_initiator_set(unit, &intf, &tunnel_init)) < 0) { cli_out("ERROR %s: setting tunnel initiator for %d %s\n", ARG_CMD(a), interface, bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init_show * Description: * Service routine used to get & show tunnel initiator info. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_show(int unit, args_t *a) { bcm_tunnel_initiator_t tunnel_init; bcm_l3_intf_t intf; parse_table_t pt; cmd_result_t retCode; bcm_if_t interface; int rv; parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL|PQ_INT, 0, (void*)&interface, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } bcm_tunnel_initiator_t_init(&tunnel_init); bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = interface; if ((rv = bcm_tunnel_initiator_get(unit, &intf, &tunnel_init)) < 0) { cli_out("ERROR %s: getting tunnel initiator for %d %s\n", ARG_CMD(a), interface, bcm_errmsg(rv)); return CMD_FAIL; } cmd_ltsw_l3_tunnel_init_print(unit, interface, &tunnel_init); return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init_clear * Description: * Service routine used to delete the tunnel association for the given L3 interface. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_init_clear(int unit, args_t *a) { bcm_if_t interface; cmd_result_t retCode; bcm_l3_intf_t intf; parse_table_t pt; int rv; parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL|PQ_INT, 0, (void*)&interface, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = interface; if ((rv = bcm_tunnel_initiator_clear(unit, &intf)) < 0) { cli_out("ERROR %s: clearing tunnel initiator for %d %s\n", ARG_CMD(a), interface, bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_init * Description: * Service routine used to manipulate tunnel initiator entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_tunnel_init(int unit, args_t *arg) { int r; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { cli_out("%s: ERROR: Missing l3_tunnel_init subcommand\n", ARG_CMD(arg)); return CMD_FAIL; } if (sal_strcasecmp(subcmd, "create") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_create(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "get") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_get(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "destroy") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_destroy(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "set") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_set(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "show") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_show(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "clear") == 0) { if ((r = cmd_ltsw_l3_tunnel_init_clear(unit, arg)) < 0) { goto bcm_err; } } else { return CMD_USAGE; } return CMD_OK; bcm_err: return CMD_FAIL; } /* * Function: * cmd_ltsw_l3_tunnel_term_print * Description: * Internal function to print out tunnel terminator info. * Parameters: * unit - (IN) Device number. * info - (IN) Pointer to bcm_tunnel_terminator_t data structure. */ STATIC int cmd_ltsw_l3_tunnel_term_print (int unit, bcm_tunnel_terminator_t *info) { char ip_str[IP6ADDR_STR_LEN + 3]; cli_out("Tunnel terminator:\n"); cli_out("\tUnit = %d\n", unit); cli_out("\tTUNNEL_TYPE = %d\n", info->type); if (BCMI_LTSW_TUNNEL_OUTER_HEADER_IPV6(info->type)) { format_ip6addr(ip_str, info->dip6); cli_out("\tDIP = 0x%-s\n", ip_str); format_ip6addr(ip_str, info->dip6_mask); cli_out("\tDIP MASK = 0x%-s\n", ip_str); format_ip6addr(ip_str, info->sip6); cli_out("\tSIP = 0x%-s\n", ip_str); format_ip6addr(ip_str, info->sip6_mask); cli_out("\tSIP MASK = 0x%-s\n", ip_str); } else { cli_out("\tDIP = 0x%08x\n", info->dip); cli_out("\tDIP_MASK = 0x%08x\n", info->dip_mask); cli_out("\tSIP = 0x%08x\n", info->sip); cli_out("\tSIP_MASK = 0x%08x\n", info->sip_mask); } if (info->flags & BCM_TUNNEL_TERM_EM) { cli_out("\tEM = TRUE\n"); } else { cli_out("\tEM = FALSE\n"); } cli_out("\tVlan id = 0x%08x\n", info->vlan); if (info->flags & BCM_TUNNEL_TERM_USE_OUTER_DSCP) { cli_out("\tCopy DSCP from outer ip header.\n"); } if (info->flags & BCM_TUNNEL_TERM_USE_OUTER_TTL) { cli_out("\tCopy TTL from outer ip header.\n"); } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_term_add * Description: * Service routine used to add tunnel terminator entry. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_term_add(int unit, args_t *a) { bcm_tunnel_terminator_t tunnel_term; cmd_result_t retCode; parse_table_t pt; int rv; bcm_ip6_t sip6; bcm_ip6_t dip6; int vlan = 0; int dip = 0; int sip = 0; int sip_mask_len = 0; int dip_mask_len = 0; int tnl_type = 0; int outer_ttl = 0; int outer_dscp = 0; int replace=0; int em = 0; parse_table_init(unit, &pt); sal_memset(sip6, 0, sizeof(bcm_ip6_t)); sal_memset(dip6, 0, sizeof(bcm_ip6_t)); parse_table_add(&pt, "DIP", PQ_DFL|PQ_IP, 0, (void*)&dip, 0); parse_table_add(&pt, "SIP", PQ_DFL|PQ_IP, 0, (void*)&sip, 0); parse_table_add(&pt, "DIP6", PQ_DFL|PQ_IP6, 0, (void*)&dip6, 0); parse_table_add(&pt, "SIP6", PQ_DFL|PQ_IP6, 0, (void*)&sip6, 0); parse_table_add(&pt, "DipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&dip_mask_len, 0); parse_table_add(&pt, "SipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&sip_mask_len, 0); parse_table_add(&pt, "TYpe", PQ_DFL|PQ_INT, 0, (void*)&tnl_type, 0); parse_table_add(&pt, "OuterDSCP", PQ_DFL|PQ_BOOL, 0,(void *)&outer_dscp, 0); parse_table_add(&pt, "OuterTTL", PQ_DFL|PQ_BOOL, 0, (void *)&outer_ttl, 0); parse_table_add(&pt, "VLanid", PQ_DFL|PQ_INT, 0, (void*)&vlan, 0); parse_table_add(&pt, "Replace", PQ_DFL|PQ_BOOL, 0, &replace, 0); parse_table_add(&pt, "EM", PQ_DFL|PQ_BOOL, 0, &em, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } sal_memset(&tunnel_term, 0, sizeof (tunnel_term)); if (BCMI_LTSW_TUNNEL_OUTER_HEADER_IPV6(tnl_type)) { sal_memcpy(tunnel_term.sip6, sip6, sizeof(bcm_ip6_t)); sal_memcpy(tunnel_term.dip6, dip6, sizeof(bcm_ip6_t)); bcm_ip6_mask_create(tunnel_term.sip6_mask, sip_mask_len); bcm_ip6_mask_create(tunnel_term.dip6_mask, dip_mask_len); } else { tunnel_term.sip = sip; tunnel_term.dip = dip; tunnel_term.sip_mask = bcm_ip_mask_create(sip_mask_len); tunnel_term.dip_mask = bcm_ip_mask_create(dip_mask_len); } tunnel_term.type = tnl_type; if (outer_dscp) { tunnel_term.flags |= BCM_TUNNEL_TERM_USE_OUTER_DSCP; } if (outer_ttl) { tunnel_term.flags |= BCM_TUNNEL_TERM_USE_OUTER_TTL; } if (replace) { tunnel_term.flags |= BCM_TUNNEL_REPLACE; } if (em) { tunnel_term.flags |= BCM_TUNNEL_TERM_EM; } tunnel_term.vlan = (bcm_vlan_t)vlan; if ((rv = bcm_tunnel_terminator_add(unit, &tunnel_term)) < 0) { cli_out("ERROR %s: adding tunnel term %s\n", ARG_CMD(a), bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_term_delete * Description: * Service routine used to delete tunnel terminator entry. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_term_delete(int unit, args_t *a) { bcm_tunnel_terminator_t tunnel_term; cmd_result_t retCode; parse_table_t pt; int rv; bcm_ip6_t sip6; bcm_ip6_t dip6; int dip = 0; int sip = 0; int sip_mask_len = 0; int dip_mask_len = 0; int tnl_type = 0; int em = 0; parse_table_init(unit, &pt); sal_memset(sip6, 0, sizeof(bcm_ip6_t)); sal_memset(dip6, 0, sizeof(bcm_ip6_t)); parse_table_add(&pt, "DIP", PQ_DFL|PQ_IP, 0, (void*)&dip, 0); parse_table_add(&pt, "SIP", PQ_DFL|PQ_IP, 0, (void*)&sip, 0); parse_table_add(&pt, "DIP6", PQ_DFL|PQ_IP6, 0, (void*)&dip6, 0); parse_table_add(&pt, "SIP6", PQ_DFL|PQ_IP6, 0, (void*)&sip6, 0); parse_table_add(&pt, "DipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&dip_mask_len, 0); parse_table_add(&pt, "SipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&sip_mask_len, 0); parse_table_add(&pt, "TYpe", PQ_DFL|PQ_INT, 0, (void*)&tnl_type, 0); parse_table_add(&pt, "EM", PQ_DFL|PQ_BOOL, 0, &em, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } sal_memset(&tunnel_term, 0, sizeof (tunnel_term)); if (BCMI_LTSW_TUNNEL_OUTER_HEADER_IPV6(tnl_type)) { sal_memcpy(tunnel_term.sip6, sip6, sizeof(bcm_ip6_t)); sal_memcpy(tunnel_term.dip6, dip6, sizeof(bcm_ip6_t)); bcm_ip6_mask_create(tunnel_term.sip6_mask, sip_mask_len); bcm_ip6_mask_create(tunnel_term.dip6_mask, dip_mask_len); } else { tunnel_term.sip = sip; tunnel_term.dip = dip; tunnel_term.sip_mask = bcm_ip_mask_create(sip_mask_len); tunnel_term.dip_mask = bcm_ip_mask_create(dip_mask_len); } tunnel_term.type = tnl_type; if (em) { tunnel_term.flags |= BCM_TUNNEL_TERM_EM; } if ((rv = bcm_tunnel_terminator_delete(unit, &tunnel_term)) < 0) { cli_out("ERROR %s: adding tunnel term %s\n", ARG_CMD(a), bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_term_get * Description: * Service routine used to read tunnel terminator entry. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ STATIC cmd_result_t cmd_ltsw_l3_tunnel_term_get(int unit, args_t *a) { bcm_tunnel_terminator_t tunnel_term; cmd_result_t retCode; parse_table_t pt; int rv; bcm_ip6_t sip6; bcm_ip6_t dip6; int vlan = 0; int dip = 0; int sip = 0; int sip_mask_len = 0; int dip_mask_len = 0; int tnl_type = 0; int em = 0; parse_table_init(unit, &pt); sal_memset(sip6, 0, sizeof(bcm_ip6_t)); sal_memset(dip6, 0, sizeof(bcm_ip6_t)); sal_memset(&tunnel_term, 0, sizeof(bcm_tunnel_terminator_t)); parse_table_add(&pt, "DIP", PQ_DFL|PQ_IP, 0, (void*)&dip, 0); parse_table_add(&pt, "SIP", PQ_DFL|PQ_IP, 0, (void*)&sip, 0); parse_table_add(&pt, "DIP6", PQ_DFL|PQ_IP6, 0, (void*)&dip6, 0); parse_table_add(&pt, "SIP6", PQ_DFL|PQ_IP6, 0, (void*)&sip6, 0); parse_table_add(&pt, "DipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&dip_mask_len, 0); parse_table_add(&pt, "SipMaskLen", PQ_DFL|PQ_INT, 0, (void*)&sip_mask_len, 0); parse_table_add(&pt, "TYpe", PQ_DFL|PQ_INT, 0, (void*)&tnl_type, 0); parse_table_add(&pt, "VLAN", PQ_DFL|PQ_INT, 0, (void*)&vlan, 0); parse_table_add(&pt, "EM", PQ_DFL|PQ_BOOL, 0, &em, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } sal_memset(&tunnel_term, 0, sizeof (tunnel_term)); if (BCMI_LTSW_TUNNEL_OUTER_HEADER_IPV6(tnl_type)) { sal_memcpy(tunnel_term.sip6, sip6, sizeof(bcm_ip6_t)); sal_memcpy(tunnel_term.dip6, dip6, sizeof(bcm_ip6_t)); bcm_ip6_mask_create(tunnel_term.sip6_mask, sip_mask_len); bcm_ip6_mask_create(tunnel_term.dip6_mask, dip_mask_len); } else { tunnel_term.sip = sip; tunnel_term.dip = dip; tunnel_term.sip_mask = bcm_ip_mask_create(sip_mask_len); tunnel_term.dip_mask = bcm_ip_mask_create(dip_mask_len); } tunnel_term.type = tnl_type; tunnel_term.vlan = (bcm_vlan_t)vlan; if (em) { tunnel_term.flags |= BCM_TUNNEL_TERM_EM; } if ((rv = bcm_tunnel_terminator_get(unit, &tunnel_term)) < 0) { cli_out("ERROR %s: getting tunnel term %s\n", ARG_CMD(a), bcm_errmsg(rv)); return CMD_FAIL; } cmd_ltsw_l3_tunnel_term_print(unit, &tunnel_term); return CMD_OK; } /* * Function: * cmd_ltsw_l3_tunnel_term * Description: * Service routine used to manipulate tunnel terminator entry. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_tunnel_term(int unit, args_t *arg) { int r; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { cli_out("%s: ERROR: Missing l3_tunnel_term subcommand\n", ARG_CMD(arg)); return CMD_FAIL; } if (sal_strcasecmp(subcmd, "add") == 0) { if ((r = cmd_ltsw_l3_tunnel_term_add(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "delete") == 0) { if ((r = cmd_ltsw_l3_tunnel_term_delete(unit, arg)) < 0) { goto bcm_err; } } else if (sal_strcasecmp(subcmd, "show") == 0) { if ((r = cmd_ltsw_l3_tunnel_term_get(unit, arg)) < 0) { goto bcm_err; } } else { return CMD_USAGE; } return CMD_OK; bcm_err: return CMD_FAIL; } /*! * \brief Print the ingress interface info. * * \param [in] unit Unit number. * \param [in] intf_id Ingress interface ID. * \param [in] info Ingress interface info. * * \return none. */ static void l3_cmd_ingress_print(int unit, int intf_id, bcm_l3_ingress_t *info) { cli_out("%-5d 0x%-10x %-5d %-9d %-9d %-9d\n", intf_id, info->flags, info->vrf, info->urpf_mode, info->intf_class, info->qos_map_id); cli_out("\n"); } /*! * \brief The callback of ingress interface traverse. * * \param [in] unit Unit number. * \param [in] intf_id Ingress interface ID. * \param [in] info Ingress interface info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_ingress_show_trav_cb(int unit, bcm_if_t intf_id, bcm_l3_ingress_t *info, void *cookie) { l3_cmd_ingress_print(unit, intf_id, info); return BCM_E_NONE; } /*! * \brief The callback of ingress interface traverse. * * \param [in] unit Unit number. * \param [in] intf_id Ingress interface ID. * \param [in] info Ingress interface info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_ingress_clear_trav_cb(int unit, bcm_if_t intf_id, bcm_l3_ingress_t *info, void *cookie) { return bcm_l3_ingress_destroy(unit, intf_id); } /*! * \brief Add a L3 ingress interface entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress_add(int unit, args_t *arg) { parse_table_t pt; bcm_l3_ingress_t intf; int intf_id = BCM_IF_INVALID; int def_intf_id = BCM_IF_INVALID; int vrf = 0, urpf_mode = 0, intf_class = 0, qos_map_id = 0, dscp_trust = 0; int urpf_dft_rt_chk_en = 0, pim_bidir = 0; int rv; cmd_result_t retcode; parse_table_init(unit, &pt); parse_table_add(&pt, "INTF", PQ_DFL | PQ_INT, (void *)&def_intf_id, (void *)&intf_id, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "UrpfMode", PQ_DFL | PQ_INT, 0, (void *)&urpf_mode, 0); parse_table_add(&pt, "INtfClass", PQ_DFL | PQ_INT, 0, (void *)&intf_class, 0); parse_table_add(&pt, "QOSmapID", PQ_DFL | PQ_INT, 0, (void *)&qos_map_id, 0); parse_table_add(&pt, "DSCPTrust", PQ_DFL | PQ_BOOL, 0, (void *)&dscp_trust, 0); parse_table_add(&pt, "UrpfDefaultRouteCheck", PQ_DFL | PQ_BOOL, 0, (void *)&urpf_dft_rt_chk_en, 0); parse_table_add(&pt, "PIM_BIDIR", PQ_DFL | PQ_BOOL, 0, (void *)&pim_bidir, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } bcm_l3_ingress_t_init(&intf); if (intf_id != BCM_IF_INVALID) { intf.flags |= BCM_L3_INGRESS_WITH_ID; } if (dscp_trust) { intf.flags |= BCM_L3_INGRESS_DSCP_TRUST; } if (urpf_dft_rt_chk_en) { intf.flags |= BCM_L3_INGRESS_URPF_DEFAULT_ROUTE_CHECK; } if (pim_bidir) { intf.flags |= BCM_L3_INGRESS_PIM_BIDIR; } intf.vrf = vrf; intf.urpf_mode = urpf_mode; intf.intf_class = intf_class; intf.qos_map_id = qos_map_id; rv = bcm_l3_ingress_create(unit, &intf, &intf_id); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding entry to L3 Ingress Interface table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete a L3 ingress interface entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress_delete(int unit, args_t *arg) { parse_table_t pt; bcm_if_t intf_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (intf_id == BCM_IF_INVALID) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } rv = bcm_l3_ingress_destroy(unit, intf_id); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting ingress interface (%d): %s\n", ARG_CMD(arg), intf_id, bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get a L3 ingress interface. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress_get(int unit, args_t *arg) { parse_table_t pt; bcm_l3_ingress_t intf; bcm_if_t intf_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (intf_id == BCM_IF_INVALID) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } bcm_l3_ingress_t_init(&intf); rv = bcm_l3_ingress_get(unit, intf_id, &intf); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting ingress interface (%d): %s\n", ARG_CMD(arg), intf_id, bcm_errmsg(rv)); return (CMD_FAIL); } cli_out("%-5s %-10s %-5s %-9s %-9s %-9s\n", "INTF", "Flag", "VRF", "URPF_MODE", "INTF_CLASS", "QOS_MAP_ID"); cli_out("-----------------------------------------------------------\n"); l3_cmd_ingress_print(unit, intf_id, &intf); return CMD_OK; } /*! * \brief Delete all L3 ingress interfaces. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress_clear(int unit, args_t *arg) { int rv; rv = bcm_l3_ingress_traverse(unit, l3_cmd_ingress_clear_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting all ingress interfaces: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 ingress interface entries. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress_show(int unit, args_t *arg) { int rv; cli_out("%-5s %-10s %-5s %-9s %-9s %-9s\n", "INTF", "Flag", "VRF", "URPF_MODE", "INTF_CLASS", "QOS_MAP_ID"); cli_out("-----------------------------------------------------------\n"); rv = bcm_l3_ingress_traverse(unit, l3_cmd_ingress_show_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error showing all ingress interfaces: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief L3 ingress interface cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ingress(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_ingress_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_ingress_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_ingress_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_ingress_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_ingress_show(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Print the egress interface info. * * \param [in] unit Unit number. * \param [in] info Egress interface info. * * \return none. */ static void l3_cmd_intf_print(int unit, bcm_l3_intf_t *info) { char mac_str[SAL_MACADDR_STR_LEN]; char str[20]; format_macaddr(mac_str, info->l3a_mac_addr); if (!ltsw_feature(unit, LTSW_FT_L3_EGRESS_DEFAULT_UNDERLAY)) { if (!ltsw_feature(unit, LTSW_FT_L3_HIER)) { if (info->l3a_intf_flags & BCM_L3_INTF_UNDERLAY) { sal_strcpy(str, "UnderLay"); } else { sal_strcpy(str, "OverLay"); } } else { if (info->l3a_intf_flags & BCM_L3_INTF_OVERLAY) { sal_strcpy(str, "OverLay"); } else { sal_strcpy(str, "UnderLay"); } } } else { sal_strcpy(str, " "); } cli_out("%-5d %-5d %-18s %-9s\n", info->l3a_intf_id, info->l3a_vid, mac_str, str); cli_out("\n"); } /*! * \brief Add a L3 egress interface entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf_add(int unit, args_t *arg) { parse_table_t pt; bcm_l3_intf_t intf; bcm_mac_t mac; bcm_if_t intf_id = BCM_IF_INVALID; int vid = 0, ul = 0; int rv; cmd_result_t retcode; sal_memset(mac, 0, sizeof(bcm_mac_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "Vlan", PQ_DFL | PQ_INT, 0, &vid, 0); parse_table_add(&pt, "MAC", PQ_DFL | PQ_MAC, 0, mac, 0); parse_table_add(&pt, "INtf", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); parse_table_add(&pt, "UnderLay", PQ_DFL | PQ_BOOL, 0, (void *)&ul, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } bcm_l3_intf_t_init(&intf); sal_memcpy(intf.l3a_mac_addr, mac, sizeof(bcm_mac_t)); intf.l3a_vid = (bcm_vlan_t)vid; if (intf_id != BCM_IF_INVALID) { intf.l3a_intf_id = intf_id; intf.l3a_flags |= BCM_L3_WITH_ID; } if (!bcmi_ltsw_property_get(unit, BCMI_CPN_L3_DISABLE_ADD_TO_ARL, 0)) { intf.l3a_flags |= BCM_L3_ADD_TO_ARL; } intf.l3a_intf_flags = ul ? BCM_L3_INTF_UNDERLAY : BCM_L3_INTF_OVERLAY; rv = bcm_l3_intf_create(unit, &intf); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding entry to L3 Egress Interface table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete a L3 egress interface entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf_delete(int unit, args_t *arg) { parse_table_t pt; bcm_l3_intf_t intf; bcm_if_t intf_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (intf_id == BCM_IF_INVALID) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = intf_id; rv = bcm_l3_intf_delete(unit, &intf); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting egress interface (%d): %s\n", ARG_CMD(arg), intf_id, bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get a L3 egress interface. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf_get(int unit, args_t *arg) { parse_table_t pt; bcm_l3_intf_t intf; bcm_if_t intf_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "INtf", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (intf_id == BCM_IF_INVALID) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = intf_id; rv = bcm_l3_intf_get(unit, &intf); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting egress interface (%d): %s\n", ARG_CMD(arg), intf_id, bcm_errmsg(rv)); return (CMD_FAIL); } cli_out("%-5s %-5s %-18s\n", "INTF", "VID", "MAC Address"); cli_out("----------------------------------------------\n"); l3_cmd_intf_print(unit, &intf); return CMD_OK; } /*! * \brief Delete all L3 egress interfaces. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf_clear(int unit, args_t *arg) { int rv; rv = bcm_l3_intf_delete_all(unit); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting all egress interfaces: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 route entries. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf_show(int unit, args_t *arg) { int i, rv; bcm_l3_info_t info; bcm_l3_intf_t intf; if ((rv = bcm_l3_info(unit, &info) < 0)) { cli_out("Error in L3 info access: %s\n", bcm_errmsg(rv)); return CMD_FAIL; } cli_out("%-5s %-5s %-18s\n", "INTF", "VID", "MAC Address"); cli_out("----------------------------------------------\n"); for (i = 1; i < info.l3info_max_intf; i++) { bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = i; rv = bcm_l3_intf_get(unit, &intf); if (BCM_SUCCESS(rv)) { l3_cmd_intf_print(unit, &intf); } else { continue; } } return CMD_OK; } /*! * \brief L3 egress interface cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_intf(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_intf_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_intf_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_intf_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_intf_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_intf_show(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Resolve the gport. * * \param [in] unit Unit number. * \param [in] gport Gport number. * \param [in] port Port number. * \param [in] modid Module ID. * \param [in] tgid Trunk ID. * \param [in] port_type Port type string. * * \return none. */ static int gport_resolve(int unit, bcm_gport_t gport, int *port, int *modid, int *tgid, char *port_type) { int mod_in, port_in; if (BCM_GPORT_IS_BLACK_HOLE(gport)) { sal_strcpy(port_type, "BlackHole"); } else if (BCM_GPORT_IS_TRUNK(gport)) { *tgid = BCM_GPORT_TRUNK_GET(gport); sal_strcpy(port_type, "trunk"); } else if (BCM_GPORT_IS_LOCAL(gport)) { *port = BCM_GPORT_LOCAL_GET(gport); BCM_IF_ERROR_RETURN (bcm_stk_my_modid_get(unit, modid)); } else if (BCM_GPORT_IS_DEVPORT(gport)) { *port = BCM_GPORT_DEVPORT_PORT_GET(gport); BCM_IF_ERROR_RETURN (bcm_stk_my_modid_get(unit, modid)); } else if (BCM_GPORT_IS_MODPORT(gport)) { mod_in = BCM_GPORT_MODPORT_MODID_GET(gport); port_in = BCM_GPORT_MODPORT_PORT_GET(gport); BCM_IF_ERROR_RETURN (bcm_stk_modmap_map(unit, BCM_STK_MODMAP_SET, mod_in, port_in, modid, port)); } else if (BCM_GPORT_IS_MPLS_PORT(gport)) { *port = BCM_GPORT_MPLS_PORT_ID_GET(gport); BCM_IF_ERROR_RETURN (bcm_stk_my_modid_get(unit, modid)); sal_strcpy(port_type, "mpls"); } else if (BCM_GPORT_IS_FLOW_PORT(gport)) { *port = BCM_GPORT_FLOW_PORT_ID_GET(gport); BCM_IF_ERROR_RETURN (bcm_stk_my_modid_get(unit, modid)); sal_strcpy(port_type, "flow"); } else { return BCM_E_PARAM; } return BCM_E_NONE; } /*! * \brief Print the egress object info. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * * \return none. */ static void l3_cmd_egress_print(int unit, int intf_id, bcm_l3_egress_t *info) { char mac_str[SAL_MACADDR_STR_LEN]; int port, tgid, modid, rv; char port_type[16] = {0}; port = -1; modid = -1; tgid = BCM_TRUNK_INVALID; format_macaddr(mac_str, info->mac_addr); if (BCM_GPORT_IS_SET(info->port)) { rv = gport_resolve(unit, info->port, &port, &modid, &tgid, port_type); if (BCM_FAILURE(rv)) { cli_out("Error: Invalid gport %d.\n", info->port); } } else { if (info->flags & BCM_L3_TGID) { sal_strcpy(port_type, "trunk"); } port = info->port; modid = info->module; tgid = info->trunk; } if (ltsw_feature(unit, LTSW_FT_L3_EGRESS_DEFAULT_UNDERLAY)) { cli_out("%d %18s %6d %5d %5s %6d %5d %4s\n", intf_id, mac_str, info->intf, ((info->flags & BCM_L3_TGID) ? tgid : port), port_type, modid, info->mtu, (info->flags & BCM_L3_DST_DISCARD) ? "yes" : "no"); } else { if (ltsw_feature(unit, LTSW_FT_L3_HIER)) { cli_out("%d %18s %6d %5d %5s %6d %5d %10s %4s\n", intf_id, mac_str, info->intf, ((info->flags & BCM_L3_TGID) ? tgid : port), port_type, modid, info->mtu, (sal_strcmp(port_type, "flow") == 0) ? "overlay" : "underlay", (info->flags & BCM_L3_DST_DISCARD) ? "yes" : "no"); } else { cli_out("%d %18s %6d %5d %5s %6d %5d %10s %4s\n", intf_id, mac_str, info->intf, ((info->flags & BCM_L3_TGID) ? tgid : port), port_type, modid, info->mtu, (info->flags2 & BCM_L3_FLAGS2_UNDERLAY) ? "underlay" : "overlay", (info->flags & BCM_L3_DST_DISCARD) ? "yes" : "no"); } } cli_out("\n"); } /*! * \brief The callback of egress object traverse. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_egress_show_trav_cb(int unit, bcm_if_t intf_id, bcm_l3_egress_t *info, void *cookie) { l3_cmd_egress_print(unit, intf_id, info); return BCM_E_NONE; } /*! * \brief The callback of egress object traverse. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_egress_clear_trav_cb(int unit, bcm_if_t intf_id, bcm_l3_egress_t *info, void *cookie) { return bcm_l3_egress_destroy(unit, intf_id); } /*! * \brief Add an L3 egress object entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress_add(int unit, args_t *arg) { parse_table_t pt; bcm_l3_egress_t intf; bcm_mac_t mac; bcm_port_t port = 0; bcm_module_t modid = 0; bcm_trunk_t trunk = -1; int l2tocpu = 0, ul = 0; bcm_if_t l3oif = BCM_IF_INVALID; int egr_id = BCM_IF_INVALID; uint32 flags = 0; int rv; cmd_result_t retcode; sal_memset(mac, 0, sizeof(bcm_mac_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "Mac", PQ_DFL | PQ_MAC, 0, (void *)mac, 0); parse_table_add(&pt, "Port", PQ_DFL | PQ_PORT, 0, (void *)&port, 0); parse_table_add(&pt, "MOdule", PQ_DFL | PQ_INT, 0, (void *)&modid, 0); parse_table_add(&pt, "Trunk", PQ_DFL | PQ_INT, 0, (void *)&trunk, 0); parse_table_add(&pt, "L2tocpu", PQ_DFL | PQ_BOOL, 0, (void *)&l2tocpu, 0); parse_table_add(&pt, "INTF", PQ_DFL | PQ_INT, 0, (void *)&l3oif, 0); parse_table_add(&pt, "EgrId", PQ_DFL | PQ_INT, 0, (void *)&egr_id, 0); parse_table_add(&pt, "UnderLay", PQ_DFL | PQ_BOOL, 0, (void *)&ul, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } bcm_l3_egress_t_init(&intf); if (egr_id > BCM_IF_INVALID) { flags |= BCM_L3_WITH_ID; } intf.intf = l3oif; sal_memcpy(intf.mac_addr, mac, sizeof(bcm_mac_t)); if (BCM_GPORT_IS_SET(port)) { intf.port = port; } else { intf.module = modid; if (trunk >= 0) { intf.flags |= BCM_L3_TGID; intf.trunk = trunk; } else { intf.port = port; } } if (l2tocpu) { intf.flags |= BCM_L3_L2TOCPU; } if (ul) { intf.flags2 |= BCM_L3_FLAGS2_UNDERLAY; } rv = bcm_l3_egress_create(unit, flags, &intf, &egr_id); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding L3 egress object: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete an L3 egress object. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress_delete(int unit, args_t *arg) { parse_table_t pt; bcm_if_t intf_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: EgrID=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "EgrID", PQ_DFL | PQ_INT, 0, (void *)&intf_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (intf_id == BCM_IF_INVALID) { cli_out("Expected command parameters: EgrID=id\n"); return (CMD_FAIL); } rv = bcm_l3_egress_destroy(unit, intf_id); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting L3 egress object (%d): %s\n", ARG_CMD(arg), intf_id, bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get an L3 egress object. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress_get(int unit, args_t *arg) { parse_table_t pt; bcm_l3_egress_t intf; bcm_if_t egr_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: EgrID=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "EgrID", PQ_DFL | PQ_INT, 0, (void *)&egr_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (egr_id == BCM_IF_INVALID) { cli_out("Expected command parameters: Intf=id\n"); return (CMD_FAIL); } bcm_l3_egress_t_init(&intf); rv = bcm_l3_egress_get(unit, egr_id, &intf); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting egress interface (%d): %s\n", ARG_CMD(arg), egr_id, bcm_errmsg(rv)); return (CMD_FAIL); } cli_out("%s %18s %6s %9s %6s %5s %10s %4s\n", "EgrID", " MAC Address", "Intf", "Port", "Module", "MTU", "Type", "Drop"); cli_out("---------------------------------------------------------------\n"); l3_cmd_egress_print(unit, egr_id, &intf); return CMD_OK; } /*! * \brief Delete all L3 ingress interfaces. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress_clear(int unit, args_t *arg) { int rv; rv = bcm_l3_egress_traverse(unit, l3_cmd_egress_clear_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting all L3 egress objects: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 egress object entries. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress_show(int unit, args_t *arg) { int rv; cli_out("%s %18s %6s %9s %6s %5s %10s %4s\n", "EgrID", " MAC Address", "Intf", "Port", "Module", "MTU", "Type", "Drop"); cli_out("---------------------------------------------------------------\n"); rv = bcm_l3_egress_traverse(unit, l3_cmd_egress_show_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error showing all egress objects: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief L3 egress object cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_egress(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_egress_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_egress_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_egress_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_egress_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_egress_show(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Print the ECMP object info. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * * \return none. */ static void l3_cmd_ecmp_print(int unit, bcm_l3_egress_ecmp_t *info, int member_cnt, bcm_l3_ecmp_member_t *member_arr) { int idx; int ul = false; if (!ltsw_feature(unit, LTSW_FT_L3_EGRESS_DEFAULT_UNDERLAY)) { if (ltsw_feature(unit, LTSW_FT_L3_HIER)) { ul = (info->ecmp_group_flags & BCM_L3_ECMP_OVERLAY) ? false : true; } else { ul = (info->ecmp_group_flags & BCM_L3_ECMP_UNDERLAY) ? true : false; } cli_out("ECMP group %d(%s):\n\t", info->ecmp_intf, ul ? "UnderLay" : "OverLay"); } else { cli_out("ECMP group %d:\n\t", info->ecmp_intf); } cli_out("Dynamic mode %d, Flags 0x%x, Max path %d\n\t", info->dynamic_mode, info->ecmp_group_flags, info->max_paths); cli_out("Interfaces: (member count %d)\n\t", member_cnt); for (idx = 0; idx < member_cnt; idx++) { cli_out("{"); cli_out("%d", member_arr[idx].egress_if); if (member_arr[idx].egress_if_2) { cli_out(" %d", member_arr[idx].egress_if_2); } cli_out("} "); if (idx && (!(idx % 10))) { cli_out("\n"); } } cli_out("\n"); } /*! * \brief The callback of ECMP traverse. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_ecmp_show_trav_cb(int unit, bcm_l3_egress_ecmp_t *info, int member_cnt, bcm_l3_ecmp_member_t *member_arr, void *cookie) { l3_cmd_ecmp_print(unit, info, member_cnt, member_arr); return BCM_E_NONE; } /*! * \brief The callback of ECMP traverse. * * \param [in] unit Unit number. * \param [in] intf_id Egress object ID. * \param [in] info Egress object info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_ecmp_clear_trav_cb(int unit, bcm_l3_egress_ecmp_t *info, int member_cnt, bcm_l3_ecmp_member_t *member_arr, void *cookie) { return bcm_l3_ecmp_destroy(unit, info->ecmp_intf); } /*! * \brief Add an L3 ECMP group. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_add(int unit, args_t *arg) { parse_table_t pt; bcm_l3_egress_ecmp_t ecmp; int grp_id = BCM_IF_INVALID; int max_paths = 0, dynamic_mode = 0, egr_if_cnt = 0, ul = 0; int ol_egr_if_arr[ECMP_MEMBER_MAX] = {0}; int ul_egr_if_arr[ECMP_MEMBER_MAX] = {0}; char ol_egr_if_str[ECMP_MEMBER_MAX][16]; char ul_egr_if_str[ECMP_MEMBER_MAX][16]; bcm_l3_ecmp_member_t member_arr[ECMP_MEMBER_MAX]; int i, rv; uint32 options = 0; cmd_result_t retcode; sal_memset(member_arr, 0, sizeof(bcm_l3_ecmp_member_t) * ECMP_MEMBER_MAX); parse_table_init(unit, &pt); parse_table_add(&pt, "GRouPID", PQ_DFL | PQ_INT, 0, (void *)&grp_id, 0); parse_table_add(&pt, "MaxPaths", PQ_DFL | PQ_INT, 0, (void *)&max_paths, 0); parse_table_add(&pt, "DynamicMode", PQ_DFL | PQ_INT, 0, (void *)&dynamic_mode, 0); parse_table_add(&pt, "UnderLay", PQ_DFL | PQ_BOOL, 0, (void *)&ul, 0); for (i = 0; i < ECMP_MEMBER_MAX; i++) { sal_sprintf(ol_egr_if_str[i], "OL_INTF%d", i); parse_table_add(&pt, ol_egr_if_str[i], PQ_DFL | PQ_INT, 0, (void *)&ol_egr_if_arr[i], 0); sal_sprintf(ul_egr_if_str[i], "UL_INTF%d", i); parse_table_add(&pt, ul_egr_if_str[i], PQ_DFL | PQ_INT, 0, (void *)&ul_egr_if_arr[i], 0); } if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } bcm_l3_egress_ecmp_t_init(&ecmp); if (grp_id > BCM_IF_INVALID) { options |= BCM_L3_ECMP_O_CREATE_WITH_ID; ecmp.ecmp_intf = grp_id; } if (!ul) { ecmp.ecmp_group_flags |= BCM_L3_ECMP_OVERLAY; } else { ecmp.ecmp_group_flags |= BCM_L3_ECMP_UNDERLAY; } ecmp.max_paths = max_paths; ecmp.dynamic_mode = dynamic_mode; for (i = 0; i < ECMP_MEMBER_MAX; i++) { if (!ol_egr_if_arr[i] && !ul_egr_if_arr[i]) { continue; } if (ol_egr_if_arr[i] > 0) { member_arr[egr_if_cnt].egress_if = ol_egr_if_arr[i]; } if (ul_egr_if_arr[i] > 0) { member_arr[egr_if_cnt].egress_if_2 = ul_egr_if_arr[i]; } egr_if_cnt++; } rv = bcm_l3_ecmp_create(unit, options, &ecmp, egr_if_cnt, member_arr); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding L3 ECMP group: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete an L3 ECMP group. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_delete(int unit, args_t *arg) { parse_table_t pt; bcm_if_t grp_id = BCM_IF_INVALID; int rv; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: GRouPID=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "GRouPID", PQ_DFL | PQ_INT, 0, (void *)&grp_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (grp_id == BCM_IF_INVALID) { cli_out("Expected command parameters: GRouPID=id\n"); return (CMD_FAIL); } rv = bcm_l3_ecmp_destroy(unit, grp_id); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting L3 ECMP group (%d): %s\n", ARG_CMD(arg), grp_id, bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get an L3 ECMP group. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_get(int unit, args_t *arg) { parse_table_t pt; bcm_l3_egress_ecmp_t ecmp; bcm_if_t grp_id = BCM_IF_INVALID; int egr_if_cnt = 0; bcm_l3_ecmp_member_t *member_arr = NULL; int rv, sz; cmd_result_t retcode; if (!ARG_CNT(arg)) { cli_out("Expected command parameters: GRoupID=id\n"); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "GRouPID", PQ_DFL | PQ_INT, 0, (void *)&grp_id, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (grp_id == BCM_IF_INVALID) { cli_out("Expected command parameters: GRouPID=id\n"); return (CMD_FAIL); } bcm_l3_egress_ecmp_t_init(&ecmp); ecmp.ecmp_intf = grp_id; rv = bcm_l3_ecmp_get(unit, &ecmp, 0, NULL, &egr_if_cnt); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting ECMP group (%d): %s\n", ARG_CMD(arg), grp_id, bcm_errmsg(rv)); return (CMD_FAIL); } if (egr_if_cnt) { sz = egr_if_cnt * sizeof(bcm_l3_ecmp_member_t); member_arr = sal_alloc(sz, "ecmp member"); if (member_arr == NULL) { cli_out("%s: ERROR: %s\n", ARG_CMD(arg), bcm_errmsg(BCM_E_MEMORY)); return (CMD_FAIL); } sal_memset(member_arr, 0, sz); rv = bcm_l3_ecmp_get(unit, &ecmp, egr_if_cnt, member_arr, &egr_if_cnt); if (BCM_FAILURE(rv)) { sal_free(member_arr); cli_out("%s: Error getting ECMP group (%d): %s\n", ARG_CMD(arg), grp_id, bcm_errmsg(rv)); return (CMD_FAIL); } } l3_cmd_ecmp_print(unit, &ecmp, egr_if_cnt, member_arr); if (!member_arr) { sal_free(member_arr); } return CMD_OK; } /*! * \brief Delete all L3 ECMP groups. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_clear(int unit, args_t *arg) { int rv; rv = bcm_l3_ecmp_traverse(unit, l3_cmd_ecmp_clear_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting all L3 ECMP groups: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 ECMP groups. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_show(int unit, args_t *arg) { int rv; rv = bcm_l3_ecmp_traverse(unit, l3_cmd_ecmp_show_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error showing all ECMP groups: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Add/delete an L3 ECMP member. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp_member_op(int unit, args_t *arg) { char *subcmd; parse_table_t pt; int grp_id = BCM_IF_INVALID; int ol_egr_if = BCM_IF_INVALID; int ul_egr_if = BCM_IF_INVALID; bcm_l3_ecmp_member_t member; int insert = 0; int rv; cmd_result_t retcode; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } else if(!sal_strcasecmp(subcmd, "insert")) { insert = true; } else if (!sal_strcasecmp(subcmd, "remove")) { insert = false; } else { cli_out("%s: Unsupported command to ECMP member.\n", ARG_CMD(arg)); return (CMD_FAIL); } parse_table_init(unit, &pt); parse_table_add(&pt, "GRouPID", PQ_DFL | PQ_INT, 0, (void *)&grp_id, 0); parse_table_add(&pt, "OL_INTF", PQ_DFL | PQ_INT, 0, (void *)&ol_egr_if, 0); parse_table_add(&pt, "UL_INTF", PQ_DFL | PQ_INT, 0, (void *)&ul_egr_if, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } bcm_l3_ecmp_member_t_init(&member); member.egress_if = ol_egr_if; member.egress_if_2 = ul_egr_if; if (insert) { rv = bcm_l3_ecmp_member_add(unit, grp_id, &member); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding member to ECMP groups: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } } else { rv = bcm_l3_ecmp_member_delete(unit, grp_id, &member); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting member from ECMP groups: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } } return CMD_OK; } /*! * \brief L3 ECMP cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_ecmp(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_ecmp_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_ecmp_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_ecmp_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_ecmp_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_ecmp_show(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "member")) { if ((rv = cmd_ltsw_l3_ecmp_member_op(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Print the host info. * * \param [in] unit Unit number. * \param [in] info host info. * * \return none. */ static void l3_cmd_host_print(int unit, bcm_l3_host_t *info) { char ip_str[IP6ADDR_STR_LEN + 3]; if (info->l3a_flags & BCM_L3_IP6) { format_ip6addr(ip_str, info->l3a_ip6_addr); cli_out("%-4d %-19s %-4d %-4d", info->l3a_vrf, ip_str, info->l3a_intf, info->l3a_ul_intf); } else { format_ipaddr(ip_str, info->l3a_ip_addr); cli_out("%-4d %-19s %-4d %-4d", info->l3a_vrf, ip_str, info->l3a_intf, info->l3a_ul_intf); } cli_out("\n"); } /*! * \brief The callback of host traverse. * * \param [in] unit Unit number. * \param [in] index Entry index. * \param [in] info Host info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_host_trav_cb(int unit, int index, bcm_l3_host_t *info, void *cookie) { cli_out("%-8d", index); l3_cmd_host_print(unit, info); return BCM_E_NONE; } /*! * \brief Add a L3 host entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host_add(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int vrf = 0, ol_intf = 0, ul_intf = 0, v6 = 0; bcm_l3_host_t host_info; parse_table_t pt; int rv, ecmp = 0; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "INTF", PQ_DFL | PQ_INT, 0, (void *)&ol_intf, 0); parse_table_add(&pt, "UL_INTF", PQ_DFL | PQ_INT, 0, (void *)&ul_intf, 0); parse_table_add(&pt, "ECMP", PQ_DFL | PQ_BOOL, 0, (void *)&ecmp, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_host_t_init(&host_info); if (v6) { sal_memcpy(host_info.l3a_ip6_addr, ip6_addr, BCM_IP6_ADDRLEN); host_info.l3a_flags |= BCM_L3_IP6; } else { host_info.l3a_ip_addr = ip_addr; } host_info.l3a_vrf = vrf; host_info.l3a_intf = ol_intf; host_info.l3a_ul_intf = ul_intf; if (ecmp) { host_info.l3a_flags |= BCM_L3_MULTIPATH; } rv = bcm_l3_host_add(unit, &host_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding host table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete a L3 host entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host_delete(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int vrf = 0, v6 = 0; bcm_l3_host_t host_info; parse_table_t pt; int rv; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_host_t_init(&host_info); if (v6) { sal_memcpy(host_info.l3a_ip6_addr, ip6_addr, BCM_IP6_ADDRLEN); host_info.l3a_flags |= BCM_L3_IP6; } else { host_info.l3a_ip_addr = ip_addr; } host_info.l3a_vrf = vrf; rv = bcm_l3_host_delete(unit, &host_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting host table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get a L3 host entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host_get(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int vrf = 0, v6 = 0; bcm_l3_host_t host_info; parse_table_t pt; int rv; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_host_t_init(&host_info); if (v6) { sal_memcpy(host_info.l3a_ip6_addr, ip6_addr, BCM_IP6_ADDRLEN); host_info.l3a_flags |= BCM_L3_IP6; } else { host_info.l3a_ip_addr = ip_addr; } host_info.l3a_vrf = vrf; rv = bcm_l3_host_find(unit, &host_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting host entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } cli_out("%3s %-19s %-4s %-4s\n", "VRF", "Net Addr", "INTF", "UL_INTF"); cli_out("--------------------------------------------\n"); l3_cmd_host_print(unit, &host_info); return CMD_OK; } /*! * \brief Delete all L3 host entries. * * Use option 'v6' to specify the host table to be cleared. * By default, only IPv4 host table will be cleared. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host_clear(int unit, args_t *arg) { int v6 = 0; bcm_l3_host_t host_info; parse_table_t pt; int rv; cmd_result_t retcode; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "V6", PQ_DFL | PQ_BOOL, 0, (void *)&v6, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } } bcm_l3_host_t_init(&host_info); if (v6) { host_info.l3a_flags |= BCM_L3_IP6; } rv = bcm_l3_host_delete_all(unit, &host_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error clearing host entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 host entries. * * Use option 'v6' to specify the host table to be shown. * By default, only show entries in IPv4 host table. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host_show(int unit, args_t *arg) { int v6 = 0; int start, end; parse_table_t pt; int rv; cmd_result_t retcode; uint32 flags = 0; bcm_l3_info_t l3info; start = end = 0; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "V6", PQ_DFL | PQ_BOOL, 0, (void *)&v6, 0); parse_table_add(&pt, "START", PQ_DFL | PQ_INT, 0, (void *)&start, 0); parse_table_add(&pt, "END", PQ_DFL | PQ_INT, 0, (void *)&end, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (v6) { flags = BCM_L3_IP6; } } if (!end) { rv = bcm_l3_info(unit, &l3info); if (BCM_FAILURE(rv)) { cli_out("%s: Error L3 info accessing: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } end = l3info.l3info_max_host; } cli_out("%8s %-19s %-4s %-4s\n", "VRF", "Net Addr", "INTF", "UL_INTF"); cli_out("--------------------------------------------\n"); rv = bcm_l3_host_traverse(unit, flags, start, end, l3_cmd_host_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error showing host entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief L3 host cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_host(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_host_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_host_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_host_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_host_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_host_show(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Print the route info. * * \param [in] unit Unit number. * \param [in] info Route info. * * \return none. */ static void l3_cmd_route_print(int unit, bcm_l3_route_t *info) { char ip_str[IP6ADDR_STR_LEN + 3]; char vrf_str[20]; int masklen; if (info->l3a_vrf == BCM_L3_VRF_GLOBAL) { sal_strcpy(vrf_str, "Global"); } else if (info->l3a_vrf == BCM_L3_VRF_OVERRIDE) { sal_strcpy(vrf_str, "Override"); } else { sal_sprintf(vrf_str, "%d", info->l3a_vrf); } if (info->l3a_flags & BCM_L3_IP6) { format_ip6addr(ip_str, info->l3a_ip6_net); masklen = bcm_ip6_mask_length(info->l3a_ip6_mask); cli_out("%-8s %-15s/%d %-4d %-4d", vrf_str, ip_str, masklen, info->l3a_intf, info->l3a_ul_intf); } else { format_ipaddr_mask(ip_str, info->l3a_subnet, info->l3a_ip_mask); cli_out("%-8s %-19s %-4d %-4d", vrf_str, ip_str, info->l3a_intf, info->l3a_ul_intf); } cli_out("\n"); } /*! * \brief The callback of route traverse. * * \param [in] unit Unit number. * \param [in] index Entry index. * \param [in] info Route info. * \param [in] cookie User data. * * \retval BCM_E_NONE No error. */ static int l3_cmd_route_trav_cb(int unit, int index, bcm_l3_route_t *info, void *cookie) { cli_out("%-8d", index); l3_cmd_route_print(unit, info); return BCM_E_NONE; } /*! * \brief Add a L3 route entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_add(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int masklen = 0, vrf = 0, ol_intf = 0, ul_intf = 0, v6 = 0, dst_discard = 0; bcm_l3_route_t route_info; parse_table_t pt; int rv; int replace = 0, ecmp = 0; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "MASKLEN", PQ_DFL | PQ_INT, 0, (void *)&masklen, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "INTF", PQ_DFL | PQ_INT, 0, (void *)&ol_intf, 0); parse_table_add(&pt, "UL_INTF", PQ_DFL | PQ_INT, 0, (void *)&ul_intf, 0); parse_table_add(&pt, "DstDiscard", PQ_DFL | PQ_BOOL, 0, (void *)&dst_discard, 0); parse_table_add(&pt, "Replace", PQ_DFL | PQ_BOOL, 0, (void *)&replace, 0); parse_table_add(&pt, "ECMP", PQ_DFL | PQ_BOOL, 0, (void *)&ecmp, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_route_t_init(&route_info); if (replace) { route_info.l3a_flags |= BCM_L3_REPLACE; } if (v6) { sal_memcpy(route_info.l3a_ip6_net, ip6_addr, BCM_IP6_ADDRLEN); bcm_ip6_mask_create(route_info.l3a_ip6_mask, masklen); route_info.l3a_flags |= BCM_L3_IP6; } else { route_info.l3a_subnet = ip_addr; route_info.l3a_ip_mask = bcm_ip_mask_create(masklen); } route_info.l3a_vrf = vrf; route_info.l3a_intf = ol_intf; route_info.l3a_ul_intf = ul_intf; if (ecmp) { route_info.l3a_flags |= BCM_L3_MULTIPATH; } if (dst_discard) { route_info.l3a_flags |= BCM_L3_DST_DISCARD; } rv = bcm_l3_route_add(unit, &route_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error adding route table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Delete a L3 route entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_delete(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int masklen = 0, vrf = 0, v6 = 0; bcm_l3_route_t route_info; parse_table_t pt; int rv; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "MASKLEN", PQ_DFL | PQ_INT, 0, (void *)&masklen, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_route_t_init(&route_info); if (v6) { sal_memcpy(route_info.l3a_ip6_net, ip6_addr, BCM_IP6_ADDRLEN); bcm_ip6_mask_create(route_info.l3a_ip6_mask, masklen); route_info.l3a_flags |= BCM_L3_IP6; } else { route_info.l3a_subnet = ip_addr; route_info.l3a_ip_mask = bcm_ip_mask_create(masklen); } route_info.l3a_vrf = vrf; rv = bcm_l3_route_delete(unit, &route_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error deleting route table: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Get a L3 route entry. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_get(int unit, args_t *arg) { bcm_ip_t ip_addr = 0; bcm_ip6_t ip6_addr; int masklen = 0, vrf = 0, v6 = 0; bcm_l3_route_t route_info; parse_table_t pt; int rv; sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); parse_table_init(unit, &pt); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "IP6", PQ_DFL | PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "MASKLEN", PQ_DFL | PQ_INT, 0, (void *)&masklen, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); if (!ARG_CNT(arg)) { /* Display settings */ cli_out("Current settings:\n"); parse_eq_format(&pt); parse_arg_eq_done(&pt); return CMD_OK; } if (parse_arg_eq(arg, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(arg), ARG_CUR(arg)); parse_arg_eq_done(&pt); return CMD_FAIL; } if (pt.pt_entries[1].pq_type & PQ_PARSED) { v6 = true; } parse_arg_eq_done(&pt); bcm_l3_route_t_init(&route_info); if (v6) { sal_memcpy(route_info.l3a_ip6_net, ip6_addr, BCM_IP6_ADDRLEN); bcm_ip6_mask_create(route_info.l3a_ip6_mask, masklen); route_info.l3a_flags |= BCM_L3_IP6; } else { route_info.l3a_subnet = ip_addr; route_info.l3a_ip_mask = bcm_ip_mask_create(masklen); } route_info.l3a_vrf = vrf; rv = bcm_l3_route_get(unit, &route_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error getting route entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } cli_out("%3s %-19s %-4s %-4s\n", "VRF", "Net Addr", "INTF", "UL_INTF"); cli_out("--------------------------------------------\n"); l3_cmd_route_print(unit, &route_info); return CMD_OK; } /*! * \brief Delete all L3 route entries. * * Use option 'v6' to specify the route table to be cleared. * By default, only IPv4 route table will be cleared. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_clear(int unit, args_t *arg) { int v6 = 0; bcm_l3_route_t route_info; parse_table_t pt; int rv; cmd_result_t retcode; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "V6", PQ_DFL | PQ_BOOL, 0, (void *)&v6, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } } bcm_l3_route_t_init(&route_info); if (v6) { route_info.l3a_flags |= BCM_L3_IP6; } rv = bcm_l3_route_delete_all(unit, &route_info); if (BCM_FAILURE(rv)) { cli_out("%s: Error clearing route entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Show L3 route entries. * * Use option 'v6' to specify the route table to be shown. * By default, only show entries in IPv4 route table. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_show(int unit, args_t *arg) { int v6 = 0; int start, end; parse_table_t pt; int rv; cmd_result_t retcode; uint32 flags = 0; bcm_l3_info_t l3info; start = end = 0; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "V6", PQ_DFL | PQ_BOOL, 0, (void *)&v6, 0); parse_table_add(&pt, "START", PQ_DFL | PQ_INT, 0, (void *)&start, 0); parse_table_add(&pt, "END", PQ_DFL | PQ_INT, 0, (void *)&end, 0); if(!parseEndOk(arg, &pt, &retcode)) { return retcode; } if (v6) { flags = BCM_L3_IP6; } } if (!end) { rv = bcm_l3_info(unit, &l3info); if (BCM_FAILURE(rv)) { cli_out("%s: Error L3 info accessing: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } end = l3info.l3info_max_route; } cli_out("%7s %-8s %-18s %4s %4s\n", " ", "VRF", "Net Addr", "INTF", "UL_INTF"); cli_out("--------------------------------------------\n"); rv = bcm_l3_route_traverse(unit, flags, start, end, l3_cmd_route_trav_cb, NULL); if (BCM_FAILURE(rv)) { cli_out("%s: Error showing route entry: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return (CMD_FAIL); } return CMD_OK; } /*! * \brief Add a time measurement to a perf_data_t instance. * * \param [in] perf Performance data. * \param [in] duration Time measurement. * * \return none. */ static void route_perf_data_add(route_perf_data_t *perf, int duration) { if (perf->count == 0) { perf->count = 1; perf->min = duration; perf->max = duration; perf->total = duration; } else { perf->count++; if (duration > perf->max) { perf->max = duration; } if (duration < perf->min) { perf->min = duration; } perf->total += duration; } } /*! * \brief Print performance data. * * \param [in] perf Performance data. * \param [in] route_cnt Added route number. * \param [in] label Label. * * \return none. */ static void route_perf_data_print(route_perf_data_t *perf, int route_cnt, const char *label) { if( perf->count > 0) { /*int u_avg = perf->total / perf->count;*/ uint32 temp; temp = route_cnt * perf->count; if (temp > 4294) { uint32 temp2 = 0; uint32 rem = 0, divn; while ((int)temp > 0) { divn = (temp > 2147) ? 2147 : temp; divn = divn * 1000000; temp2 += (divn + rem) / perf->total; rem = (divn + rem) % perf->total; temp -= 2147; } temp = temp2; } else { temp = temp * 1000000 / perf->total; } cli_out(" %7d ", temp); } else { cli_out(" - "); } } /*! * \brief Preparation for route performance test. * * \param [in] unit Unit number. * * \retval BCM_E_NONE No error. */ static int route_perf_test_setup(int unit) { int rv; bcm_l3_intf_t l3_intf; bcm_l3_egress_t egr_obj; bcm_if_t l3_intf_id; bcm_mac_t smac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; bcm_mac_t dmac = {0x00, 0x00, 0x00, 0x00, 0xfe, 0x01}; int vrf_arr[] = {ROUTE_PERF_VRF, BCM_L3_VRF_GLOBAL, BCM_L3_VRF_OVERRIDE}; int i = 0; bcm_l3_vrf_route_data_mode_t dmode; /* Turn off back ground threads */ sh_process_command(unit, "l2 learn off"); sh_process_command(unit, "l2 age off"); sh_process_command(unit, "linkscan off"); sh_process_command(unit, "counter off"); l3_intf_id = 1; /* L3 Interface */ bcm_l3_intf_t_init(&l3_intf); sal_memcpy(l3_intf.l3a_mac_addr, smac, sizeof(smac)); l3_intf.l3a_flags = BCM_L3_WITH_ID; l3_intf.l3a_intf_id = l3_intf_id; l3_intf.l3a_vid = 1; rv = bcm_l3_intf_create(unit, &l3_intf); if (BCM_FAILURE(rv) && (rv != BCM_E_EXISTS)) { cli_out("UT Route: Create L3 intf failed: %s\n", bcm_errmsg(rv)); return rv; } /* L3 Egress */ bcm_l3_egress_t_init(&egr_obj); egr_obj.intf = l3_intf_id; egr_obj.port = 1; sal_memcpy(egr_obj.mac_addr, dmac, sizeof(dmac)); rv = bcm_l3_egress_create(unit, 0, &egr_obj, &egr_obj_id[unit]); if (BCM_FAILURE(rv) && (rv != BCM_E_EXISTS)) { cli_out("UT Route: Error creating egress object: %s\n", bcm_errmsg(rv)); return rv; } bcm_l3_egress_t_init(&egr_obj); dmac[5]++; egr_obj.intf = l3_intf_id; egr_obj.port = 2; sal_memcpy(egr_obj.mac_addr, dmac, sizeof(dmac)); rv = bcm_l3_egress_create(unit, 0, &egr_obj, &egr_obj_id2[unit]); if (BCM_FAILURE(rv) && (rv != BCM_E_EXISTS)) { cli_out("UT Route: Error creating egress object: %s\n", bcm_errmsg(rv)); return rv; } for (i = 0; i < COUNTOF(vrf_arr); i ++) { rv = bcm_l3_vrf_route_data_mode_get(unit, vrf_arr[i], 0, &dmode); if (BCM_SUCCESS(rv)) { alpm_dmode[i][0] = dmode; } } for (i = 0; i < COUNTOF(vrf_arr); i ++) { rv = bcm_l3_vrf_route_data_mode_get(unit, vrf_arr[i], BCM_L3_IP6, &dmode); if (BCM_SUCCESS(rv)) { alpm_dmode[i][1] = dmode; } } return BCM_E_NONE; } /*! * \brief Operate IPv4 route table through LT interfaces. * * \param [in] unit Unit number. * \param [in] op Operation code. * \param [in] vrf VRF. * \param [in] ip IP address. * \param [in] ip_mask IP mask. * \param [in] intf Egress object ID. * \param [in] alpm_dmode alpm data mode array. * * \retval BCM_E_NONE No error. */ static int route_perf_v4_lt_op( int unit, bcmi_ltsw_l3_route_perf_opcode_t op, int vrf, uint32 ip, uint32 ip_mask, int intf, int (*alpm_dmode)[2]) { int rv; rv = bcmi_l3_route_perf_v4_lt_op(unit, op, vrf, ip, ip_mask, intf, alpm_dmode); return rv; } /*! * \brief Operate IPv4 route table. * * \param [in] unit Unit number. * \param [in] op Operation code. * \param [in] use_api Use BCM API. * \param [in] set_idx Index of set. * \param [in] rpd Pointer to performance data. * \param [in] vrf Vrf value. * \param [out] route_cnt Added route number. * * \retval BCM_E_NONE No error. */ static int route_perf_v4_op_test(int unit, bcmi_ltsw_l3_route_perf_opcode_t op, int use_api, int set_idx, route_perf_data_t *rpd, int vrf, int *route_cnt) { int rv = BCM_E_NONE; int start, end, duration = 0; bcm_l3_route_t route_info; uint32_t ip, start_ip = 0x01010101; uint32 ip_mask = 0xffffffff; int loop = 4096; int loop_ip = 1024; int i, j, intf; uint32 prfx[4] = {22, 23, 24, 20}; uint32 mask[4] = {0xfffffc00, 0xfffffe00, 0xffffff00, 0xfffff000}; uint32 ipv4[4] = {0x02020202, 0x29020202, 0x61020202, 0x8C010101}; uint32 base_ip; int (*op_func[BCMI_LTSW_RP_OPCODE_NUM])(int, bcm_l3_route_t *) = { bcm_l3_route_add, bcm_l3_route_add, bcm_l3_route_get, bcm_l3_route_delete }; *route_cnt = 0; bcm_l3_route_t_init(&route_info); start = sal_time_usecs(); ip = start_ip + set_idx * loop; for (i = 0; i < loop; i++) { if (use_api) { route_info.l3a_vrf = vrf; route_info.l3a_subnet = ip; route_info.l3a_ip_mask= ip_mask; route_info.l3a_intf = egr_obj_id[unit]; if (op == BCMI_LTSW_RP_OPCODE_UPD) { route_info.l3a_flags = BCM_L3_REPLACE; route_info.l3a_intf = egr_obj_id2[unit]; } rv = op_func[op](unit, &route_info); } else { if (op == BCMI_LTSW_RP_OPCODE_UPD) { intf = egr_obj_id2[unit] - 100000;/* _SHR_L3_EGRESS_IDX_MIN */ } else { intf = egr_obj_id[unit] - 100000; } rv = route_perf_v4_lt_op(unit, op, vrf, ip, ip_mask, intf, alpm_dmode); } if (BCM_FAILURE(rv)) { end = sal_time_usecs(); duration = end - start; goto exit; } else { *route_cnt += 1; } ip++; } end = sal_time_usecs(); duration = end - start; for (j = 0; j < 4; j++) { start = sal_time_usecs(); for (i = 0; i < loop_ip; i++) { base_ip = ((loop_ip + i + loop_ip * set_idx) << (32 - prfx[j])); ip = base_ip + ipv4[j]; ip_mask = mask[j]; if (use_api) { route_info.l3a_vrf = vrf; route_info.l3a_subnet = ip; route_info.l3a_ip_mask= ip_mask; route_info.l3a_intf = egr_obj_id[unit]; if (op == BCMI_LTSW_RP_OPCODE_UPD) { route_info.l3a_flags = BCM_L3_REPLACE; route_info.l3a_intf = egr_obj_id2[unit]; } rv = op_func[op](unit, &route_info); } else { if (op == BCMI_LTSW_RP_OPCODE_UPD) { intf = egr_obj_id2[unit] - 100000; } else { intf = egr_obj_id[unit] - 100000; } rv = route_perf_v4_lt_op(unit, op, vrf, ip, ip_mask, intf, alpm_dmode); } if (BCM_FAILURE(rv)) { end = sal_time_usecs(); duration += (end - start); goto exit; } else { *route_cnt += 1; } } end = sal_time_usecs(); duration += (end - start); } exit: route_perf_data_add(&rpd[set_idx], duration); return rv; } /*! * \brief Clean up resource allocated for route performance test. * * \param [in] unit Unit number. * * \retval None. */ static void route_perf_test_clean(int unit) { int rv; bcm_l3_intf_t intf; rv = bcm_l3_egress_destroy(unit, egr_obj_id2[unit]); if (BCM_FAILURE(rv) && (rv != BCM_E_BUSY) && (rv != BCM_E_NOT_FOUND)) { cli_out("UT Route: Error deleting egress obj2: %s\n", bcm_errmsg(rv)); } rv = bcm_l3_egress_destroy(unit, egr_obj_id[unit]); if (BCM_FAILURE(rv) && (rv != BCM_E_BUSY) && (rv != BCM_E_NOT_FOUND)) { cli_out("UT Route: Error deleting egress obj: %s\n", bcm_errmsg(rv)); } bcm_l3_intf_t_init(&intf); intf.l3a_intf_id = 1; rv = bcm_l3_intf_delete(unit, &intf); if (BCM_FAILURE(rv) && (rv != BCM_E_BUSY) && (rv != BCM_E_NOT_FOUND)) { cli_out("UT Route: Error deleting interface: %s\n", bcm_errmsg(rv)); } /* Turn on back ground threads */ sh_process_command(unit, "l2 learn on"); sh_process_command(unit, "l2 age on"); sh_process_command(unit, "linkscan on"); sh_process_command(unit, "counter on"); return; } /*! * \brief Performance test on IPv4 route table. * * \param [in] unit Unit number. * \param [in] ops Bitmap of operation code. * \param [in] loops Number of runs. * \param [in] nsets Number of sets. * \param [in] use_api Use BCM API. * \param [in] vrf Vrf value. * * \retval BCM_E_NONE No error. */ static int route_perf_v4_test(int unit, int ops, int loops, int nsets, int use_api, int vrf) { int run, i, sz, op; int route_add = 0, set_size = 0, route_cnt = 0, tot_route = 0; route_perf_data_t *rpd[BCMI_LTSW_RP_OPCODE_NUM], *ptr; char *data, *pd = NULL; int rv = BCM_E_NONE; bcm_l3_route_t route_info; sz = sizeof(route_perf_data_t) * nsets; data = sal_alloc((sz * BCMI_LTSW_RP_OPCODE_NUM), "bcmRoutePerfData"); if (!data) { return BCM_E_MEMORY; } sal_memset(data, 0, (sz * BCMI_LTSW_RP_OPCODE_NUM)); for (i = 0; i < BCMI_LTSW_RP_OPCODE_NUM; i++) { rpd[i] = (route_perf_data_t *)(data + i * sz); } for (run = 0; run < loops; run++) { if (ops & (1 << BCMI_LTSW_RP_OPCODE_ADD)) { /* Add default route */ if (use_api) { bcm_l3_route_t_init(&route_info); route_info.l3a_vrf = vrf; route_info.l3a_subnet = 0; route_info.l3a_ip_mask= 0; route_info.l3a_intf = egr_obj_id[unit]; rv = bcm_l3_route_add(unit, &route_info); } else { rv = route_perf_v4_lt_op(unit, BCMI_LTSW_RP_OPCODE_ADD, vrf, 0, 0, egr_obj_id[unit] - 100000, alpm_dmode); } if (BCM_FAILURE(rv) && (rv != BCM_E_EXISTS)) { cli_out("Failed to add IPv4 default route (rv = %d)\n", rv); goto exit; } } route_add = 0; for (op = 0; op < BCMI_LTSW_RP_OPCODE_NUM; op++) { if (!(ops & (1 << op))) { continue; } for (i = 0; i < nsets; i++) { rv = route_perf_v4_op_test(unit, op, use_api, i, rpd[op], vrf, &route_cnt); if (op == BCMI_LTSW_RP_OPCODE_ADD) { route_add += route_cnt; if (i == 0) { set_size = route_cnt; } } if (BCM_FAILURE(rv)) { if (op == BCMI_LTSW_RP_OPCODE_ADD) { nsets = i + 1; } break; } } } if (ops & (1 << BCMI_LTSW_RP_OPCODE_DEL)) { /* Delete default route */ if (use_api) { rv = bcm_l3_route_delete(unit, &route_info); } else { rv = route_perf_v4_lt_op(unit, BCMI_LTSW_RP_OPCODE_DEL, vrf, 0, 0, 0, alpm_dmode); } if (BCM_FAILURE(rv)) { cli_out("Failed to delete IPv4 default route (rv = %d)\n", rv); goto exit; } } /* For test purpose, flush heap memory by allocate 16MB and free, * in order to trigger garbage defragmentation before next run. */ pd = sal_alloc(1024*1024*16, "alpm_mem_flush"); if (pd) { sal_free(pd); pd = NULL; } } tot_route = route_add + 1; /* include the default route. */ cli_out("IPv4 (%s) performance test: Added routes = %d\n", (vrf == BCM_L3_VRF_GLOBAL ? "Global" : (vrf == BCM_L3_VRF_OVERRIDE ? "Override" : "Private")), tot_route); cli_out(" Set RouteCnt TotRoute RPS:Add Update Lookup Delete \n"); tot_route = 0; for (i = 0; i < nsets; i++) { if ((tot_route + set_size) > route_add) { route_cnt = route_add - tot_route; } else { route_cnt = set_size; } tot_route += route_cnt; cli_out("%3d %7d %7d ", i, route_cnt, tot_route); for (op = 0; op < BCMI_LTSW_RP_OPCODE_NUM; op++) { ptr = rpd[op]; route_perf_data_print(&ptr[i], route_cnt, ""); } cli_out("\n"); } cli_out("\n"); exit: if (data) { sal_free(data);; } return rv; } /*! * \brief Operate IPv6 route table through LT interfaces. * * \param [in] unit Unit number. * \param [in] op Operation code. * \param [in] vrf VRF. * \param [in] v6 IP address. * \param [in] v6_mask IP mask. * \param [in] intf Egress object ID. * \param [in] alpm_dmode alpm data mode array. * * \retval BCM_E_NONE No error. */ static int route_perf_v6_lt_op( int unit, bcmi_ltsw_l3_route_perf_opcode_t op, int vrf, uint64_t *v6, uint64_t *v6_mask, int intf, int (*alpm_dmode)[2]) { int rv; rv = bcmi_l3_route_perf_v6_lt_op(unit, op, vrf, v6, v6_mask, intf, alpm_dmode); return rv; } /*! * \brief Operate IPv6 route table. * * \param [in] unit Unit number. * \param [in] op Operation code. * \param [in] use_api Use BCM API. * \param [in] set_idx Index of set. * \param [in] rpd Pointer to performance data. * \param [in] vrf Vrf value. * \param [out] route_cnt Added route number. * * \retval BCM_E_NONE No error. */ static int route_perf_v6_op_test(int unit, bcmi_ltsw_l3_route_perf_opcode_t op, int use_api, int set_idx, route_perf_data_t *rpd, int vrf, int *route_cnt) { int rv = BCM_E_NONE; int start, end, duration = 0; bcm_l3_route_t route_info; uint64_t ip[2], start_ip[2] = {0x0101010101010101, 0x0101010101010101}; uint64_t ip_mask[2] = {0xffffffffffffffff, 0xffffffffffffffff}; int loop = 4096; int loop_ip = 1024; int i, j, intf, pos; uint32 prfx[4] = {118, 119, 120, 116}; uint64_t mask[4][2] = {{0xfffffffffffffc00, 0xffffffffffffffff}, {0xfffffffffffffe00, 0xffffffffffffffff}, {0xffffffffffffff00, 0xffffffffffffffff}, {0xfffffffffffff000, 0xffffffffffffffff} }; uint64_t ipv6[4][2] = {{0x0202020202020202, 0x0202020202020202}, {0x0202020202020202, 0x2902020202020202}, {0x0202020202020202, 0x6102020202020202}, {0x0202020202020202, 0x8c02020202020202}, }; int (*op_func[BCMI_LTSW_RP_OPCODE_NUM])(int, bcm_l3_route_t *) = { bcm_l3_route_add, bcm_l3_route_add, bcm_l3_route_get, bcm_l3_route_delete }; if (!bcmi_ltsw_property_get(unit, BCMI_CPN_IPV6_LPM_128B_ENABLE, 1)) { pos = 1; start_ip[0] = 0; ip_mask[0] = 0; for (i = 0; i < 4; i++) { prfx[i] = 64 - (i+1)*2; mask[i][1] &= ~((1 << ((i+1)*2)) - 1); mask[i][0] = 0; } } else { pos = 0; } ip[1] = start_ip[1]; ip[0] = start_ip[0]; ip[pos] += set_idx * loop; *route_cnt = 0; bcm_l3_route_t_init(&route_info); start = sal_time_usecs(); for (i = 0; i < loop; i++) { if (use_api) { route_info.l3a_flags = BCM_L3_IP6; route_info.l3a_vrf = vrf; bcmi_ltsw_util_uint64_to_ip6(&(route_info.l3a_ip6_net), ip); bcmi_ltsw_util_uint64_to_ip6(&(route_info.l3a_ip6_mask), ip_mask); route_info.l3a_intf = egr_obj_id[unit]; if (op == BCMI_LTSW_RP_OPCODE_UPD) { route_info.l3a_flags |= BCM_L3_REPLACE; route_info.l3a_intf = egr_obj_id2[unit]; } rv = op_func[op](unit, &route_info); } else { if (op == BCMI_LTSW_RP_OPCODE_UPD) { intf = egr_obj_id2[unit] - 100000;/* _SHR_L3_EGRESS_IDX_MIN */ } else { intf = egr_obj_id[unit] - 100000; } rv = route_perf_v6_lt_op(unit, op, vrf, ip, ip_mask, intf, alpm_dmode); } if (BCM_FAILURE(rv)) { end = sal_time_usecs(); duration = end - start; goto exit; } else { *route_cnt += 1; } ip[pos]++; } end = sal_time_usecs(); duration = end - start; for (j = 0; j < 4; j++) { start = sal_time_usecs(); for (i = 0; i < loop_ip; i++) { ip[1] = ipv6[j][1]; ip_mask[1] = mask[j][1]; ip[0] = ipv6[j][0]; ip_mask[0] = mask[j][0]; ip[pos] += ((loop_ip + i + loop_ip * set_idx) << (128 - prfx[j])); if (use_api) { route_info.l3a_flags = BCM_L3_IP6; route_info.l3a_vrf = vrf; bcmi_ltsw_util_uint64_to_ip6(&(route_info.l3a_ip6_net), ip); bcmi_ltsw_util_uint64_to_ip6(&(route_info.l3a_ip6_mask), ip_mask); route_info.l3a_intf = egr_obj_id[unit]; if (op == BCMI_LTSW_RP_OPCODE_UPD) { route_info.l3a_flags |= BCM_L3_REPLACE; route_info.l3a_intf = egr_obj_id2[unit]; } rv = op_func[op](unit, &route_info); } else { if (op == BCMI_LTSW_RP_OPCODE_UPD) { intf = egr_obj_id2[unit] - 100000; } else { intf = egr_obj_id[unit] - 100000; } rv = route_perf_v6_lt_op(unit, op, vrf, ip, ip_mask, intf, alpm_dmode); } if (BCM_FAILURE(rv)) { end = sal_time_usecs(); duration += (end - start); goto exit; } else { *route_cnt += 1; } } end = sal_time_usecs(); duration += (end - start); } exit: route_perf_data_add(&rpd[set_idx], duration); return rv; } /*! * \brief Performance test on IPv6 route table. * * \param [in] unit Unit number. * \param [in] ops Bitmap of operation code. * \param [in] loops Number of runs. * \param [in] nsets Number of sets. * \param [in] use_api Use BCM API. * \param [in] vrf Vrf value. * * \retval BCM_E_NONE No error. */ static int route_perf_v6_test(int unit, int ops, int loops, int nsets, int use_api, int vrf) { int run, i, sz, op; int route_add = 0, set_size = 0, route_cnt = 0, tot_route = 0; route_perf_data_t *rpd[BCMI_LTSW_RP_OPCODE_NUM], *ptr; char *data = NULL, *pd = NULL; int rv = BCM_E_NONE; bcm_l3_route_t route_info; uint64_t v6_zero[2] = {0, 0}; sz = sizeof(route_perf_data_t) * nsets; data = sal_alloc((sz * BCMI_LTSW_RP_OPCODE_NUM), "bcmRoutePerfData"); if (!data) { return BCM_E_MEMORY; } sal_memset(data, 0, (sz * BCMI_LTSW_RP_OPCODE_NUM)); for (i = 0; i < BCMI_LTSW_RP_OPCODE_NUM; i++) { rpd[i] = (route_perf_data_t *)(data + i * sz); } for (run = 0; run < loops; run++) { if (ops & (1 << BCMI_LTSW_RP_OPCODE_ADD)) { /* Add default route */ if (use_api) { bcm_l3_route_t_init(&route_info); route_info.l3a_flags = BCM_L3_IP6; route_info.l3a_vrf = vrf; route_info.l3a_intf = egr_obj_id[unit]; rv = bcm_l3_route_add(unit, &route_info); } else { rv = route_perf_v6_lt_op(unit, BCMI_LTSW_RP_OPCODE_ADD, vrf, v6_zero, v6_zero, egr_obj_id[unit] - 100000, alpm_dmode); } if (BCM_FAILURE(rv)) { cli_out("Failed to add IPv6 default route (rv = %d)\n", rv); goto exit; } } route_add = 0; for (op = 0; op < BCMI_LTSW_RP_OPCODE_NUM; op++) { if (!(ops & (1 << op))) { continue; } for (i = 0; i < nsets; i++) { rv = route_perf_v6_op_test(unit, op, use_api, i, rpd[op], vrf, &route_cnt); if (op == BCMI_LTSW_RP_OPCODE_ADD) { route_add += route_cnt; if (i == 0) { set_size = route_cnt; } } if (BCM_FAILURE(rv)) { if (op == BCMI_LTSW_RP_OPCODE_ADD) { nsets = i + 1; } break; } } } if (ops & (1 << BCMI_LTSW_RP_OPCODE_DEL)) { /* Delete default route */ if (use_api) { rv = bcm_l3_route_delete(unit, &route_info); } else { rv = route_perf_v6_lt_op(unit, BCMI_LTSW_RP_OPCODE_DEL, vrf, v6_zero, v6_zero, 0, alpm_dmode); } if (BCM_FAILURE(rv)) { cli_out("Failed to delete IPv6 default route (rv = %d)\n", rv); goto exit; } } /* For test purpose, flush heap memory by allocate 16MB and free, * in order to trigger garbage defragmentation before next run. */ pd = sal_alloc(1024*1024*16, "alpm_mem_flush"); if (pd) { sal_free(pd); pd = NULL; } } tot_route = route_add + 1; /* include the default route. */ cli_out("IPv6 (%s) performance test: Added routes = %d\n", (vrf == BCM_L3_VRF_GLOBAL ? "Global" : (vrf == BCM_L3_VRF_OVERRIDE ? "Override" : "Private")), tot_route); cli_out(" Set RouteCnt TotRoute RPS:Add Update Lookup Delete \n"); tot_route = 0; for (i = 0; i < nsets; i++) { if ((tot_route + set_size) > route_add) { route_cnt = route_add - tot_route; } else { route_cnt = set_size; } tot_route += route_cnt; cli_out("%3d %7d %7d ", i, route_cnt, tot_route); for (op = 0; op < BCMI_LTSW_RP_OPCODE_NUM; op++) { ptr = rpd[op]; route_perf_data_print(&ptr[i], route_cnt, ""); } cli_out("\n"); } cli_out("\n"); exit: if (data) { sal_free(data);; } return rv; } /*! * \brief Route performance test. * * \param [in] unit Unit number. * \param [in] ip_type IP type. * \param [in] ops Bitmap of operation code. * \param [in] loops Number of runs. * \param [in] nsets Number of sets. * \param [in] use_api Use BCM API. * \param [in] vrf_bmp Bitmap of VRF. * * \retval BCM_E_NONE No error. */ static int ltsw_l3_route_perf(int unit, int ip_type, int ops, int loops, int nsets, int use_api, int vrf_bmp) { int nonset, rv = BCM_E_NONE; int vrf_arr[] = {ROUTE_PERF_VRF, BCM_L3_VRF_GLOBAL, BCM_L3_VRF_OVERRIDE}; int i = 0; /* OP_ADD is must */ if ((ops & (1 << BCMI_LTSW_RP_OPCODE_ADD)) == 0) { return SHR_E_PARAM; } /* Force loops=1 if not OP_DEL */ if ((ops & (1 << BCMI_LTSW_RP_OPCODE_DEL)) == 0) { loops = 1; } rv = route_perf_test_setup(unit); if (BCM_FAILURE(rv)) { goto exit; } nonset = (nsets == -1); if ((ip_type == 1) || (ip_type == 3)) { /* IPv4 first */ if (nonset) { nsets = 130; } for (i = 0; i < COUNTOF(vrf_arr); i ++) { if (!(vrf_bmp & (1 << i))) { continue; } rv = route_perf_v4_test(unit, ops, loops, nsets, use_api, vrf_arr[i]); if (BCM_FAILURE(rv) && rv != BCM_E_RESOURCE) { goto exit; } } } if (ip_type != 1) { /* IPv6 */ if (nonset) { nsets = 300; } for (i = 0; i < COUNTOF(vrf_arr); i ++) { if (!(vrf_bmp & (1 << i))) { continue; } rv = route_perf_v6_test(unit, ops, loops, nsets, use_api, vrf_arr[i]); if (BCM_FAILURE(rv) && rv != BCM_E_RESOURCE) { goto exit; } } } if (ip_type == 4) { /* then IPv4 */ if (nonset) { nsets = 130; } for (i = 0; i < COUNTOF(vrf_arr); i ++) { if (!(vrf_bmp & (1 << i))) { continue; } rv = route_perf_v4_test(unit, ops, loops, nsets, use_api, vrf_arr[i]); if (BCM_FAILURE(rv) && rv != BCM_E_RESOURCE) { goto exit; } } } exit: route_perf_test_clean(unit); return BCM_E_NONE; } /*! * \brief Route performance test. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route_perf(int unit, args_t *arg) { int ip_type, loops, nsets, op_bitmap, vrf_bmp, use_api, rv; cmd_result_t cmd_rv = CMD_OK; parse_table_t pt; int alpm_temp, alpm_mode; ip_type = 1; loops = 3; op_bitmap = 0xf; use_api = 1; nsets = -1; alpm_temp = bcmi_ltsw_property_get(unit, BCMI_CPN_L3_ALPM_TEMPLATE, 1); if ((alpm_temp == 1) || (alpm_temp == 3) || (alpm_temp == 5) || (alpm_temp == 7) || (alpm_temp == 9) || (alpm_temp == 11)) { /* Combined. */ alpm_mode = 0; vrf_bmp = 0x1; } else if ((alpm_temp == 2) || (alpm_temp == 4) || (alpm_temp == 6) || (alpm_temp == 10)) { /* * In Parallel mode, the database (both TCAM and SRAM) is partitioned * up front into global and VRF specific regions. Run perf test on both * global and VRF by default. */ alpm_mode = 1; vrf_bmp = 0x3; } else { cli_out("Invalide ALPM template: %d\n", alpm_temp); return CMD_FAIL; } parse_table_init(unit, &pt); parse_table_add(&pt, "v4v6", PQ_DFL | PQ_INT, 0, (void *)&ip_type, 0); parse_table_add(&pt, "loops", PQ_DFL | PQ_INT, 0, (void *)&loops, 0); parse_table_add(&pt, "nsets", PQ_DFL | PQ_INT, 0, (void *)&nsets, 0); parse_table_add(&pt, "UseApi", PQ_DFL | PQ_INT, 0, (void *)&use_api, 0); parse_table_add(&pt, "OPs", PQ_DFL | PQ_INT, 0, (void *)&op_bitmap, 0); parse_table_add(&pt, "VRFs", PQ_DFL | PQ_INT, 0, (void *)&vrf_bmp, 0); if (!parseEndOk(arg, &pt, &cmd_rv)) { return cmd_rv; } cli_out("Test runs: %d\n", loops); cli_out("ALPM mode %s\n", alpm_mode == 1 ? "Parallel" : "Combined"); rv = ltsw_l3_route_perf(unit, ip_type, op_bitmap, loops, nsets, use_api, vrf_bmp); if (BCM_FAILURE(rv)) { cli_out("L3 Route performance test failed: %s\n", bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /*! * \brief L3 route cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_l3_route(int unit, args_t *arg) { int rv; char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "add")) { if ((rv = cmd_ltsw_l3_route_add(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "delete")) { if ((rv = cmd_ltsw_l3_route_delete(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "get")) { if ((rv = cmd_ltsw_l3_route_get(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "clear")) { if ((rv = cmd_ltsw_l3_route_clear(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "show")) { if ((rv = cmd_ltsw_l3_route_show(unit, arg)) < 0) { return CMD_FAIL; } } else if (!sal_strcasecmp(subcmd, "perf")) { if ((rv = cmd_ltsw_l3_route_perf(unit, arg)) < 0) { return CMD_FAIL; } } else { return CMD_USAGE; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_egress_print * Description: * Internal function to print out nat egress info. * Parameters: * unit - (IN) Device number. * info - (IN) Pointer to bcm_l3_nat_egress_t data structure. */ static void cmd_ltsw_l3_nat_egress_print(int unit, bcm_l3_nat_egress_t *info) { char sip_str[IP6ADDR_STR_LEN]; char dip_str[IP6ADDR_STR_LEN]; format_ipaddr(sip_str,info->sip_addr); format_ipaddr(dip_str,info->dip_addr); cli_out("%-5d %-7d %-7d %-16s %-16s %-6d %-6d\n", info->flags, info->snat_id, info->dnat_id, sip_str, dip_str, info->src_port, info->dst_port); } /* * Function: * nat_egress_traverse_cb * Description: * Internal function to print out nat egress info. * Parameters: * unit - (IN) Device number. * index - (IN) Egress NAT index. * nat_info - (IN) Egress NAT structure. * data - (IN) Egress NAT user data. */ static int nat_egress_traverse_cb(int unit, int index, bcm_l3_nat_egress_t *nat_info, void *data) { cmd_ltsw_l3_nat_egress_print(unit, nat_info); return BCM_E_NONE; } /* * Function: * cmd_ltsw_l3_nat_egress_add * Description: * Service routine used to create a nat egress entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_egress_add(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; int snat = 0; int dnat = 0; int snat_id = 0; int dnat_id = 0; bcm_ip_t sip_addr = 0; bcm_ip_t dip_addr = 0; int src_port = 0; int dst_port = 0; bcm_l3_nat_egress_t nat_egress; int rv; if (ARG_CNT(arg) == 0) { return CMD_USAGE; } parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "SNAT", PQ_DFL|PQ_INT, 0, (void*)&snat, 0); parse_table_add(&pt, "DNAT", PQ_DFL|PQ_INT, 0, (void*)&dnat, 0); parse_table_add(&pt, "SNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&snat_id, 0); parse_table_add(&pt, "DNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&dnat_id, 0); parse_table_add(&pt, "DIP", PQ_DFL | PQ_IP, 0, (void *)&dip_addr, 0); parse_table_add(&pt, "SIP", PQ_DFL | PQ_IP, 0, (void *)&sip_addr, 0); parse_table_add(&pt, "SRCPORT", PQ_DFL | PQ_INT, 0, (void *)&src_port, 0); parse_table_add(&pt, "DSTPORT", PQ_DFL | PQ_INT, 0, (void *)&dst_port, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_egress_t_init(&nat_egress); nat_egress.flags |= BCM_L3_NAT_EGRESS_WITH_ID; if (napt) { nat_egress.flags |= BCM_L3_NAT_EGRESS_NAPT; } if (snat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_SNAT; } if (dnat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_DNAT; } nat_egress.snat_id = snat_id; nat_egress.dnat_id = dnat_id; nat_egress.sip_addr = sip_addr; nat_egress.src_port = src_port; nat_egress.dip_addr = dip_addr; nat_egress.dst_port = dst_port; if ((rv = bcm_l3_nat_egress_add(unit, &nat_egress)) < 0) { cli_out("ERROR %s: creating nat egress %s.\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } cli_out("New NAT egress: snat_id:%d, dnat_id:%d.\n", nat_egress.snat_id, nat_egress.dnat_id); return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_egress_get * Description: * Service routine used to get & show l3 nat egress info. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_egress_get(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; int snat = 0; int dnat = 0; int snat_id = 0; int dnat_id = 0; bcm_l3_nat_egress_t nat_egress; int rv; parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "SNAT", PQ_DFL|PQ_INT, 0, (void*)&snat, 0); parse_table_add(&pt, "DNAT", PQ_DFL|PQ_INT, 0, (void*)&dnat, 0); parse_table_add(&pt, "SNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&snat_id, 0); parse_table_add(&pt, "DNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&dnat_id, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_egress_t_init(&nat_egress); if (napt) { nat_egress.flags |= BCM_L3_NAT_EGRESS_NAPT; } if (snat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_SNAT; } if (dnat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_DNAT; } nat_egress.snat_id = snat_id; nat_egress.dnat_id = dnat_id; if ((rv = bcm_l3_nat_egress_get(unit, &nat_egress)) < 0) { cli_out("ERROR %s: getting nat egress snat_id:%d, dnat_id:%d %s\n", ARG_CMD(arg), nat_egress.snat_id, nat_egress.dnat_id, bcm_errmsg(rv)); return CMD_FAIL; } cli_out("%-7s %-7s %-7s %-16s %-16s %-6s %-7s\n", "FLAGS", "SNAT_ID", "DNAT_ID", "SIP", "DIP", "SPORT", "DPORT"); cmd_ltsw_l3_nat_egress_print(unit, &nat_egress); return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_egress_destroy * Description: * Service routine used to destroy nat egress entry. * Parameters: * unit - (IN) Device number. * a - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_egress_destroy(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; int snat = 0; int dnat = 0; int snat_id = 0; int dnat_id = 0; bcm_l3_nat_egress_t nat_egress; int rv; if (ARG_CNT(arg) == 0) { return CMD_USAGE; } parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "SNAT", PQ_DFL|PQ_INT, 0, (void*)&snat, 0); parse_table_add(&pt, "DNAT", PQ_DFL|PQ_INT, 0, (void*)&dnat, 0); parse_table_add(&pt, "SNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&snat_id, 0); parse_table_add(&pt, "DNAT_ID", PQ_DFL|PQ_INT, 0, (void*)&dnat_id, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_egress_t_init(&nat_egress); if (napt) { nat_egress.flags |= BCM_L3_NAT_EGRESS_NAPT; } if (snat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_SNAT; } if (dnat) { nat_egress.flags |= BCM_L3_NAT_EGRESS_DNAT; } nat_egress.snat_id = snat_id; nat_egress.dnat_id = dnat_id; if ((rv = bcm_l3_nat_egress_destroy(unit, &nat_egress)) < 0) { cli_out("ERROR %s: destroying nat egress snat_id:%d, dnat_id:%d %s\n", ARG_CMD(arg), nat_egress.snat_id, nat_egress.dnat_id, bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_egress_show * Description: * Service routine used to show nat egress info. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static int cmd_ltsw_l3_nat_egress_show(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; uint32 flags = 0; int napt = 0; int snat = 0; int dnat = 0; int rv; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "SNAT", PQ_DFL|PQ_INT, 0, (void*)&snat, 0); parse_table_add(&pt, "DNAT", PQ_DFL|PQ_INT, 0, (void*)&dnat, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } } if (napt) { flags |= BCM_L3_NAT_EGRESS_NAPT; } if (snat) { flags |= BCM_L3_NAT_EGRESS_SNAT; } if (dnat) { flags |= BCM_L3_NAT_EGRESS_DNAT; } cli_out("%-5s %-7s %-7s %-16s %-16s %-6s %-7s\n", "FLAGS", "SNAT_ID", "DNAT_ID", "SIP", "DIP", "SPORT", "DPORT"); rv = bcm_l3_nat_egress_traverse(unit, flags, 0, 0, nat_egress_traverse_cb, NULL); if(rv < 0) { cli_out("Failed in egress_traverse: %s\n", bcm_errmsg(rv)); return rv; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_egress * Description: * Service routine used to manipulate l3 nat egress entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_egress(int unit, args_t *arg) { char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { cli_out("%s: ERROR: Missing l3_nat_egress subcommand\n", ARG_CMD(arg)); return CMD_FAIL; } if (sal_strcasecmp(subcmd, "add") == 0) { return cmd_ltsw_l3_nat_egress_add(unit, arg); } else if (sal_strcasecmp(subcmd, "get") == 0) { return cmd_ltsw_l3_nat_egress_get(unit, arg); } else if (sal_strcasecmp(subcmd, "destroy") == 0) { return cmd_ltsw_l3_nat_egress_destroy(unit, arg); } else if (sal_strcasecmp(subcmd, "show") == 0) { return cmd_ltsw_l3_nat_egress_show(unit, arg); } else { return CMD_USAGE; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_ingress_print * Description: * Internal function to print out nat ingress info. * Parameters: * unit - (IN) Device number. * info - (IN) Pointer to bcm_l3_nat_ingress_t data structure. */ static void cmd_ltsw_l3_nat_ingress_print(int unit, bcm_l3_nat_ingress_t *info) { char ip_str[IP6ADDR_STR_LEN]; format_ipaddr(ip_str,info->ip_addr); cli_out("%-5d %-16s %-5d %-6d %-5d %-5d %-7d %-8d\n", info->flags, ip_str, info->vrf, info->nat_id, info->ip_proto, info->l4_port, info->nexthop, info->class_id); } /* * Function: * nat_ingress_traverse_cb * Description: * Internal function to print out nat ingress info. * Parameters: * unit - (IN) Device number. * index - (IN) Ingress NAT index. * nat_info - (IN) Ingress NAT structure. * data - (IN) Ingress NAT user data. */ static int nat_ingress_traverse_cb(int unit, int index, bcm_l3_nat_ingress_t *nat_info, void *data) { cmd_ltsw_l3_nat_ingress_print(unit, nat_info); return BCM_E_NONE; } /* * Function: * cmd_ltsw_l3_nat_ingress_add * Description: * Service routine used to create a nat ingress entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_ingress_add(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; int dst_discard = 0; bcm_ip_t ip_addr = 0; int vrf = 0; int proto = 0; int l4_port = 0; int nat_id = 0; int nexthop = 0; int realm_id = 0; int class_id = 0; bcm_l3_nat_ingress_t nat_ingress; int rv; if (ARG_CNT(arg) == 0) { return CMD_USAGE; } parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "DST_DISCARD", PQ_DFL|PQ_INT, 0,(void*)&dst_discard, 0); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL|PQ_INT, 0, (void*)&vrf, 0); parse_table_add(&pt, "PROTO", PQ_DFL | PQ_INT, 0, (void *)&proto, 0); parse_table_add(&pt, "L4_PORT", PQ_DFL | PQ_INT, 0, (void *)&l4_port, 0); parse_table_add(&pt, "NAT_ID", PQ_DFL|PQ_INT, 0, (void*)&nat_id, 0); parse_table_add(&pt, "NEXTHOP", PQ_DFL|PQ_INT, 0, (void*)&nexthop, 0); parse_table_add(&pt, "REALM_ID", PQ_DFL|PQ_INT, 0, (void*)&realm_id, 0); parse_table_add(&pt, "CLASS_ID", PQ_DFL|PQ_INT, 0, (void*)&class_id, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_ingress_t_init(&nat_ingress); if (napt) { nat_ingress.flags |= BCM_L3_NAT_INGRESS_TYPE_NAPT; } if (dst_discard) { nat_ingress.flags |= BCM_L3_NAT_INGRESS_DST_DISCARD; } nat_ingress.ip_addr = ip_addr; nat_ingress.vrf = vrf; nat_ingress.ip_proto = proto; nat_ingress.l4_port = l4_port; nat_ingress.nat_id = nat_id; nat_ingress.nexthop = nexthop; nat_ingress.realm_id = realm_id; nat_ingress.class_id = class_id; if ((rv = bcm_l3_nat_ingress_add(unit, &nat_ingress)) < 0) { cli_out("ERROR %s: creating nat ingress %s.\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_ingress_get * Description: * Service routine used to get & show l3 nat ingress info. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_ingress_get(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; bcm_ip_t ip_addr = 0; int vrf = 0; int proto = 0; int l4_port = 0; bcm_l3_nat_ingress_t nat_ingress; int rv; if (ARG_CNT(arg) == 0) { return CMD_USAGE; } parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL|PQ_INT, 0, (void*)&vrf, 0); parse_table_add(&pt, "PROTO", PQ_DFL | PQ_INT, 0, (void *)&proto, 0); parse_table_add(&pt, "L4_PORT", PQ_DFL | PQ_INT, 0, (void *)&l4_port, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_ingress_t_init(&nat_ingress); if (napt) { nat_ingress.flags |= BCM_L3_NAT_INGRESS_TYPE_NAPT; } nat_ingress.ip_addr = ip_addr; nat_ingress.vrf = vrf; nat_ingress.ip_proto = proto; nat_ingress.l4_port = l4_port; if ((rv = bcm_l3_nat_ingress_find(unit, &nat_ingress)) < 0) { cli_out("ERROR %s: getting nat ingress %s.\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } cli_out("%-5s %-16s %-5s %-6s %-5s %-7s %-7s %-8s\n", "FLAGS", "IP", "VRF", "NAT_ID", "PROTO", "L4_PORT", "NEXTHOP", "CLASS_ID"); cmd_ltsw_l3_nat_ingress_print(unit, &nat_ingress); return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_ingress_delete * Description: * Service routine used to delete nat ingress entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_ingress_delete(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; int napt = 0; bcm_ip_t ip_addr = 0; int vrf = 0; int proto = 0; int l4_port = 0; bcm_l3_nat_ingress_t nat_ingress; int rv; if (ARG_CNT(arg) == 0) { return CMD_USAGE; } parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "IP", PQ_DFL | PQ_IP, 0, (void *)&ip_addr, 0); parse_table_add(&pt, "VRF", PQ_DFL|PQ_INT, 0, (void*)&vrf, 0); parse_table_add(&pt, "PROTO", PQ_DFL | PQ_INT, 0, (void *)&proto, 0); parse_table_add(&pt, "L4_PORT", PQ_DFL | PQ_INT, 0, (void *)&l4_port, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } /* Initialize data structures. */ bcm_l3_nat_ingress_t_init(&nat_ingress); if (napt) { nat_ingress.flags |= BCM_L3_NAT_INGRESS_TYPE_NAPT; } nat_ingress.ip_addr = ip_addr; nat_ingress.vrf = vrf; nat_ingress.ip_proto = proto; nat_ingress.l4_port = l4_port; if ((rv = bcm_l3_nat_ingress_delete(unit, &nat_ingress)) < 0) { cli_out("ERROR %s: destroying nat ingress %s\n", ARG_CMD(arg), bcm_errmsg(rv)); return CMD_FAIL; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_ingress_show * Description: * Service routine used to show nat ingress info. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static int cmd_ltsw_l3_nat_ingress_show(int unit, args_t *arg) { parse_table_t pt; cmd_result_t retCode; uint32 flags = 0; int napt = 0; int dst_discard = 0; int rv; if (ARG_CNT(arg)) { parse_table_init(unit, &pt); parse_table_add(&pt, "NAPT", PQ_DFL|PQ_INT, 0, (void *)&napt, 0); parse_table_add(&pt, "DST_DISCARD", PQ_DFL|PQ_INT, 0, (void*)&dst_discard, 0); if (!parseEndOk(arg, &pt, &retCode)) { return retCode; } } if (napt) { flags |= BCM_L3_NAT_INGRESS_TYPE_NAPT; } if (dst_discard) { flags |= BCM_L3_NAT_INGRESS_DST_DISCARD; } cli_out("%-5s %-16s %-5s %-6s %-5s %-7s %-7s %-8s\n", "FLAGS", "IP", "VRF", "NAT_ID", "PROTO", "L4_PORT", "NEXTHOP", "CLASS_ID"); rv = bcm_l3_nat_ingress_traverse(unit, flags, 0, 0, nat_ingress_traverse_cb, NULL); if(rv < 0) { cli_out("Failed in egress_traverse: %s\n", bcm_errmsg(rv)); return rv; } return CMD_OK; } /* * Function: * cmd_ltsw_l3_nat_ingress * Description: * Service routine used to manipulate l3 nat ingress entry. * Parameters: * unit - (IN) Device number. * arg - (IN) Command arguments. * Returns: * CMD_XXX */ static cmd_result_t cmd_ltsw_l3_nat_ingress(int unit, args_t *arg) { char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { cli_out("%s: ERROR: Missing l3_nat_ingress subcommand\n", ARG_CMD(arg)); return CMD_FAIL; } if (sal_strcasecmp(subcmd, "add") == 0) { return cmd_ltsw_l3_nat_ingress_add(unit, arg); } else if (sal_strcasecmp(subcmd, "get") == 0) { return cmd_ltsw_l3_nat_ingress_get(unit, arg); } else if (sal_strcasecmp(subcmd, "delete") == 0) { return cmd_ltsw_l3_nat_ingress_delete(unit, arg); } else if (sal_strcasecmp(subcmd, "show") == 0) { return cmd_ltsw_l3_nat_ingress_show(unit, arg); } else { return CMD_USAGE; } return CMD_OK; } /* * Function: * cmd_ipmc_entry_print * Description: * Internal function to print out ipmc entry info. * Parameters: * unit - (IN) - device number. * info - (IN) - Pointer to bcm_ipmc_addr_t data structure. * cookie - (IN) - user cookie */ static int cmd_ipmc_entry_print(int unit, bcm_ipmc_addr_t *info, void *cookie) { char s_ip_str[IP6ADDR_STR_LEN]; char mc_ip_str[IP6ADDR_STR_LEN]; int masklen; /* Input parameters check. */ if (NULL == info) { return (BCM_E_PARAM); } /* Print IPMC entry. */ if (info->flags & BCM_IPMC_IP6) { format_ip6addr(s_ip_str, info->s_ip6_addr); format_ip6addr(mc_ip_str, info->mc_ip6_addr); masklen = bcm_ip6_mask_length(info->mc_ip6_mask); cli_out("SRC IP ADDRESS : %s\n", s_ip_str); cli_out("MC IP ADDRESS : %s\n", mc_ip_str); cli_out("MC IP MASK LEN : %d\n", masklen); cli_out("VLAN : %d\n", info->vid); cli_out("VRF : %d\n", info->vrf); cli_out("GROUP : 0x%x\n", info->group); cli_out("GROUP_L2 : 0x%x\n", info->group_l2); cli_out("CLASSS : %d\n", info->lookup_class); cli_out("HIT : %s\n", (info->flags & BCM_IPMC_HIT) ? "Y" :"N"); cli_out("Ingress L3_IIF : %d\n", info->ing_intf); cli_out("Expected L3_IIF: %d\n", info->l3a_intf); } else { format_ipaddr(s_ip_str, info->s_ip_addr); format_ipaddr(mc_ip_str, info->mc_ip_addr); masklen = bcm_ip_mask_length(info->mc_ip_mask); cli_out("SRC IP ADDRESS : %s\n", s_ip_str); cli_out("MC IP ADDRESS : %s\n", mc_ip_str); cli_out("MC IP MASK LEN : %d\n", masklen); cli_out("VLAN : %d\n", info->vid); cli_out("VRF : %d\n", info->vrf); cli_out("GROUP : 0x%x\n", info->group); cli_out("GROUP_L2 : 0x%x\n", info->group_l2); cli_out("CLASSS : %d\n", info->lookup_class); cli_out("HIT : %s\n", (info->flags & BCM_IPMC_HIT) ? "Y" :"N"); cli_out("Ingress L3_IIF : %d\n", info->ing_intf); cli_out("Expected L3_IIF: %d\n", info->l3a_intf); } return (BCM_E_NONE); } /*! * \brief Print ALPM usage. * * \param [in] unit Unit number. * \param [in] res ALPM resources. * * \retval None. */ static void alpm_res_usage_print(int unit, bcm_l3_alpm_resource_t *res) { int grp, i, tot, usage[BCM_L3_ALPM_LEVELS] = {0}; cli_out("- Current ALPM route count & resource usage\n"); cli_out("\t\t Routes L1_usage L2_usage L3_usage L1_used:total L2_used:total L3_used:total\n"); for (grp = 0; grp < bcmL3RouteGroupCounter; grp++) { /* calculate level's usage = cnt_used / cnt_total */ for (i = 0; i < BCM_L3_ALPM_LEVELS; i++) { tot = res[grp].lvl_usage[i].cnt_total; if (tot) { /* usage in 10000% */ usage[i] = (res[grp].lvl_usage[i].cnt_used * 10000L) / tot; } } cli_out("%s:%7d %3d.%02d %3d.%02d %3d.%02d %6d:%6d %6d:%6d %6d:%6d\n", alpm_route_grp_str[grp], res[grp].route_cnt, usage[0]/100, usage[0]%100, usage[1]/100, usage[1]%100, usage[2]/100, usage[2]%100, res[grp].lvl_usage[0].cnt_used, res[grp].lvl_usage[0].cnt_total, res[grp].lvl_usage[1].cnt_used, res[grp].lvl_usage[1].cnt_total, res[grp].lvl_usage[2].cnt_used, res[grp].lvl_usage[2].cnt_total); } } /*! * \brief Show ALPM usage. * * \param [in] unit Unit number. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_alpm_res_usage_show(int unit) { bcm_l3_alpm_resource_t res[bcmL3RouteGroupCounter]; int grp, rv; sal_memset(res, 0, sizeof(bcm_l3_alpm_resource_t) * bcmL3RouteGroupCounter); for (grp = 0; grp < bcmL3RouteGroupCounter; grp++) { rv = bcm_l3_alpm_resource_get(unit, grp, &res[grp]); if (BCM_FAILURE(rv)) { cli_out("Error showing ALPM usage on route group %d: %s\n", grp, bcm_errmsg(rv)); return CMD_FAIL; } } alpm_res_usage_print(unit, res); return CMD_OK; } /*! * \brief ALPM resource usage cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_alpm_res_usage(int unit, args_t *arg) { char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "show")) { return cmd_ltsw_alpm_res_usage_show(unit); } else { return CMD_USAGE; } return CMD_OK; } /*! * \brief Show ALPM projection. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_alpm_projection_show(int unit, args_t *arg) { char *subcmd; int grp, i, rv, proj_route; int v4v6_ratio, max_lvl, max_usage, alpm_temp, mix_route; bcm_l3_alpm_resource_t res[bcmL3RouteGroupCounter]; bool alpm_mode_combined; alpm_temp = bcmi_ltsw_property_get(unit, BCMI_CPN_L3_ALPM_TEMPLATE, 1); if ((alpm_temp == 1) || (alpm_temp == 3) || (alpm_temp == 5) || (alpm_temp == 7) || (alpm_temp == 9) || (alpm_temp == 11)) { alpm_mode_combined = true; } else if ((alpm_temp == 2) || (alpm_temp == 4) || (alpm_temp == 6) || (alpm_temp == 10)) { alpm_mode_combined = false; } else { cli_out("No resource for ALPM (l3_alpm_template %d).\n", alpm_temp); return CMD_FAIL; } subcmd = ARG_GET(arg); if (subcmd != NULL) { v4v6_ratio = parse_integer(subcmd); } else { /* Default to uni-dimensional. */ v4v6_ratio = 0; } sal_memset(res, 0, sizeof(bcm_l3_alpm_resource_t) * bcmL3RouteGroupCounter); for (grp = 0; grp < bcmL3RouteGroupCounter; grp++) { rv = bcm_l3_alpm_resource_get(unit, grp, &res[grp]); if (BCM_FAILURE(rv)) { cli_out("Error showing ALPM usage on route group %d: %s\n", grp, bcm_errmsg(rv)); return CMD_FAIL; } } alpm_res_usage_print(unit, res); /* Show route projection based on current route trend */ cli_out("\n- Route projection based on current route trend\n"); i = 0; for (grp = 0; grp < bcmL3RouteGroupCounter; grp++) { if (alpm_mode_combined) { if (grp == bcmL3RouteGroupGlobalV4 || grp == bcmL3RouteGroupGlobalV6) { continue; /* skip Global grp in Combined mode */ } } rv = bcmi_ltsw_l3_route_grp_projection(unit, grp, &proj_route, &max_lvl, &max_usage); if (BCM_FAILURE(rv)) { continue; /* projection unavailable */ } cli_out("%s: Prj:%7d (max L%d_usage:%3d%%)\n", alpm_mode_combined? alpm_route_comb_str[grp] : alpm_route_grp_str[grp], proj_route, max_lvl, max_usage); i++; } if (i == 0) { cli_out(" <none>\n"); } /* Show route projection based on test DB result interpolation */ cli_out("\n- Route projection based on test DB result interpolation and configuration\n"); if (v4v6_ratio) { cli_out(" (using mixed V4/V6 ratio: %d%%)\n",v4v6_ratio); } else { cli_out(" (uni-dimensional projection)\n"); } for (grp = 0; grp < bcmL3RouteGroupCounter; grp++) { if (alpm_mode_combined) { if (grp == bcmL3RouteGroupGlobalV4 || grp == bcmL3RouteGroupGlobalV6) { continue; /* skip Global grp in Combined mode */ } } rv = bcmi_ltsw_l3_route_grp_testdb(unit, grp, v4v6_ratio, &proj_route, &mix_route, &max_lvl, &max_usage); if (BCM_FAILURE(rv)) { continue; /* default unavailable */ } if (v4v6_ratio) { cli_out("%s: Max:%7d Mix:%7d (max L%d_usage:%3d%%)\n", alpm_mode_combined ? alpm_route_comb_str[grp] : alpm_route_grp_str[grp], proj_route, mix_route, max_lvl, max_usage); } else { cli_out("%s: Max:%7d (max L%d_usage:%3d%%)\n", alpm_mode_combined ? alpm_route_comb_str[grp] : alpm_route_grp_str[grp], proj_route, max_lvl, max_usage); } } cli_out("\n"); return CMD_OK; } /*! * \brief ALPM projection cmd handler. * * \param [in] unit Unit number. * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ static cmd_result_t cmd_ltsw_alpm_projection(int unit, args_t *arg) { char *subcmd; subcmd = ARG_GET(arg); if (subcmd == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "show")) { return cmd_ltsw_alpm_projection_show(unit, arg); } else { return CMD_USAGE; } return CMD_OK; } /****************************************************************************** * Public Functions */ /*! * \brief L3 cmd handler. * * \param [in] unit Unit number * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ cmd_result_t cmd_ltsw_l3(int unit, args_t *arg) { char *subcmd = NULL; int rv; if ((subcmd = ARG_GET(arg)) == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "init")) { if ((rv = bcm_l3_init(unit)) < 0) { cli_out("%s: error initializing: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); } return CMD_OK; } else if (!sal_strcasecmp(subcmd, "detach")) { if ((rv = bcm_l3_cleanup(unit)) < 0) { cli_out("%s: error detaching: %s\n", ARG_CMD(arg), bcm_errmsg(rv)); } return CMD_OK; } else if (!sal_strcasecmp(subcmd, "tunnel_init")) { return cmd_ltsw_l3_tunnel_init(unit, arg); } else if (!sal_strcasecmp(subcmd, "tunnel_term")) { return cmd_ltsw_l3_tunnel_term(unit, arg); } else if (!sal_strcasecmp(subcmd, "ing_intf")) { return cmd_ltsw_l3_ingress(unit, arg); } else if (!sal_strcasecmp(subcmd, "intf")) { return cmd_ltsw_l3_intf(unit, arg); } else if (!sal_strcasecmp(subcmd, "egress")) { return cmd_ltsw_l3_egress(unit, arg); } else if (!sal_strcasecmp(subcmd, "ecmp")) { return cmd_ltsw_l3_ecmp(unit, arg); } else if (!sal_strcasecmp(subcmd, "host")) { return cmd_ltsw_l3_host(unit, arg); } else if (!sal_strcasecmp(subcmd, "route")) { return cmd_ltsw_l3_route(unit, arg); } else if (!sal_strcasecmp(subcmd, "nat_egress")) { return cmd_ltsw_l3_nat_egress(unit, arg); } else if (!sal_strcasecmp(subcmd, "nat_ingress")) { return cmd_ltsw_l3_nat_ingress(unit, arg); } else { cli_out("Unsupported command. \n"); return CMD_OK; } return CMD_OK; } cmd_result_t cmd_ltsw_ipmc(int unit, args_t *a) { char *table, *subcmd_s, *argstr; int subcmd = 0; parse_table_t pt; cmd_result_t retCode; bcm_mac_t mac; vlan_id_t vid; int vlan = 0; int r, i; int port = 0, ttl_th = 1, untag = 1; char mac_str[SAL_MACADDR_STR_LEN]; bcm_ipmc_counters_t counters; bcm_ip_t s_ip_addr = 0, mc_ip_addr = 0; bcm_ipmc_addr_t ipmc_data; bcm_pbmp_t pbmp; bcm_port_config_t pcfg; int valid = 1, cos = 0, ts = 0, nocheck = 0, replace = 0, group = 0, group_l2 = 0; int lookup_class = 0; int cfg_enable = 1, cfg_check_src_port = 1, cfg_check_src_ip = 1; int vrf = 0; bcm_ip6_t ip6_addr, sip6_addr; int mc_ip_mask_len = 0; int mc_ip6_mask_len = 0; bcm_if_t l3_iif = BCM_IF_INVALID; int hit = 0; #define IPMC_ADD 1 #define IPMC_DEL 2 #define IPMC_CLEAR 3 #define IPMC_SHOW 4 #define IPMC_SET 5 sal_memset(mac, 0x10, 6); sal_memset(&ipmc_data, 0, sizeof(ipmc_data)); sal_memset(ip6_addr, 0, sizeof(bcm_ip6_t)); sal_memset(sip6_addr, 0, sizeof(bcm_ip6_t)); /* Check valid device to operation on ...*/ if (!sh_check_attached(ARG_CMD(a), unit)) { return CMD_FAIL; } if (bcm_port_config_get(unit, &pcfg) != BCM_E_NONE) { cli_out("%s: Error: bcm ports not initialized\n", ARG_CMD(a)); return CMD_FAIL; } if ((table = ARG_GET(a)) == NULL) { return CMD_USAGE; } if (sal_strcasecmp(table, "init") == 0) { if ((r = bcm_ipmc_init(unit)) < 0) { cli_out("%s: error initializing: %s\n", ARG_CMD(a), bcm_errmsg(r)); } return CMD_OK; } else if (sal_strcasecmp(table, "detach") == 0) { if ((r = bcm_ipmc_detach(unit)) < 0) { cli_out("%s: error detaching: %s\n", ARG_CMD(a), bcm_errmsg(r)); } return CMD_OK; } if (sal_strcasecmp(table, "config") == 0) { parse_table_init(unit, &pt); parse_table_add(&pt, "Enable", PQ_DFL|PQ_BOOL, 0, (void *)&cfg_enable, 0); parse_table_add(&pt, "CheckSrcPort", PQ_DFL|PQ_BOOL, 0, (void *)&cfg_check_src_port, 0); parse_table_add(&pt, "CheckSrcIp", PQ_DFL|PQ_BOOL, 0, (void *)&cfg_check_src_ip, 0); if (parse_arg_eq(a, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(a), ARG_CUR(a)); parse_arg_eq_done(&pt); return CMD_FAIL; } i = CMD_OK; if (pt.pt_entries[0].pq_type & PQ_PARSED) { r = bcm_ipmc_enable(unit, cfg_enable); if (r < 0) { cli_out("%s: Error: Enable failed: %s\n", ARG_CMD(a), bcm_errmsg(r)); i = CMD_FAIL; } } if (pt.pt_entries[1].pq_type & PQ_PARSED) { /* bcm_ipmc_source_port_check is deprecated */ r = BCM_E_UNAVAIL; if (r < 0) { cli_out("%s: Error: check_source_port failed: %s\n", ARG_CMD(a), bcm_errmsg(r)); i = CMD_FAIL; } } if (pt.pt_entries[2].pq_type & PQ_PARSED) { /* bcm_ipmc_source_ip_search is deprecated */ r = BCM_E_UNAVAIL; if (r < 0) { cli_out("%s: Error: check_source_ip failed: %s\n", ARG_CMD(a), bcm_errmsg(r)); i = CMD_FAIL; } } parse_arg_eq_done(&pt); return (i); } if ((subcmd_s = ARG_GET(a)) == NULL) { return CMD_USAGE; } if (sal_strcasecmp(subcmd_s, "add") == 0) { subcmd = IPMC_ADD; } else if (sal_strcasecmp(subcmd_s, "del") == 0) { subcmd = IPMC_DEL; } else if (sal_strcasecmp(subcmd_s, "clear") == 0) { subcmd = IPMC_CLEAR; } else if (sal_strcasecmp(subcmd_s, "show") == 0) { subcmd = IPMC_SHOW; } else if (sal_strcasecmp(subcmd_s, "set") == 0) { subcmd = IPMC_SET; } else { return CMD_USAGE; } if (sal_strcasecmp(table, "table") == 0) { switch (subcmd) { case IPMC_ADD: parse_table_init(unit, &pt); parse_table_add(&pt, "Src_IP", PQ_DFL|PQ_IP, 0, (void *)&s_ip_addr, 0); parse_table_add(&pt, "Mc_IP", PQ_DFL|PQ_IP, 0, (void *)&mc_ip_addr, 0); parse_table_add(&pt, "Mc_IPMaskLen", PQ_DFL|PQ_INT, 0, (void*)&mc_ip_mask_len, 0); parse_table_add(&pt, "VlanID", PQ_DFL|PQ_INT, 0, (void *)&vlan, 0); parse_table_add(&pt, "COS", PQ_DFL|PQ_INT, 0, (void *)&cos, 0); parse_table_add(&pt, "VRF", PQ_DFL|PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "Valid", PQ_DFL|PQ_BOOL, 0, (void *)&valid, 0); parse_table_add(&pt, "src_Port", PQ_INT, 0, (void *)&port, 0); parse_table_add(&pt, "TS", PQ_INT, 0, (void *)&ts, 0); parse_table_add(&pt, "NoCHECK", PQ_DFL|PQ_BOOL, 0, (void *)&nocheck, 0); parse_table_add(&pt, "Replace", PQ_DFL|PQ_BOOL, 0, (void *)&replace, 0); parse_table_add(&pt, "LookupClass", PQ_DFL|PQ_INT, 0, (void *)&lookup_class, 0); parse_table_add(&pt, "Group", PQ_DFL|PQ_INT, 0, (void *)&group, 0); parse_table_add(&pt, "GroupL2", PQ_DFL|PQ_INT, 0, (void *)&group_l2, 0); parse_table_add(&pt, "IngIntf", PQ_DFL|PQ_INT, 0, (void *)&l3_iif, 0); parse_table_add(&pt, "Hit", PQ_DFL|PQ_BOOL, 0, (void *)&hit, 0); if (parse_arg_eq(a, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(a), ARG_CUR(a)); parse_arg_eq_done(&pt); return CMD_FAIL; } bcm_ipmc_addr_t_init(&ipmc_data); if (pt.pt_entries[3].pq_type & PQ_PARSED) { ipmc_data.flags |= BCM_IPMC_SETPRI; } parse_arg_eq_done(&pt); vid = vlan; ipmc_data.s_ip_addr = s_ip_addr; ipmc_data.mc_ip_addr = mc_ip_addr; ipmc_data.mc_ip_mask = bcm_ip_mask_create(mc_ip_mask_len); ipmc_data.vid = vid; ipmc_data.vrf = vrf; ipmc_data.cos = cos; ipmc_data.ts = ts; ipmc_data.port_tgid = port; ipmc_data.v = valid; ipmc_data.ing_intf = l3_iif; if (nocheck) { ipmc_data.flags |= BCM_IPMC_SOURCE_PORT_NOCHECK; } if (replace) { ipmc_data.flags |= BCM_IPMC_REPLACE; } if (hit) { ipmc_data.flags |= BCM_IPMC_HIT_ENABLE; } ipmc_data.lookup_class = lookup_class; if (group) { ipmc_data.group = group; } if (group_l2) { ipmc_data.group_l2 = group_l2; ipmc_data.flags |= BCM_IPMC_L2; } r = bcm_ipmc_add(unit, &ipmc_data); if (r < 0) { cli_out("%s: Error Add to ipmc table %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return CMD_OK; case IPMC_DEL: parse_table_init(unit, &pt); parse_table_add(&pt, "Src_IP", PQ_DFL|PQ_IP, 0, (void *)&s_ip_addr, 0); parse_table_add(&pt, "Mc_IP", PQ_DFL|PQ_IP, 0, (void *)&mc_ip_addr, 0); parse_table_add(&pt, "Mc_IPMaskLen", PQ_DFL|PQ_INT, 0, (void*)&mc_ip_mask_len, 0); parse_table_add(&pt, "VlanID", PQ_DFL|PQ_INT, 0, (void *)&vlan, 0); parse_table_add(&pt, "VRF", PQ_DFL|PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "IngIntf", PQ_DFL|PQ_INT, 0, (void *)&l3_iif, 0); if (!parseEndOk( a, &pt, &retCode)) return retCode; bcm_ipmc_addr_t_init(&ipmc_data); ipmc_data.s_ip_addr = s_ip_addr; ipmc_data.mc_ip_addr = mc_ip_addr; ipmc_data.mc_ip_mask = bcm_ip_mask_create(mc_ip_mask_len); ipmc_data.vid = vlan; ipmc_data.vrf = vrf; ipmc_data.ing_intf = l3_iif; r = bcm_ipmc_remove(unit, &ipmc_data); if (r < 0) { cli_out("%s: Error delete from ipmc table %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return CMD_OK; case IPMC_CLEAR: r = bcm_ipmc_remove_all(unit); if (r < 0) { cli_out("%s: %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return (CMD_OK); case IPMC_SHOW: if (ARG_CNT(a)) { r = BCM_E_UNAVAIL; return CMD_OK; } bcm_ipmc_traverse(unit, 0, cmd_ipmc_entry_print, NULL); return (CMD_OK); default: return CMD_USAGE; } return CMD_OK; } if (sal_strcasecmp(table, "egr") == 0) { switch (subcmd) { case IPMC_SET: parse_table_init(unit, &pt); parse_table_add(&pt, "Port", PQ_PORT, 0, (void *)&port, 0); parse_table_add(&pt, "MAC", PQ_DFL|PQ_MAC, 0, (void *)mac, 0); parse_table_add(&pt, "Vlan", PQ_INT, 0, (void *)&vlan, 0); parse_table_add(&pt, "Untag", PQ_DFL|PQ_BOOL, 0, (void *)&untag, 0); parse_table_add(&pt, "Ttl_thresh", PQ_DFL|PQ_INT, 0, (void *)&ttl_th, 0); if (!parseEndOk(a, &pt, &retCode)) { return retCode; } vid = vlan; r = bcm_ipmc_egress_port_set(unit, port, mac, untag, vid, ttl_th); if (r < 0) { cli_out("%s: Egress IP Multicast Configuration registers: %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return CMD_OK; case IPMC_SHOW: if ((argstr = ARG_GET(a)) == NULL) { pbmp = pcfg.e; } else { if (parse_bcm_port(unit, argstr, &port) < 0) { cli_out("%s: Invalid port string: %s\n", ARG_CMD(a), argstr); return CMD_FAIL; } if (!BCM_PBMP_MEMBER(pcfg.e, port)) { cli_out("port %d is not a valid Ethernet port\n", port); return CMD_FAIL; } BCM_PBMP_CLEAR(pbmp); BCM_PBMP_PORT_ADD(pbmp, port); } cli_out("Egress IP Multicast Configuration Register information\n"); cli_out("Port Mac Address Vlan Untag TTL_THRESH\n"); BCM_PBMP_ITER(pbmp, port) { r = bcm_ipmc_egress_port_get(unit, port, mac, &untag, &vid, &ttl_th); if (r == BCM_E_NONE) { format_macaddr(mac_str, mac); cli_out("%-4s %-18s %4d %s %5d\n", BCM_PORT_NAME(unit, port), mac_str, vid, untag ? "Y" : "N", ttl_th); } } return CMD_OK; default: return CMD_USAGE; } return CMD_OK; } if (sal_strcasecmp(table, "counter") == 0) { if ((argstr = ARG_GET(a)) == NULL) { pbmp = pcfg.e; } else { if (parse_bcm_port(unit, argstr, &port) < 0) { cli_out("%s: Invalid port string: %s\n", ARG_CMD(a), argstr); return CMD_FAIL; } if (!BCM_PBMP_MEMBER(pcfg.e, port)) { cli_out("port %d is not a valid Ethernet port\n", port); return CMD_FAIL; } BCM_PBMP_CLEAR(pbmp); BCM_PBMP_PORT_ADD(pbmp, port); } cli_out("PORT RMCA TMCA IMBP IMRP RIMDR TIMDR\n"); /* coverity[overrun-local] */ BCM_PBMP_ITER(pbmp, port) { r = bcm_ipmc_counters_get(unit, port, &counters); if (r == BCM_E_NONE) { cli_out("%4d %8d %8d %8d %8d %8d %8d\n", port, COMPILER_64_LO(counters.rmca), COMPILER_64_LO(counters.tmca), COMPILER_64_LO(counters.imbp), COMPILER_64_LO(counters.imrp), COMPILER_64_LO(counters.rimdr), COMPILER_64_LO(counters.timdr)); } } return CMD_OK; } if (sal_strcasecmp(table, "ip6table") == 0) { switch (subcmd) { /* ipmc ip6table add */ case IPMC_ADD: parse_table_init(unit, &pt); parse_table_add(&pt, "Src_IP", PQ_DFL|PQ_IP6, 0, (void *)&sip6_addr, 0); parse_table_add(&pt, "Mc_IP", PQ_DFL|PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "Mc_IPMaskLen", PQ_DFL|PQ_INT, 0, (void*)&mc_ip6_mask_len, 0); parse_table_add(&pt, "VlanID", PQ_DFL|PQ_INT, 0, (void *)&vlan, 0); parse_table_add(&pt, "Valid", PQ_DFL|PQ_BOOL, 0, (void *)&valid, 0); parse_table_add(&pt, "COS", PQ_DFL|PQ_INT, 0, (void *)&cos, 0); parse_table_add(&pt, "src_Port", PQ_INT, 0, (void *)&port, 0); parse_table_add(&pt, "TS", PQ_INT, 0, (void *)&ts, 0); parse_table_add(&pt, "NoCHECK", PQ_DFL|PQ_BOOL, 0, (void *)&nocheck, 0); parse_table_add(&pt, "LookupClass", PQ_DFL|PQ_INT, 0, (void *)&lookup_class, 0); parse_table_add(&pt, "Group", PQ_DFL|PQ_INT, 0, (void *)&group, 0); parse_table_add(&pt, "GroupL2", PQ_DFL|PQ_INT, 0, (void *)&group_l2, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "IngIntf", PQ_DFL|PQ_INT, 0, (void *)&l3_iif, 0); parse_table_add(&pt, "Hit", PQ_DFL|PQ_BOOL, 0, (void *)&hit, 0); if (parse_arg_eq(a, &pt) < 0) { cli_out("%s: Error: Unknown option: %s\n", ARG_CMD(a), ARG_CUR(a)); parse_arg_eq_done(&pt); return CMD_FAIL; } bcm_ipmc_addr_t_init(&ipmc_data); if (pt.pt_entries[4].pq_type & PQ_PARSED) { ipmc_data.flags |= BCM_IPMC_SETPRI; } parse_arg_eq_done(&pt); sal_memcpy(ipmc_data.mc_ip6_addr, ip6_addr, BCM_IP6_ADDRLEN); sal_memcpy(ipmc_data.s_ip6_addr, sip6_addr, BCM_IP6_ADDRLEN); bcm_ip6_mask_create(ipmc_data.mc_ip6_mask, mc_ip6_mask_len); ipmc_data.cos = cos; ipmc_data.vid = vlan; ipmc_data.flags |= BCM_IPMC_IP6; ipmc_data.ts = ts; ipmc_data.port_tgid = port; ipmc_data.vrf = vrf; ipmc_data.v = valid; ipmc_data.ing_intf = l3_iif; if (nocheck) { ipmc_data.flags |= BCM_IPMC_SOURCE_PORT_NOCHECK; } if (hit) { ipmc_data.flags |= BCM_IPMC_HIT_ENABLE; } ipmc_data.lookup_class = lookup_class; if (group) { ipmc_data.group = group; } if (group_l2) { ipmc_data.group_l2 = group_l2; ipmc_data.flags |= BCM_IPMC_L2; } r = bcm_ipmc_add(unit, &ipmc_data); if (r < 0) { cli_out("%s: Error Add to ipmc table %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return CMD_OK; break; case IPMC_DEL: /* ipmc ip6table del */ parse_table_init(unit, &pt); parse_table_add(&pt, "Src_IP", PQ_DFL|PQ_IP6, 0, (void *)&sip6_addr, 0); parse_table_add(&pt, "Mc_IP", PQ_DFL|PQ_IP6, 0, (void *)&ip6_addr, 0); parse_table_add(&pt, "Mc_IPMaskLen", PQ_DFL|PQ_INT, 0, (void*)&mc_ip6_mask_len, 0); parse_table_add(&pt, "VlanID", PQ_DFL|PQ_INT, 0, (void *)&vlan, 0); parse_table_add(&pt, "VRF", PQ_DFL | PQ_INT, 0, (void *)&vrf, 0); parse_table_add(&pt, "IngIntf", PQ_DFL|PQ_INT, 0, (void *)&l3_iif, 0); if (!parseEndOk( a, &pt, &retCode)) { return retCode; } bcm_ipmc_addr_t_init(&ipmc_data); sal_memcpy(ipmc_data.mc_ip6_addr, ip6_addr, BCM_IP6_ADDRLEN); sal_memcpy(ipmc_data.s_ip6_addr, sip6_addr, BCM_IP6_ADDRLEN); bcm_ip6_mask_create(ipmc_data.mc_ip6_mask, mc_ip6_mask_len); ipmc_data.vid=vlan; ipmc_data.flags = BCM_IPMC_IP6; ipmc_data.vrf = vrf; ipmc_data.ing_intf = l3_iif; r = bcm_ipmc_remove(unit, &ipmc_data); if (r < 0) { cli_out("%s: Error delete from ipmc table %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return CMD_OK; case IPMC_CLEAR: /* ipmc ip6table clear */ r = bcm_ipmc_remove_all(unit); if (r < 0) { cli_out("%s: %s\n", ARG_CMD(a), bcm_errmsg(r)); return CMD_FAIL; } return (CMD_OK); case IPMC_SHOW: if (ARG_CNT(a)) { r = BCM_E_UNAVAIL; return CMD_OK; } /* ipmc ip6table show */ bcm_ipmc_traverse(unit, BCM_IPMC_IP6, cmd_ipmc_entry_print, NULL); return (CMD_OK); default: return CMD_USAGE; } return CMD_OK; } return CMD_USAGE; } /*! * \brief ALPM cmd handler. * * \param [in] unit Unit number * \param [in] arg Arg structure for parsing arguments. * * \retval CMD_OK Command completed successfully. * \retval CMD_FAIL Command failed. */ cmd_result_t cmd_ltsw_alpm(int unit, args_t *arg) { char *subcmd = NULL; if ((subcmd = ARG_GET(arg)) == NULL) { return CMD_USAGE; } if (!sal_strcasecmp(subcmd, "usage")) { return cmd_ltsw_alpm_res_usage(unit, arg); } else if (!sal_strcasecmp(subcmd, "projection")) { return cmd_ltsw_alpm_projection(unit, arg); } else { cli_out("Unsupported command. \n"); } return CMD_OK; } #endif /* BCM_LTSW_SUPPORT */
29.643095
134
0.572007
[ "object", "3d" ]
e7deec3fbd5fbdd4a635655b1eb081bb09b255f2
1,742
h
C
src/train.h
haoyz/sym-STDP-SNN
4795b96a97a229c55e9d6a1e11879e751b5f1eaa
[ "Apache-2.0" ]
30
2019-10-23T02:36:33.000Z
2022-03-30T16:51:37.000Z
src/train.h
haoyz/sym-STDP-SNN
4795b96a97a229c55e9d6a1e11879e751b5f1eaa
[ "Apache-2.0" ]
null
null
null
src/train.h
haoyz/sym-STDP-SNN
4795b96a97a229c55e9d6a1e11879e751b5f1eaa
[ "Apache-2.0" ]
8
2019-10-30T23:35:20.000Z
2022-01-05T04:42:18.000Z
#ifndef _TRAIN_H_ #define _TRAIN_H_ #include "gnuplot.h" #include "model.h" #include "../global.h" #include <stddef.h> #include <vector> using namespace std; #define N_rand 256 #define preN_EI NExc #define postN_EI NInh #define preN_IE NInh #define postN_IE NExc #define connN_E2I NExc #define connN_I2E NInh *(NExc - 1) #define INPUT_INTENSITY_INIT 2 #define Cla_INPUT_INTENSITY_INIT 0.2 //khz #define LastTrain 0 #define NowTrain 1 #define NowTest 2 #define FinalTest 0 extern long int imageNum; // ------------------------------------------------------------------------------ // visualization // ------------------------------------------------------------------------------ vector<vector<float>> PEVisual(WIDTH *NExc_Sqrt, vector<float>(HEIGHT *NExc_Sqrt)); vector<vector<float>> ECVisual(ECw_X, vector<float>(ECw_Y)); vector<vector<float>> ECVisual_inferred(ECw_X, vector<float>(ECw_Y)); vector<vector<float>> CEVisual(ECw_Y, vector<float>(ECw_X)); vector<vector<float>> CEVisual_inferred(ECw_Y, vector<float>(ECw_X)); int str2int(string s); void convertRateToRandomNumberThreshold(vector<float> rateKHz_pattern, uint64_t *pattern, int Num); void get_rand_g(float *p, long int n, int g_max); void get_rand(uint64_t *p, long int n, int max); void get_inputdata(string datapath, vector<vector<float>> &images, vector<float> &labels, vector<vector<float>> &images_test, vector<float> &labels_test); void rewrite_gEI_gIE(); void reset_Cla_para(); void feed_to_networks(vector<float> image, vector<float> &FR_khz, float input_intensity); void Cla_feed_to_networks(int label, vector<float> &cla_FR_khz, float cla_input_intensity); void reset_ratesPPoi(vector<float> &FR_khz); void reset_ratesPCla(vector<float> &cla_FR_khz); #endif
35.55102
154
0.706085
[ "vector", "model" ]
e7f3d5dcfd36a90f7f30918281dbcf014efd1506
2,773
h
C
trikControl/src/fifoworker.h
KirillSmirnov/trikRuntime
072aceca7ed59d0beab3d7fda97c59504fc57053
[ "Apache-2.0" ]
null
null
null
trikControl/src/fifoworker.h
KirillSmirnov/trikRuntime
072aceca7ed59d0beab3d7fda97c59504fc57053
[ "Apache-2.0" ]
1
2022-03-23T09:33:11.000Z
2022-03-23T09:33:11.000Z
trikControl/src/fifoworker.h
KirillSmirnov/trikRuntime
072aceca7ed59d0beab3d7fda97c59504fc57053
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 CyberTech Labs 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. */ #pragma once #include <QtCore/QObject> #include <QtCore/QThread> #include <QtCore/QScopedPointer> #include "deviceState.h" #include <trikHal/fifoInterface.h> #include <trikHal/hardwareAbstractionInterface.h> #include <qsemaphore.h> namespace trikControl { /// Worker object that processes FIFO output and updates stored reading. Meant to be executed in separate /// thread. class FifoWorker : public QObject, public DeviceInterface { Q_OBJECT public: /// Constructor. Creates FIFO device programmatically by file name. /// @param fileName - name of a FIFO file. /// @param hardwareAbstraction - interface to underlying hardware or operating system capabilities of a robot. FifoWorker(const QString &fileName , const trikHal::HardwareAbstractionInterface &hardwareAbstraction); ~FifoWorker(); Status status() const override; public slots: /// Work with DeviceState and connections. void init(); /// Reads line from this FIFO file, returning all available data as string. QString read(); /// Reads data from this FIFO file, returning all available data as string. QVector<uint8_t> readRaw(); /// Returns true if FIFO has new line in it. bool hasLine() const; /// Returns true if FIFO has new bytes in it. bool hasData() const; /// Blocks the Thread with QSemaphore until init() method releases it. void waitUntilInited(); signals: /// Emitted once per each text line that arrives to FIFO. void newLine(const QString &data); /// Emitted when new bytes have arrived to FIFO file. void newData(const QVector<uint8_t> &data); private slots: void onNewLine(const QString &line); void onNewData(const QVector<uint8_t> &data); void onReadError(); private: const QString mFifoFileName; const trikHal::HardwareAbstractionInterface &mHardwareAbstraction; QScopedPointer<trikHal::FifoInterface> mFifo; /// Last line that was read from FIFO. QString mCurrentLine; /// Last data that was read from FIFO. QVector<uint8_t> mCurrentData; /// Lock for mCurrent mutable QReadWriteLock mCurrentLock; /// State of a FIFO file as a device. DeviceState mState; /// Releases when init() is finished QSemaphore mWaitForInit {1}; }; }
29.189474
111
0.75009
[ "object" ]
e7f4098c588839d80f955fca0e5021e0c23b8b1b
9,136
c
C
gnd-sys/cfs-templates/osk_c_app/fsw/src/@template@_app.c
Atomicchipmonk/cfsat
e8f199c8036bdc3fe91643b125570a397bdb20b8
[ "Apache-2.0" ]
null
null
null
gnd-sys/cfs-templates/osk_c_app/fsw/src/@template@_app.c
Atomicchipmonk/cfsat
e8f199c8036bdc3fe91643b125570a397bdb20b8
[ "Apache-2.0" ]
null
null
null
gnd-sys/cfs-templates/osk_c_app/fsw/src/@template@_app.c
Atomicchipmonk/cfsat
e8f199c8036bdc3fe91643b125570a397bdb20b8
[ "Apache-2.0" ]
null
null
null
/* ** Purpose: Implement the @Template@ application ** ** Notes: ** 1. See header notes. ** ** References: ** 1. OpenSatKit Object-based Application Developer's Guide. ** 2. cFS Application Developer's Guide. ** ** Written by David McComas, 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. */ /* ** Includes */ #include <string.h> #include "@template@_app.h" /***********************/ /** Macro Definitions **/ /***********************/ /* Convenience macros */ #define INITBL_OBJ (&(@Template@.IniTbl)) #define CMDMGR_OBJ (&(@Template@.CmdMgr)) #define TBLMGR_OBJ (&(@Template@.TblMgr)) #define EXOBJ_OBJ (&(@Template@.ExObj)) /*******************************/ /** Local Function Prototypes **/ /*******************************/ static int32 InitApp(void); static int32 ProcessCommands(void); static void SendHousekeepingPkt(void); /**********************/ /** File Global Data **/ /**********************/ /* ** Must match DECLARE ENUM() declaration in app_cfg.h ** Defines "static INILIB_CfgEnum_t IniCfgEnum" */ DEFINE_ENUM(Config,APP_CONFIG) /*****************/ /** Global Data **/ /*****************/ @TEMPLATE@_Class_t @Template@; /****************************************************************************** ** Function: @TEMPLATE@_AppMain ** */ void @TEMPLATE@_AppMain(void) { uint32 RunStatus = CFE_ES_RunStatus_APP_ERROR; CFE_EVS_Register(NULL, 0, CFE_EVS_NO_FILTER); if (InitApp() == CFE_SUCCESS) /* Performs initial CFE_ES_PerfLogEntry() call */ { RunStatus = CFE_ES_RunStatus_APP_RUN; } /* ** Main process loop */ while (CFE_ES_RunLoop(&RunStatus)) { RunStatus = ProcessCommands(); /* Pends indefinitely & manages CFE_ES_PerfLogEntry() calls */ } /* End CFE_ES_RunLoop */ CFE_ES_WriteToSysLog("@TEMPLATE@ App terminating, run status = 0x%08X\n", RunStatus); /* Use SysLog, events may not be working */ CFE_EVS_SendEvent(@TEMPLATE@_EXIT_EID, CFE_EVS_EventType_CRITICAL, "@TEMPLATE@ App terminating, run status = 0x%08X", RunStatus); CFE_ES_ExitApp(RunStatus); /* Let cFE kill the task (and any child tasks) */ } /* End of @TEMPLATE@_AppMain() */ /****************************************************************************** ** Function: @TEMPLATE@_NoOpCmd ** */ bool @TEMPLATE@_NoOpCmd(void* ObjDataPtr, const CFE_MSG_Message_t *MsgPtr) { CFE_EVS_SendEvent (@TEMPLATE@_NOOP_EID, CFE_EVS_EventType_INFORMATION, "No operation command received for @TEMPLATE@ App version %d.%d.%d", @TEMPLATE@_MAJOR_VER, @TEMPLATE@_MINOR_VER, @TEMPLATE@_PLATFORM_REV); return true; } /* End @TEMPLATE@_NoOpCmd() */ /****************************************************************************** ** Function: @TEMPLATE@_ResetAppCmd ** ** Notes: ** 1. Framework objects require an object reference since they are ** reentrant. Applications use the singleton pattern and store a ** reference pointer to the object data during construction. */ bool @TEMPLATE@_ResetAppCmd(void* ObjDataPtr, const CFE_MSG_Message_t *MsgPtr) { CMDMGR_ResetStatus(CMDMGR_OBJ); TBLMGR_ResetStatus(TBLMGR_OBJ); EXOBJ_ResetStatus(); return true; } /* End @TEMPLATE@_ResetAppCmd() */ /****************************************************************************** ** Function: SendHousekeepingPkt ** */ static void SendHousekeepingPkt(void) { /* Good design practice in case app expands to more than one table */ const TBLMGR_Tbl_t* LastTbl = TBLMGR_GetLastTblStatus(TBLMGR_OBJ); /* ** Framework Data */ @Template@.HkPkt.ValidCmdCnt = @Template@.CmdMgr.ValidCmdCnt; @Template@.HkPkt.InvalidCmdCnt = @Template@.CmdMgr.InvalidCmdCnt; /* ** Table Data ** - Loaded with status from the last table action */ @Template@.HkPkt.LastTblAction = LastTbl->LastAction; @Template@.HkPkt.LastTblActionStatus = LastTbl->LastActionStatus; /* ** Example Object Data */ @Template@.HkPkt.ExObjCounterMode = @Template@.ExObj.CounterMode; @Template@.HkPkt.ExObjCounterValue = @Template@.ExObj.CounterValue; CFE_SB_TimeStampMsg(CFE_MSG_PTR(@Template@.HkPkt.TlmHeader)); CFE_SB_TransmitMsg(CFE_MSG_PTR(@Template@.HkPkt.TlmHeader), true); } /* End SendHousekeepingPkt() */ /****************************************************************************** ** Function: InitApp ** */ static int32 InitApp(void) { int32 Status = OSK_C_FW_CFS_ERROR; /* ** Initialize objects */ if (INITBL_Constructor(INITBL_OBJ, @TEMPLATE@_INI_FILENAME, &IniCfgEnum)) { @Template@.PerfId = INITBL_GetIntConfig(INITBL_OBJ, CFG_APP_PERF_ID); CFE_ES_PerfLogEntry(@Template@.PerfId); @Template@.CmdMid = CFE_SB_ValueToMsgId(@TEMPLATE@_CMD_MID); @Template@.ExecuteMid = CFE_SB_ValueToMsgId(@TEMPLATE@_EXE_MID); @Template@.SendHkMid = CFE_SB_ValueToMsgId(@TEMPLATE@_SEND_HK_MID); Status = CFE_SUCCESS; } /* End if INITBL Constructed */ if (Status == CFE_SUCCESS) { /* ** Constuct app's contained objects */ EXOBJ_Constructor(EXOBJ_OBJ, INITBL_OBJ); /* ** Initialize app level interfaces */ CFE_SB_CreatePipe(&@Template@.CmdPipe, INITBL_GetIntConfig(INITBL_OBJ, CFG_CMD_PIPE_DEPTH), INITBL_GetStrConfig(INITBL_OBJ, CFG_CMD_PIPE_NAME)); CFE_SB_Subscribe(@Template@.CmdMid, @Template@.CmdPipe); CFE_SB_Subscribe(@Template@.ExecuteMid, @Template@.CmdPipe); CFE_SB_Subscribe(@Template@.SendHkMid, @Template@.CmdPipe); CMDMGR_Constructor(CMDMGR_OBJ); CMDMGR_RegisterFunc(CMDMGR_OBJ, CMDMGR_NOOP_CMD_FC, NULL, @TEMPLATE@_NoOpCmd, 0); CMDMGR_RegisterFunc(CMDMGR_OBJ, CMDMGR_RESET_CMD_FC, NULL, @TEMPLATE@_ResetAppCmd, 0); CMDMGR_RegisterFunc(CMDMGR_OBJ, @TEMPLATE@_TBL_LOAD_CMD_FC, TBLMGR_OBJ, TBLMGR_LoadTblCmd, TBLMGR_LOAD_TBL_CMD_DATA_LEN); CMDMGR_RegisterFunc(CMDMGR_OBJ, @TEMPLATE@_TBL_DUMP_CMD_FC, TBLMGR_OBJ, TBLMGR_DumpTblCmd, TBLMGR_DUMP_TBL_CMD_DATA_LEN); CMDMGR_RegisterFunc(CMDMGR_OBJ, EXOBJ_SET_MODE_CMD_FC, EXOBJ_OBJ, EXOBJ_SetModeCmd,EXOBJ_SET_MODE_CMD_DATA_LEN); /* Contained table object must be constructed prior to table registration because its table load function is called */ TBLMGR_Constructor(TBLMGR_OBJ); TBLMGR_RegisterTblWithDef(TBLMGR_OBJ, EXOBJTBL_LoadCmd, EXOBJTBL_DumpCmd, INITBL_GetStrConfig(INITBL_OBJ, CFG_TBL_LOAD_FILE)); /* ** Initialize app messages */ CFE_MSG_Init(CFE_MSG_PTR(@Template@.HkPkt.TlmHeader), CFE_SB_ValueToMsgId(@TEMPLATE@_HK_TLM_MID), @TEMPLATE@_TLM_HK_LEN); /* ** Application startup event message */ CFE_EVS_SendEvent(@TEMPLATE@_INIT_APP_EID, CFE_EVS_EventType_INFORMATION, "@TEMPLATE@ App Initialized. Version %d.%d.%d", @TEMPLATE@_MAJOR_VER, @TEMPLATE@_MINOR_VER, @TEMPLATE@_PLATFORM_REV); } /* End if CHILDMGR constructed */ return(Status); } /* End of InitApp() */ /****************************************************************************** ** Function: ProcessCommands ** ** */ static int32 ProcessCommands(void) { int32 RetStatus = CFE_ES_RunStatus_APP_RUN; int32 SysStatus; CFE_SB_Buffer_t* SbBufPtr; CFE_SB_MsgId_t MsgId = CFE_SB_INVALID_MSG_ID; CFE_ES_PerfLogExit(@Template@.PerfId); SysStatus = CFE_SB_ReceiveBuffer(&SbBufPtr, @Template@.CmdPipe, CFE_SB_PEND_FOREVER); CFE_ES_PerfLogEntry(@Template@.PerfId); if (SysStatus == CFE_SUCCESS) { SysStatus = CFE_MSG_GetMsgId(&SbBufPtr->Msg, &MsgId); if (SysStatus == CFE_SUCCESS) { if (CFE_SB_MsgId_Equal(MsgId, @Template@.CmdMid)) { CMDMGR_DispatchFunc(CMDMGR_OBJ, &SbBufPtr->Msg); } else if (CFE_SB_MsgId_Equal(MsgId, @Template@.ExecuteMid)) { EXOBJ_Execute(); } else if (CFE_SB_MsgId_Equal(MsgId, @Template@.SendHkMid)) { SendHousekeepingPkt(); } else { CFE_EVS_SendEvent(@TEMPLATE@_INVALID_MID_EID, CFE_EVS_EventType_ERROR, "Received invalid command packet, MID = 0x%08X", CFE_SB_MsgIdToValue(MsgId)); } } /* End if got message ID */ } /* End if received buffer */ else { RetStatus = CFE_ES_RunStatus_APP_ERROR; } return RetStatus; } /* End ProcessCommands() */
28.820189
152
0.625438
[ "object" ]
e7fdb04be6fa60e7f2a29c22768df2a5ce1a9b84
20,629
h
C
source/gameengine/Ketsji/KX_Scene.h
lordloki/upbge
18d0f5419cc1338ecf739362afef56bd96b42cfb
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2022-01-11T10:02:21.000Z
2022-01-11T10:02:21.000Z
source/gameengine/Ketsji/KX_Scene.h
lordloki/upbge
18d0f5419cc1338ecf739362afef56bd96b42cfb
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/gameengine/Ketsji/KX_Scene.h
lordloki/upbge
18d0f5419cc1338ecf739362afef56bd96b42cfb
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file KX_Scene.h * \ingroup ketsji */ #pragma once #include <list> #include <set> #include <vector> #include "EXP_PyObjectPlus.h" #include "EXP_Value.h" #include "KX_PhysicsEngineEnums.h" #include "KX_PythonComponentManager.h" #include "MT_Transform.h" #include "RAS_FramingManager.h" #include "RAS_Rect.h" #include "SCA_IScene.h" #include "SG_Frustum.h" #include "SG_Node.h" /** * \section Forward declarations */ struct SM_MaterialProps; struct SM_ShapeProps; struct Scene; template<class T> class CListValue; class CValue; class SCA_LogicManager; class SCA_KeyboardManager; class SCA_TimeEventManager; class SCA_MouseManager; class SCA_ISystem; class SCA_IInputDevice; class KX_NetworkMessageScene; class KX_NetworkMessageManager; class SG_Node; class SG_Node; class KX_Camera; class KX_FontObject; class KX_GameObject; class KX_LightObject; class RAS_MeshObject; class RAS_BucketManager; class RAS_MaterialBucket; class RAS_IPolyMaterial; class RAS_Rasterizer; class RAS_DebugDraw; class RAS_FrameBuffer; class RAS_2DFilter; class RAS_2DFilterManager; class KX_2DFilterManager; class SCA_JoystickManager; class btCollisionShape; class BL_BlenderSceneConverter; struct KX_ClientObjectInfo; class KX_ObstacleSimulation; struct TaskPool; /*********EEVEE INTEGRATION************/ struct GPUTexture; struct Object; /**************************************/ /* for ID freeing */ #define IS_TAGGED(_id) ((_id) && (((ID *)_id)->tag & LIB_TAG_DOIT)) /** * The KX_Scene holds all data for an independent scene. It relates * KX_Objects to the specific objects in the modules. * */ class KX_Scene : public CValue, public SCA_IScene { public: enum DrawingCallbackType { PRE_DRAW = 0, POST_DRAW, PRE_DRAW_SETUP, MAX_DRAW_CALLBACK }; struct AnimationPoolData { double curtime; }; private: Py_Header #ifdef WITH_PYTHON PyObject *m_attr_dict; PyObject *m_drawCallbacks[MAX_DRAW_CALLBACK]; PyObject *m_removeCallbacks; #endif protected: /***************EEVEE INTEGRATION*****************/ bool m_resetTaaSamples; Object *m_lastReplicatedParentObject; Object *m_gameDefaultCamera; int m_shadingTypeBackup; std::vector<struct Collection *> m_overlay_collections; struct GPUViewport *m_currentGPUViewport; /* In the current state of the code, we need this * to Initialize KX_BlenderMaterial and BL_Texture. * BL_Texture(s) is/are used for ImageRender. */ struct GPUViewport *m_initMaterialsGPUViewport; KX_Camera *m_overlayCamera; std::vector<KX_Camera *> m_imageRenderCameraList; BL_BlenderSceneConverter *m_sceneConverter; bool m_isPythonMainLoop; std::vector<KX_GameObject *> m_kxobWithLod; std::map<Object *, char> m_obRestrictFlags; bool m_collectionRemap; /*************************************************/ RAS_BucketManager *m_bucketmanager; std::vector<KX_GameObject *> m_tempObjectList; /** * The list of objects which have been removed during the * course of one frame. They are actually destroyed in * LogicEndFrame() via a call to RemoveObject(). */ std::vector<KX_GameObject *> m_euthanasyobjects; CListValue<KX_GameObject> *m_objectlist; CListValue<KX_GameObject> *m_parentlist; // all 'root' parents CListValue<KX_LightObject> *m_lightlist; CListValue<KX_GameObject> *m_inactivelist; // all objects that are not in the active layer /// All animated objects, no need of CListValue because the list isn't exposed in python. std::vector<KX_GameObject *> m_animatedlist; /// The set of cameras for this scene CListValue<KX_Camera> *m_cameralist; /// The set of fonts for this scene CListValue<KX_FontObject> *m_fontlist; SG_QList m_sghead; // list of nodes that needs scenegraph update // the Dlist is not object that must be updated // the Qlist is for objects that needs to be rescheduled // for updates after udpate is over (slow parent, bone parent) /** * Various SCA managers used by the scene */ SCA_LogicManager *m_logicmgr; SCA_KeyboardManager *m_keyboardmgr; SCA_MouseManager *m_mousemgr; SCA_TimeEventManager *m_timemgr; KX_PythonComponentManager m_componentManager; /** * physics engine abstraction */ // e_PhysicsEngine m_physicsEngine; //who needs this ? class PHY_IPhysicsEnvironment *m_physicsEnvironment; /** * The name of the scene */ std::string m_sceneName; /** * \section Different scenes, linked to ketsji scene */ /** * Network scene. */ KX_NetworkMessageScene *m_networkScene; /** * A temporary variable used to parent objects together on * replication. Don't get confused by the name it is not * the scene's root node! */ SG_Node *m_rootnode; /** * The active camera for the scene */ KX_Camera *m_active_camera; /// The active camera for scene culling. KX_Camera *m_overrideCullingCamera; /** * Another temporary variable outstaying its welcome * used in AddReplicaObject to map game objects to their * replicas so pointers can be updated. */ std::map<SCA_IObject *, SCA_IObject *> m_map_gameobject_to_replica; /** * Another temporary variable outstaying its welcome * used in AddReplicaObject to keep a record of all added * objects. Logic can only be updated when all objects * have been updated. This stores a list of the new objects. */ std::vector<KX_GameObject *> m_logicHierarchicalGameObjects; /** * This temporary variable will contain the list of * object that can be added during group instantiation. * objects outside this list will not be added (can * happen with children that are outside the group). * Used in AddReplicaObject. If the list is empty, it * means don't care. */ std::set<KX_GameObject *> m_groupGameObjects; /** * Pointer to system variable passed in in constructor * only used in constructor so we do not need to keep it * around in this class. */ SCA_ISystem *m_kxsystem; /** * The execution priority of replicated object actuators? */ int m_ueberExecutionPriority; /** * Radius in Manhattan distance of the box for activity culling. */ float m_activity_box_radius; /** * Toggle to enable or disable activity culling. */ bool m_activity_culling; /** * Toggle to enable or disable culling via DBVT broadphase of Bullet. */ bool m_dbvt_culling; /** * Occlusion culling resolution */ int m_dbvt_occlusion_res; /** * The framing settings used by this scene */ RAS_FrameSettings m_frame_settings; /** * This scenes viewport into the game engine * canvas.Maintained externally, initially [0,0] -> [0,0] */ RAS_Rect m_viewport; /** * Visibility testing functions. */ static void PhysicsCullingCallback(KX_ClientObjectInfo *objectInfo, void *cullingInfo); struct Scene *m_blenderScene; KX_2DFilterManager *m_filterManager; KX_ObstacleSimulation *m_obstacleSimulation; AnimationPoolData m_animationPoolData; TaskPool *m_animationPool; /** * LOD Hysteresis settings */ bool m_isActivedHysteresis; int m_lodHysteresisValue; // Convert objects list & collection helpers void convert_blender_objects_list_synchronous(std::vector<Object *> objectslist); void convert_blender_collection_synchronous(Collection *co); public: KX_Scene(SCA_IInputDevice *inputDevice, const std::string &scenename, struct Scene *scene, class RAS_ICanvas *canvas, KX_NetworkMessageManager *messageManager); virtual ~KX_Scene(); /******************EEVEE INTEGRATION************************/ void ResetTaaSamples(); void ConvertBlenderObject(struct Object *ob); void ConvertBlenderObjectsList(std::vector<Object *> objectslist, bool asynchronous); void ConvertBlenderCollection(struct Collection *co, bool asynchronous); bool m_isRuntime; // Too lazy to put that in protected std::vector<Object *> m_hiddenObjectsDuringRuntime; void RenderAfterCameraSetup(KX_Camera *cam, const RAS_Rect &viewport, bool is_overlay_pass); void RenderAfterCameraSetupImageRender(KX_Camera *cam, RAS_Rasterizer *rasty, const struct rcti *window); void SetLastReplicatedParentObject(Object *ob); Object *GetLastReplicatedParentObject(); void ResetLastReplicatedParentObject(); Object *GetGameDefaultCamera(); void ReinitBlenderContextVariables(); void BackupShadingType(); void AddOverlayCollection(KX_Camera *overlay_cam, struct Collection *collection); void RemoveOverlayCollection(struct Collection *collection); void SetCurrentGPUViewport(struct GPUViewport *viewport); struct GPUViewport *GetCurrentGPUViewport(); void SetInitMaterialsGPUViewport(struct GPUViewport *viewport); struct GPUViewport *GetInitMaterialsGPUViewport(); void SetOverlayCamera(KX_Camera *cam); KX_Camera *GetOverlayCamera(); void AddImageRenderCamera(KX_Camera *cam); void RemoveImageRenderCamera(KX_Camera *cam); bool CameraIsInactive(KX_Camera *cam); void SetIsPythonMainLoop(bool isPython); void AddObjToLodObjList(KX_GameObject *gameobj); void RemoveObjFromLodObjList(KX_GameObject *gameobj); void BackupRestrictFlag(Object *ob, char restrictFlag); void RestoreRestrictFlags(); void TagForCollectionRemap(); /***************End of EEVEE INTEGRATION**********************/ RAS_BucketManager *GetBucketManager() const; RAS_MaterialBucket *FindBucket(RAS_IPolyMaterial *polymat, bool &bucketCreated); /** * Update all transforms according to the scenegraph. */ static bool KX_ScenegraphUpdateFunc(SG_Node *node, void *gameobj, void *scene); static bool KX_ScenegraphRescheduleFunc(SG_Node *node, void *gameobj, void *scene); void UpdateParents(double curtime); void DupliGroupRecurse(KX_GameObject *groupobj, int level); bool IsObjectInGroup(KX_GameObject *gameobj) { return (m_groupGameObjects.empty() || m_groupGameObjects.find(gameobj) != m_groupGameObjects.end()); } void AddObjectDebugProperties(KX_GameObject *gameobj); KX_GameObject *AddReplicaObject(KX_GameObject *gameobj, KX_GameObject *locationobj, float lifespan = 0.0f); KX_GameObject *AddNodeReplicaObject(SG_Node *node, KX_GameObject *gameobj); void RemoveNodeDestructObject(SG_Node *node, KX_GameObject *gameobj); void RemoveObject(KX_GameObject *gameobj); void RemoveDupliGroup(KX_GameObject *gameobj); void DelayedRemoveObject(KX_GameObject *gameobj); void RemoveObjectSpawn(KX_GameObject *groupobj); bool NewRemoveObject(KX_GameObject *gameobj); void ReplaceMesh(KX_GameObject *gameobj, RAS_MeshObject *mesh, bool use_gfx, bool use_phys); void AddAnimatedObject(KX_GameObject *gameobj); /** * \section Logic stuff * Initiate an update of the logic system. */ void LogicBeginFrame(double curtime, double framestep); void LogicUpdateFrame(double curtime); void UpdateAnimations(double curtime); void LogicEndFrame(); CListValue<KX_GameObject> *GetObjectList() const; CListValue<KX_GameObject> *GetInactiveList() const; CListValue<KX_GameObject> *GetRootParentList() const; CListValue<KX_LightObject> *GetLightList() const; SCA_LogicManager *GetLogicManager() const; SCA_TimeEventManager *GetTimeEventManager() const; KX_PythonComponentManager& GetPythonComponentManager(); CListValue<KX_Camera> *GetCameraList() const; void SetCameraList(CListValue<KX_Camera> *camList); CListValue<KX_FontObject> *GetFontList() const; /** Find the currently active camera. */ KX_Camera *GetActiveCamera(); /** * Set this camera to be the active camera in the scene. If the * camera is not present in the camera list, it will be added */ void SetActiveCamera(class KX_Camera *); KX_Camera *GetOverrideCullingCamera() const; void SetOverrideCullingCamera(KX_Camera *cam); /** * Move this camera to the end of the list so that it is rendered last. * If the camera is not on the list, it will be added */ void SetCameraOnTop(class KX_Camera *); /** * Activates new desired canvas width set at design time. * \param width The new desired width. */ void SetCanvasDesignWidth(unsigned int width); /** * Activates new desired canvas height set at design time. * \param width The new desired height. */ void SetCanvasDesignHeight(unsigned int height); /** * Returns the current desired canvas width set at design time. * \return The desired width. */ unsigned int GetCanvasDesignWidth(void) const; /** * Returns the current desired canvas height set at design time. * \return The desired height. */ unsigned int GetCanvasDesignHeight(void) const; /** * Set the framing options for this scene */ void SetFramingType(RAS_FrameSettings &frame_settings); /** * Return a const reference to the framing * type set by the above call. * The contents are not guaranteed to be sensible * if you don't call the above function. */ const RAS_FrameSettings &GetFramingType() const; /** * \section Accessors to different scenes of this scene */ void SetNetworkMessageScene(KX_NetworkMessageScene *newScene); KX_NetworkMessageScene *GetNetworkMessageScene(); /// \section Debug draw. void RenderDebugProperties(RAS_DebugDraw &debugDraw, int xindent, int ysize, int &xcoord, int &ycoord, unsigned short propsMax); /** * Replicate the logic bricks associated to this object. */ void ReplicateLogic(class KX_GameObject *newobj); static SG_Callbacks m_callbacks; /// Update the mesh for objects based on level of detail settings void UpdateObjectLods(KX_Camera *cam /*, const KX_CullingNodeList& nodes*/); // LoD Hysteresis functions void SetLodHysteresis(bool active); bool IsActivedLodHysteresis(); void SetLodHysteresisValue(int hysteresisvalue); int GetLodHysteresisValue(); // Update the activity box settings for objects in this scene, if needed. void UpdateObjectActivity(void); // Enable/disable activity culling. void SetActivityCulling(bool b); // Set the radius of the activity culling box. void SetActivityCullingRadius(float f); // use of DBVT tree for camera culling void SetDbvtCulling(bool b) { m_dbvt_culling = b; } bool GetDbvtCulling() { return m_dbvt_culling; } void SetDbvtOcclusionRes(int i) { m_dbvt_occlusion_res = i; } int GetDbvtOcclusionRes() { return m_dbvt_occlusion_res; } void SetBlenderSceneConverter(class BL_BlenderSceneConverter *sceneConverter); class PHY_IPhysicsEnvironment *GetPhysicsEnvironment() { return m_physicsEnvironment; } void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *physEnv); void SetGravity(const MT_Vector3 &gravity); MT_Vector3 GetGravity(); short GetAnimationFPS(); /** * 2D Filters */ RAS_2DFilterManager *Get2DFilterManager() const; RAS_FrameBuffer *Render2DFilters(RAS_Rasterizer *rasty, RAS_ICanvas *canvas, RAS_FrameBuffer *inputfb, RAS_FrameBuffer *targetfb); KX_ObstacleSimulation *GetObstacleSimulation() { return m_obstacleSimulation; } /** Inherited from CValue -- returns the name of this object. */ virtual std::string GetName(); /** Inherited from CValue -- set the name of this object. */ virtual void SetName(const std::string &name); #ifdef WITH_PYTHON /* --------------------------------------------------------------------- */ /* Python interface ---------------------------------------------------- */ /* --------------------------------------------------------------------- */ KX_PYMETHOD_DOC(KX_Scene, addObject); KX_PYMETHOD_DOC(KX_Scene, end); KX_PYMETHOD_DOC(KX_Scene, restart); KX_PYMETHOD_DOC(KX_Scene, replace); KX_PYMETHOD_DOC(KX_Scene, get); KX_PYMETHOD_DOC(KX_Scene, drawObstacleSimulation); KX_PYMETHOD_DOC(KX_Scene, convertBlenderObject); KX_PYMETHOD_DOC(KX_Scene, convertBlenderObjectsList); KX_PYMETHOD_DOC(KX_Scene, convertBlenderCollection); KX_PYMETHOD_DOC(KX_Scene, addOverlayCollection); KX_PYMETHOD_DOC(KX_Scene, removeOverlayCollection); /* attributes */ static PyObject *pyattr_get_name(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_objects(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_objects_inactive(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_lights(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_texts(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_cameras(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_filter_manager(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static PyObject *pyattr_get_active_camera(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static int pyattr_set_active_camera(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); static PyObject *pyattr_get_overrideCullingCamera(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static int pyattr_set_overrideCullingCamera(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); static PyObject *pyattr_get_drawing_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static int pyattr_set_drawing_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); static PyObject *pyattr_get_remove_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static int pyattr_set_remove_callback(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); static PyObject *pyattr_get_gravity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef); static int pyattr_set_gravity(PyObjectPlus *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); /* getitem/setitem */ static PyMappingMethods Mapping; static PySequenceMethods Sequence; /** * Run the registered python drawing functions. */ void RunDrawingCallbacks(DrawingCallbackType callbackType, KX_Camera *camera); void RunOnRemoveCallbacks(); #endif /** * Returns the Blender scene this was made from */ struct Scene *GetBlenderScene() { return m_blenderScene; } bool MergeScene(KX_Scene *other); // void PrintStats(int verbose_level) { // m_bucketmanager->PrintStats(verbose_level) //} }; #ifdef WITH_PYTHON bool ConvertPythonToScene(PyObject *value, KX_Scene **scene, bool py_none_ok, const char *error_prefix); #endif typedef std::vector<KX_Scene *> KX_SceneList;
32.132399
114
0.700228
[ "mesh", "object", "vector" ]
e7fed192e57e6707ef05a7c00ce98cea87cf0c91
11,545
h
C
vnet/vnet/mpls/mpls.h
vpp-dev/span
f24fd80df661138dc510e07042a751efe762a401
[ "Apache-2.0" ]
1
2017-02-21T07:08:20.000Z
2017-02-21T07:08:20.000Z
vnet/vnet/mpls/mpls.h
vpp-dev/span
f24fd80df661138dc510e07042a751efe762a401
[ "Apache-2.0" ]
null
null
null
vnet/vnet/mpls/mpls.h
vpp-dev/span
f24fd80df661138dc510e07042a751efe762a401
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2015 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef included_vnet_mpls_gre_h #define included_vnet_mpls_gre_h #include <vnet/vnet.h> #include <vnet/gre/gre.h> #include <vnet/mpls/packet.h> #include <vnet/mpls/mpls_types.h> #include <vnet/ip/ip4_packet.h> #include <vnet/ethernet/ethernet.h> #include <vnet/fib/fib_node.h> #include <vnet/adj/adj.h> typedef CLIB_PACKED (struct { ip4_header_t ip4; /* 20 bytes */ gre_header_t gre; /* 4 bytes */ mpls_unicast_header_t labels[0]; /* 4 bytes each */ }) ip4_gre_and_mpls_header_t; extern vnet_hw_interface_class_t mpls_gre_hw_interface_class; typedef enum { #define mpls_error(n,s) MPLS_ERROR_##n, #include <vnet/mpls/error.def> #undef mpls_error MPLS_N_ERROR, } mpls_gre_error_t; /* * No protocol info, MPLS labels don't have a next-header field * presumably the label field tells all... */ typedef struct { fib_node_t mgt_node; ip4_address_t tunnel_src; ip4_address_t tunnel_dst; ip4_address_t intfc_address; u32 mask_width; u32 inner_fib_index; u32 outer_fib_index; u32 encap_index; u32 hw_if_index; /* L2 x-connect capable tunnel intfc */ u8 * rewrite_data; u8 l2_only; fib_node_index_t fei; /* FIB Entry index for the tunnel's destination */ adj_index_t adj_index; /* The midchain adj this tunnel creates */ u32 sibling_index; } mpls_gre_tunnel_t; typedef struct { u8 tunnel_dst[6]; ip4_address_t intfc_address; u32 tx_sw_if_index; u32 inner_fib_index; u32 mask_width; u32 encap_index; u32 hw_if_index; u8 * rewrite_data; u8 l2_only; fib_node_index_t fei; } mpls_eth_tunnel_t; typedef struct { mpls_unicast_header_t *labels; /* only for policy tunnels */ u8 * rewrite; u32 output_next_index; } mpls_encap_t; typedef struct { u32 tx_fib_index; u32 next_index; /* e.g. ip4/6-input, l2-input */ } mpls_decap_t; #define MPLS_FIB_DEFAULT_TABLE_ID 0 /** * Type exposure is to allow the DP fast/inlined access */ #define MPLS_FIB_KEY_SIZE 21 #define MPLS_FIB_DB_SIZE (1 << (MPLS_FIB_KEY_SIZE-1)) typedef struct mpls_fib_t_ { /** * A hash table of entries. 21 bit key * Hash table for reduced memory footprint */ uword * mf_entries; /** * The load-balance indeices keyed by 21 bit label+eos bit. * A flat array for maximum lookup performace. */ index_t mf_lbs[MPLS_FIB_DB_SIZE]; } mpls_fib_t; /** * @brief Definition of a callback for receiving MPLS interface state change * notifications */ typedef void (*mpls_interface_state_change_callback_t)(u32 sw_if_index, u32 is_enable); typedef struct { /* MPLS FIB index for each software interface */ u32 *fib_index_by_sw_if_index; /** A pool of all the MPLS FIBs */ struct fib_table_t_ *fibs; /** A hash table to lookup the mpls_fib by table ID */ uword *fib_index_by_table_id; /* rx/tx interface/feature configuration. */ ip_config_main_t feature_config_mains[VNET_N_IP_FEAT]; /* Built-in unicast feature path indices, see ip_feature_init_cast(...) */ u32 mpls_rx_feature_lookup; u32 mpls_rx_feature_not_enabled; u32 mpls_tx_feature_interface_output; /* pool of gre tunnel instances */ mpls_gre_tunnel_t *gre_tunnels; u32 * free_gre_sw_if_indices; /* pool of ethernet tunnel instances */ mpls_eth_tunnel_t *eth_tunnels; u32 * free_eth_sw_if_indices; /* Encap side: map (fib, dst_address) to mpls label stack */ mpls_encap_t * encaps; uword * mpls_encap_by_fib_and_dest; /* Decap side: map rx label to FIB */ mpls_decap_t * decaps; uword * mpls_decap_by_rx_fib_and_label; /* mpls-o-e policy tunnel next index for ip4/ip6-classify */ u32 ip4_classify_mpls_policy_encap_next_index; u32 ip6_classify_mpls_policy_encap_next_index; /* feature path configuration lists */ vnet_ip_feature_registration_t * next_feature[VNET_N_IP_FEAT]; /* Save feature results for show command */ char **feature_nodes[VNET_N_IP_FEAT]; /* IP4 enabled count by software interface */ u8 * mpls_enabled_by_sw_if_index; /* Functions to call when MPLS state on an interface changes. */ mpls_interface_state_change_callback_t * mpls_interface_state_change_callbacks; /* convenience */ vlib_main_t * vlib_main; vnet_main_t * vnet_main; } mpls_main_t; extern mpls_main_t mpls_main; #define VNET_MPLS_FEATURE_INIT(x,...) \ __VA_ARGS__ vnet_ip_feature_registration_t uc_##x; \ static void __vnet_add_feature_registration_uc_##x (void) \ __attribute__((__constructor__)) ; \ static void __vnet_add_feature_registration_uc_##x (void) \ { \ mpls_main_t * mm = &mpls_main; \ uc_##x.next = mm->next_feature[VNET_IP_RX_UNICAST_FEAT]; \ mm->next_feature[VNET_IP_RX_UNICAST_FEAT] = &uc_##x; \ } \ __VA_ARGS__ vnet_ip_feature_registration_t uc_##x #define VNET_MPLS_TX_FEATURE_INIT(x,...) \ __VA_ARGS__ vnet_ip_feature_registration_t tx_##x; \ static void __vnet_add_feature_registration_tx_##x (void) \ __attribute__((__constructor__)) ; \ static void __vnet_add_feature_registration_tx_##x (void) \ { \ mpls_main_t * mm = &mpls_main; \ tx_##x.next = mm->next_feature[VNET_IP_TX_FEAT]; \ mm->next_feature[VNET_IP_TX_FEAT] = &tx_##x; \ } \ __VA_ARGS__ vnet_ip_feature_registration_t tx_##x extern clib_error_t * mpls_feature_init(vlib_main_t * vm); format_function_t format_mpls_protocol; format_function_t format_mpls_gre_header_with_length; format_function_t format_mpls_eth_header_with_length; format_function_t format_mpls_encap_index; format_function_t format_mpls_eos_bit; format_function_t format_mpls_unicast_header_net_byte_order; format_function_t format_mpls_unicast_label; format_function_t format_mpls_header; extern vlib_node_registration_t mpls_input_node; extern vlib_node_registration_t mpls_policy_encap_node; extern vlib_node_registration_t mpls_output_node; extern vlib_node_registration_t mpls_midchain_node; extern vnet_device_class_t mpls_gre_device_class; /* Parse mpls protocol as 0xXXXX or protocol name. In either host or network byte order. */ unformat_function_t unformat_mpls_protocol_host_byte_order; unformat_function_t unformat_mpls_protocol_net_byte_order; unformat_function_t unformat_mpls_label_net_byte_order; unformat_function_t unformat_mpls_gre_header; unformat_function_t unformat_pg_mpls_gre_header; unformat_function_t unformat_mpls_unicast_label; /* Parse mpls header. */ unformat_function_t unformat_mpls_header; unformat_function_t unformat_pg_mpls_header; /* manually added to the interface output node in mpls.c */ #define MPLS_GRE_OUTPUT_NEXT_LOOKUP 1 #define MPLS_GRE_OUTPUT_NEXT_DROP VNET_INTERFACE_TX_NEXT_DROP void mpls_sw_interface_enable_disable (mpls_main_t * mm, u32 sw_if_index, u8 is_enable); u8 mpls_sw_interface_is_enabled (u32 sw_if_index); mpls_encap_t * mpls_encap_by_fib_and_dest (mpls_main_t * mm, u32 rx_fib, u32 dst_address); int mpls_label_from_fib_id_and_dest (mpls_main_t *gm, u32 fib_id, u32 dst_address, u32 *labelp); int vnet_mpls_gre_add_del_tunnel (ip4_address_t *src, ip4_address_t *dst, ip4_address_t *intfc, u32 mask_width, u32 inner_fib_id, u32 outer_fib_id, u32 * tunnel_intfc_sw_if_index, u8 l2_only, u8 is_add); int vnet_mpls_ethernet_add_del_tunnel (u8 *dst, ip4_address_t *intfc, u32 mask_width, u32 inner_fib_id, u32 tx_sw_if_index, u32 * tunnel_sw_if_index, u8 l2_only, u8 is_add); int vnet_mpls_gre_delete_fib_tunnels (u32 fib_id); int mpls_fib_reset_labels (u32 fib_id); int vnet_mpls_add_del_decap (u32 rx_fib_id, u32 tx_fib_id, u32 label_host_byte_order, int s_bit, int next_index, int is_add); int vnet_mpls_add_del_encap (ip4_address_t *dest, u32 fib_id, u32 *labels_host_byte_order, u32 policy_tunnel_index, int no_dst_hash, u32 * indexp, int is_add); int vnet_mpls_policy_tunnel_add_rewrite (mpls_main_t * mm, mpls_encap_t * e, u32 policy_tunnel_index); typedef struct { u32 lookup_miss; /* Tunnel-id / index in tunnel vector */ u32 tunnel_id; /* mpls encap index */ u32 mpls_encap_index; /* pkt length */ u32 length; /* tunnel ip4 addresses */ ip4_address_t src; ip4_address_t dst; } mpls_gre_tx_trace_t; u8 * format_mpls_gre_tx_trace (u8 * s, va_list * args); u8 * format_mpls_gre_header (u8 * s, va_list * args); #define foreach_mpls_input_next \ _(DROP, "error-drop") \ _(LOOKUP, "mpls-lookup") typedef enum { #define _(s,n) MPLS_INPUT_NEXT_##s, foreach_mpls_input_next #undef _ MPLS_INPUT_N_NEXT, } mpls_input_next_t; #define foreach_mpls_lookup_next \ _(DROP, "error-drop") \ _(IP4_INPUT, "ip4-input") \ _(L2_OUTPUT, "l2-output") // FIXME remove. typedef enum { #define _(s,n) MPLS_LOOKUP_NEXT_##s, foreach_mpls_lookup_next #undef _ MPLS_LOOKUP_N_NEXT, } mpls_lookup_next_t; #define foreach_mpls_output_next \ _(DROP, "error-drop") typedef enum { #define _(s,n) MPLS_OUTPUT_NEXT_##s, foreach_mpls_output_next #undef _ MPLS_OUTPUT_N_NEXT, } mpls_output_next_t; typedef struct { u32 lookup_miss; /* Tunnel-id / index in tunnel vector */ u32 tunnel_id; /* output interface */ u32 tx_sw_if_index; /* mpls encap index */ u32 mpls_encap_index; /* pkt length */ u32 length; u8 dst[6]; } mpls_eth_tx_trace_t; u8 * format_mpls_eth_tx_trace (u8 * s, va_list * args); typedef struct { u32 fib_index; u32 entry_index; u32 dest; u32 s_bit; u32 label; } show_mpls_fib_t; int mpls_dest_cmp(void * a1, void * a2); int mpls_fib_index_cmp(void * a1, void * a2); int mpls_label_cmp(void * a1, void * a2); #endif /* included_vnet_mpls_gre_h */
30.704787
81
0.665656
[ "vector" ]
f00816c2ab3c724352f9a2d35c0da39a51f8bfd8
1,201
h
C
StRoot/Sti/Base/Described.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/Sti/Base/Described.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/Sti/Base/Described.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
#if !defined(AFX_DESCRIBED_H__AD46D0D8_4A85_45BE_AB18_B64D1E2A4658__INCLUDED_) #define AFX_DESCRIBED_H__AD46D0D8_4A85_45BE_AB18_B64D1E2A4658__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <string> using std::string; /*! \class Described This class encapsulates the notion of "Described". It should be used as base class to provide a "Described" property to objects. \author Claude A Pruneau */ class Described { public: virtual ~Described(); /// Set the Describe of the object void setDescription(const string & description); /// Get the Describe of the object const string getDescription() const; /// Determine whether Describe is set, i.e object has a Describe bool isDescribed() const; /// Determine whether Describe equals given Describe bool isDescription(const string & description) const; /// Determine whether Describe equals that of given object bool sameDescriptionAs(const Described & described) const; protected: /// Only derived class are Described Described(const string & aDescribe=" "); string _description; }; #endif // !defined(AFX_DESCRIBED_H__AD46D0D8_4A85_45BE_AB18_B64D1E2A4658__INCLUDED_)
25.553191
84
0.761865
[ "object" ]
f009cb4386148722f6781543b899957d0cc65fff
6,004
h
C
src/CGAL/Iso_cuboid_3.h
compTAG/r-tda-testA
26d3ff6215b544571c48ebb3039e95ca18974789
[ "BSL-1.0" ]
null
null
null
src/CGAL/Iso_cuboid_3.h
compTAG/r-tda-testA
26d3ff6215b544571c48ebb3039e95ca18974789
[ "BSL-1.0" ]
5
2018-05-18T22:25:52.000Z
2018-05-18T22:35:13.000Z
src/CGAL/Iso_cuboid_3.h
compTAG/r-tda-testA
26d3ff6215b544571c48ebb3039e95ca18974789
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 1999 // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL: https://github.com/CGAL/cgal/blob/v5.3.1/Kernel_23/include/CGAL/Iso_cuboid_3.h $ // $Id: Iso_cuboid_3.h 4e519a3 2021-05-05T13:15:37+02:00 Sébastien Loriot // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : Stefan Schirra #ifndef CGAL_ISO_CUBOID_3_H #define CGAL_ISO_CUBOID_3_H #include <CGAL/assertions.h> #include <boost/type_traits/is_same.hpp> #include <CGAL/Kernel/Return_base_tag.h> #include <CGAL/Bbox_3.h> #include <CGAL/Dimension.h> namespace CGAL { template <class R_> class Iso_cuboid_3 : public R_::Kernel_base::Iso_cuboid_3 { typedef typename R_::RT RT; typedef typename R_::Point_3 Point_3; typedef typename R_::Aff_transformation_3 Aff_transformation_3; typedef Iso_cuboid_3 Self; CGAL_static_assertion((boost::is_same<Self, typename R_::Iso_cuboid_3>::value)); public: typedef Dimension_tag<3> Ambient_dimension; typedef Dimension_tag<3> Feature_dimension; typedef typename R_::Kernel_base::Iso_cuboid_3 Rep; const Rep& rep() const { return *this; } Rep& rep() { return *this; } typedef R_ R; Iso_cuboid_3() {} Iso_cuboid_3(const Rep& r) : Rep(r) {} Iso_cuboid_3(const Point_3& p, const Point_3& q) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), p,q)) {} Iso_cuboid_3(const Point_3& p, const Point_3& q, int) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), p, q, 0)) {} Iso_cuboid_3(const Point_3 &left, const Point_3 &right, const Point_3 &bottom, const Point_3 &top, const Point_3 &far_, const Point_3 &close) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), left, right, bottom, top, far_, close)) {} Iso_cuboid_3(const RT& min_hx, const RT& min_hy, const RT& min_hz, const RT& max_hx, const RT& max_hy, const RT& max_hz, const RT& hw) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), min_hx, min_hy, min_hz, max_hx, max_hy, max_hz, hw)) {} Iso_cuboid_3(const RT& min_hx, const RT& min_hy, const RT& min_hz, const RT& max_hx, const RT& max_hy, const RT& max_hz) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), min_hx, min_hy, min_hz, max_hx, max_hy, max_hz)) {} Iso_cuboid_3(const Bbox_3& bbox) : Rep(typename R::Construct_iso_cuboid_3()(Return_base_tag(), bbox.xmin(), bbox.ymin(), bbox.zmin(), bbox.xmax(), bbox.ymax(), bbox.zmax())) {} decltype(auto) min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return R().construct_min_vertex_3_object()(*this); } decltype(auto) max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return R().construct_max_vertex_3_object()(*this); } decltype(auto) vertex(int i) const { return R().construct_vertex_3_object()(*this,i); } decltype(auto) operator[](int i) const { return R().construct_vertex_3_object()(*this,i); } decltype(auto) xmin() const { return R().compute_xmin_3_object()(*this); } decltype(auto) xmax() const { return R().compute_xmax_3_object()(*this); } decltype(auto) ymin() const { return R().compute_ymin_3_object()(*this); } decltype(auto) ymax() const { return R().compute_ymax_3_object()(*this); } decltype(auto) zmin() const { return R().compute_zmin_3_object()(*this); } decltype(auto) zmax() const { return R().compute_zmax_3_object()(*this); } decltype(auto) min_coord(int i) const { CGAL_kernel_precondition( i == 0 || i == 1 || i == 2 ); if (i == 0) return xmin(); else if (i == 1) return ymin(); else return zmin(); } decltype(auto) max_coord(int i) const { CGAL_kernel_precondition( i == 0 || i == 1 || i == 2 ); if (i == 0) return xmax(); else if (i == 1) return ymax(); else return zmax(); } bool has_on_bounded_side(const Point_3 &p) const { return R().has_on_bounded_side_3_object()(*this,p); } bool has_on_unbounded_side(const Point_3 &p) const { return R().has_on_unbounded_side_3_object()(*this,p); } bool has_on_boundary(const Point_3 &p) const { return R().has_on_boundary_3_object()(*this,p); } bool has_on(const Point_3 &p) const { return has_on_boundary(p); } Bounded_side bounded_side(const Point_3 &p) const { return R().bounded_side_3_object()(*this,p); } bool is_degenerate() const { return R().is_degenerate_3_object()(*this); } decltype(auto) volume() const { return R().compute_volume_3_object()(*this); } Bbox_3 bbox() const { return R().construct_bbox_3_object()(*this); } Iso_cuboid_3 transform(const Aff_transformation_3 &t) const { return Iso_cuboid_3(t.transform((this->min)()), t.transform((this->max)())); } }; template < class R > std::ostream & operator<<(std::ostream& os, const Iso_cuboid_3<R>& r) { switch(IO::get_mode(os)) { case IO::ASCII : return os << (r.min)() << ' ' << (r.max)(); case IO::BINARY : return os << (r.min)() << (r.max)(); default: return os << "Iso_cuboid_3(" << (r.min)() << ", " << (r.max)() << ")"; } } template < class R > std::istream & operator>>(std::istream& is, Iso_cuboid_3<R>& r) { typename R::Point_3 p, q; is >> p >> q; if (is) r = Iso_cuboid_3<R>(p, q); return is; } } //namespace CGAL #endif // CGAL_ISO_CUBOID_3_H
23.271318
107
0.617089
[ "transform" ]
f00bd9a480f92e4531a15ab88e6a493de8a25528
3,878
c
C
message_options.c
yangchaogit/php-protocolbuffers
f018ee2fbcfa86915a4c458dfb2d81ab0bd1d697
[ "BSD-2-Clause" ]
99
2015-01-15T06:45:48.000Z
2022-01-02T05:58:14.000Z
message_options.c
yangchaogit/php-protocolbuffers
f018ee2fbcfa86915a4c458dfb2d81ab0bd1d697
[ "BSD-2-Clause" ]
13
2015-01-08T08:41:02.000Z
2018-11-16T03:14:58.000Z
message_options.c
yangchaogit/php-protocolbuffers
f018ee2fbcfa86915a4c458dfb2d81ab0bd1d697
[ "BSD-2-Clause" ]
35
2015-01-15T06:45:52.000Z
2019-05-13T03:54:07.000Z
/* * Protocol Buffers for PHP * Copyright 2013 Shuhei Tanuma. All rights reserved. * * https://github.com/chobie/php-protocolbuffers * * 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "protocolbuffers.h" #include "message_options.h" int php_protocolbuffers_message_options_init_properties(zval *object TSRMLS_DC) { HashTable *properties = NULL; zval *tmp = NULL; ALLOC_HASHTABLE(properties); zend_hash_init(properties, 0, NULL, ZVAL_PTR_DTOR, 0); MAKE_STD_ZVAL(tmp); array_init(tmp); zend_hash_update(properties, "extensions", sizeof("extensions"), (void **)&tmp, sizeof(zval), NULL); zend_merge_properties(object, properties, 1 TSRMLS_CC); return 0; } ZEND_BEGIN_ARG_INFO_EX(arginfo_protocolbuffers_message_options_get_options, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() /* {{{ proto ProtocolBuffers_MessageOptions::getExtension(string $name) */ PHP_METHOD(protocolbuffers_message_options, getExtension) { zval **result = NULL, *options = NULL; char *name = {0}; long name_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } options = zend_read_property(php_protocol_buffers_descriptor_builder_class_entry, getThis(), ZEND_STRS("extensions")-1, 1 TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(options), name, name_len, (void **)&result) != SUCCESS) { if (strcmp(name, "php") == 0) { zval *obj; MAKE_STD_ZVAL(obj); object_init_ex(obj, php_protocol_buffers_php_message_options_class_entry); zend_hash_update(Z_ARRVAL_P(options), name, name_len+1, (void **)&obj, sizeof(obj), NULL); result = &obj; } else { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "%s extension does not support. now only supports php extension", name); return; } } RETURN_ZVAL(*result, 1, 0); } /* }}} */ static zend_function_entry php_protocolbuffers_message_options_methods[] = { PHP_ME(protocolbuffers_message_options, getExtension, arginfo_protocolbuffers_message_options_get_options, ZEND_ACC_PUBLIC) PHP_FE_END }; void php_protocolbuffers_message_options_class(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "ProtocolBuffersMessageOptions", php_protocolbuffers_message_options_methods); php_protocol_buffers_message_options_class_entry = zend_register_internal_class(&ce TSRMLS_CC); zend_declare_property_null(php_protocol_buffers_message_options_class_entry, ZEND_STRS("extensions")-1, ZEND_ACC_PUBLIC TSRMLS_CC); PHP_PROTOCOLBUFFERS_REGISTER_NS_CLASS_ALIAS(PHP_PROTOCOLBUFFERS_NAMESPACE, "MessageOptions", php_protocol_buffers_message_options_class_entry); }
37.288462
145
0.780557
[ "object" ]
f0125401883f335ad8c6bd381f4d65f39b0e284f
232,580
h
C
tcss/include/tencentcloud/tcss/v20201101/TcssClient.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/include/tencentcloud/tcss/v20201101/TcssClient.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/include/tencentcloud/tcss/v20201101/TcssClient.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_TCSS_V20201101_TCSSCLIENT_H_ #define TENCENTCLOUD_TCSS_V20201101_TCSSCLIENT_H_ #include <functional> #include <future> #include <tencentcloud/core/AbstractClient.h> #include <tencentcloud/core/Credential.h> #include <tencentcloud/core/profile/ClientProfile.h> #include <tencentcloud/core/AsyncCallerContext.h> #include <tencentcloud/tcss/v20201101/model/AddAssetImageRegistryRegistryDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/AddAssetImageRegistryRegistryDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/AddCompliancePolicyItemToWhitelistRequest.h> #include <tencentcloud/tcss/v20201101/model/AddCompliancePolicyItemToWhitelistResponse.h> #include <tencentcloud/tcss/v20201101/model/AddEditAbnormalProcessRuleRequest.h> #include <tencentcloud/tcss/v20201101/model/AddEditAbnormalProcessRuleResponse.h> #include <tencentcloud/tcss/v20201101/model/AddEditAccessControlRuleRequest.h> #include <tencentcloud/tcss/v20201101/model/AddEditAccessControlRuleResponse.h> #include <tencentcloud/tcss/v20201101/model/AddEditReverseShellWhiteListRequest.h> #include <tencentcloud/tcss/v20201101/model/AddEditReverseShellWhiteListResponse.h> #include <tencentcloud/tcss/v20201101/model/AddEditRiskSyscallWhiteListRequest.h> #include <tencentcloud/tcss/v20201101/model/AddEditRiskSyscallWhiteListResponse.h> #include <tencentcloud/tcss/v20201101/model/AddEditWarningRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/AddEditWarningRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/CheckRepeatAssetImageRegistryRequest.h> #include <tencentcloud/tcss/v20201101/model/CheckRepeatAssetImageRegistryResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageRegistryScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageRegistryScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageRegistryScanTaskOneKeyRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageRegistryScanTaskOneKeyResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageScanSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageScanSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateAssetImageScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateCheckComponentRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateCheckComponentResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateClusterCheckTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateClusterCheckTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateComplianceTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateComplianceTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateExportComplianceStatusListJobRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateExportComplianceStatusListJobResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateOrModifyPostPayCoresRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateOrModifyPostPayCoresResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateRefreshTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateRefreshTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateVirusScanAgainRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateVirusScanAgainResponse.h> #include <tencentcloud/tcss/v20201101/model/CreateVirusScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/CreateVirusScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/DeleteAbnormalProcessRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/DeleteAbnormalProcessRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/DeleteAccessControlRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/DeleteAccessControlRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/DeleteCompliancePolicyItemFromWhitelistRequest.h> #include <tencentcloud/tcss/v20201101/model/DeleteCompliancePolicyItemFromWhitelistResponse.h> #include <tencentcloud/tcss/v20201101/model/DeleteReverseShellWhiteListsRequest.h> #include <tencentcloud/tcss/v20201101/model/DeleteReverseShellWhiteListsResponse.h> #include <tencentcloud/tcss/v20201101/model/DeleteRiskSyscallWhiteListsRequest.h> #include <tencentcloud/tcss/v20201101/model/DeleteRiskSyscallWhiteListsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessEventsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessEventsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessEventsExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessEventsExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRuleDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRuleDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRulesExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAbnormalProcessRulesExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlEventsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlEventsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlEventsExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlEventsExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRuleDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRuleDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRulesExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAccessControlRulesExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedClusterCountRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedClusterCountResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedNodeListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedNodeListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedWorkloadListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAffectedWorkloadListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetAppServiceListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetAppServiceListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetComponentListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetComponentListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetContainerDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetContainerDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetContainerListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetContainerListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetDBServiceListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetDBServiceListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetHostDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetHostDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetHostListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetHostListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageBindRuleInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageBindRuleInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageHostListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageHostListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryAssetStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryAssetStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRegistryDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRegistryDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRegistryListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRegistryListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRiskInfoListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRiskInfoListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRiskListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryRiskListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryScanStatusOneKeyRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryScanStatusOneKeyResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistrySummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistrySummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVirusListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVirusListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVirusListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVirusListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVulListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVulListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVulListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRegistryVulListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRiskListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRiskListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRiskListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageRiskListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageSimpleListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageSimpleListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVirusListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVirusListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVirusListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVirusListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVulListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVulListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVulListExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetImageVulListExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetPortListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetPortListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetProcessListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetProcessListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetWebServiceListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeAssetWebServiceListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeCheckItemListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeCheckItemListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeClusterDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeClusterDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeClusterSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeClusterSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetDetailInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetDetailInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetPolicyItemListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceAssetPolicyItemListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePeriodTaskListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePeriodTaskListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePolicyItemAffectedAssetListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePolicyItemAffectedAssetListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePolicyItemAffectedSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeCompliancePolicyItemAffectedSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceScanFailedAssetListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceScanFailedAssetListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceTaskAssetSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceTaskAssetSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceTaskPolicyItemSummaryListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceTaskPolicyItemSummaryListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceWhitelistItemListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeComplianceWhitelistItemListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeContainerAssetSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeContainerAssetSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeContainerSecEventSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeContainerSecEventSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventsExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeEventsExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeRuleInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeRuleInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeSafeStateRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeEscapeSafeStateResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeExportJobResultRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeExportJobResultResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageAuthorizedInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageAuthorizedInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRegistryTimingScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRegistryTimingScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRiskSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRiskSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRiskTendencyRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageRiskTendencyResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageSimpleListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeImageSimpleListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribePostPayDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribePostPayDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeProVersionInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeProVersionInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribePurchaseStateInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribePurchaseStateInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRefreshTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRefreshTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellEventsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellEventsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellEventsExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellEventsExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellWhiteListDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellWhiteListDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellWhiteListsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeReverseShellWhiteListsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallEventsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallEventsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallEventsExportRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallEventsExportResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallNamesRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallNamesResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallWhiteListDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallWhiteListDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallWhiteListsRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeRiskSyscallWhiteListsResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeSecEventsTendencyRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeSecEventsTendencyResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeTaskResultSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeTaskResultSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeUnfinishRefreshTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeUnfinishRefreshTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeUserClusterRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeUserClusterResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeValueAddedSrvInfoRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeValueAddedSrvInfoResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusMonitorSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusMonitorSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanTaskStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanTaskStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanTimeoutSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusScanTimeoutSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusSummaryRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusSummaryResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusTaskListRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeVirusTaskListResponse.h> #include <tencentcloud/tcss/v20201101/model/DescribeWarningRulesRequest.h> #include <tencentcloud/tcss/v20201101/model/DescribeWarningRulesResponse.h> #include <tencentcloud/tcss/v20201101/model/ExportVirusListRequest.h> #include <tencentcloud/tcss/v20201101/model/ExportVirusListResponse.h> #include <tencentcloud/tcss/v20201101/model/InitializeUserComplianceEnvironmentRequest.h> #include <tencentcloud/tcss/v20201101/model/InitializeUserComplianceEnvironmentResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAbnormalProcessRuleStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAbnormalProcessRuleStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAbnormalProcessStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAbnormalProcessStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAccessControlRuleStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAccessControlRuleStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAccessControlStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAccessControlStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageRegistryScanStopRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageRegistryScanStopResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageRegistryScanStopOneKeyRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageRegistryScanStopOneKeyResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageScanStopRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyAssetImageScanStopResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyCompliancePeriodTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyCompliancePeriodTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyEscapeEventStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyEscapeEventStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyEscapeRuleRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyEscapeRuleResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyReverseShellStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyReverseShellStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyRiskSyscallStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyRiskSyscallStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusFileStatusRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusFileStatusResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusMonitorSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusMonitorSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusScanSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusScanSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusScanTimeoutSettingRequest.h> #include <tencentcloud/tcss/v20201101/model/ModifyVirusScanTimeoutSettingResponse.h> #include <tencentcloud/tcss/v20201101/model/RemoveAssetImageRegistryRegistryDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/RemoveAssetImageRegistryRegistryDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/RenewImageAuthorizeStateRequest.h> #include <tencentcloud/tcss/v20201101/model/RenewImageAuthorizeStateResponse.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceAssetsRequest.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceAssetsResponse.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceAssetsByPolicyItemRequest.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceAssetsByPolicyItemResponse.h> #include <tencentcloud/tcss/v20201101/model/ScanCompliancePolicyItemsRequest.h> #include <tencentcloud/tcss/v20201101/model/ScanCompliancePolicyItemsResponse.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceScanFailedAssetsRequest.h> #include <tencentcloud/tcss/v20201101/model/ScanComplianceScanFailedAssetsResponse.h> #include <tencentcloud/tcss/v20201101/model/SetCheckModeRequest.h> #include <tencentcloud/tcss/v20201101/model/SetCheckModeResponse.h> #include <tencentcloud/tcss/v20201101/model/StopVirusScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/StopVirusScanTaskResponse.h> #include <tencentcloud/tcss/v20201101/model/SyncAssetImageRegistryAssetRequest.h> #include <tencentcloud/tcss/v20201101/model/SyncAssetImageRegistryAssetResponse.h> #include <tencentcloud/tcss/v20201101/model/UpdateAssetImageRegistryRegistryDetailRequest.h> #include <tencentcloud/tcss/v20201101/model/UpdateAssetImageRegistryRegistryDetailResponse.h> #include <tencentcloud/tcss/v20201101/model/UpdateImageRegistryTimingScanTaskRequest.h> #include <tencentcloud/tcss/v20201101/model/UpdateImageRegistryTimingScanTaskResponse.h> namespace TencentCloud { namespace Tcss { namespace V20201101 { class TcssClient : public AbstractClient { public: TcssClient(const Credential &credential, const std::string &region); TcssClient(const Credential &credential, const std::string &region, const ClientProfile &profile); typedef Outcome<Core::Error, Model::AddAssetImageRegistryRegistryDetailResponse> AddAssetImageRegistryRegistryDetailOutcome; typedef std::future<AddAssetImageRegistryRegistryDetailOutcome> AddAssetImageRegistryRegistryDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddAssetImageRegistryRegistryDetailRequest&, AddAssetImageRegistryRegistryDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddAssetImageRegistryRegistryDetailAsyncHandler; typedef Outcome<Core::Error, Model::AddCompliancePolicyItemToWhitelistResponse> AddCompliancePolicyItemToWhitelistOutcome; typedef std::future<AddCompliancePolicyItemToWhitelistOutcome> AddCompliancePolicyItemToWhitelistOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddCompliancePolicyItemToWhitelistRequest&, AddCompliancePolicyItemToWhitelistOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddCompliancePolicyItemToWhitelistAsyncHandler; typedef Outcome<Core::Error, Model::AddEditAbnormalProcessRuleResponse> AddEditAbnormalProcessRuleOutcome; typedef std::future<AddEditAbnormalProcessRuleOutcome> AddEditAbnormalProcessRuleOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddEditAbnormalProcessRuleRequest&, AddEditAbnormalProcessRuleOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddEditAbnormalProcessRuleAsyncHandler; typedef Outcome<Core::Error, Model::AddEditAccessControlRuleResponse> AddEditAccessControlRuleOutcome; typedef std::future<AddEditAccessControlRuleOutcome> AddEditAccessControlRuleOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddEditAccessControlRuleRequest&, AddEditAccessControlRuleOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddEditAccessControlRuleAsyncHandler; typedef Outcome<Core::Error, Model::AddEditReverseShellWhiteListResponse> AddEditReverseShellWhiteListOutcome; typedef std::future<AddEditReverseShellWhiteListOutcome> AddEditReverseShellWhiteListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddEditReverseShellWhiteListRequest&, AddEditReverseShellWhiteListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddEditReverseShellWhiteListAsyncHandler; typedef Outcome<Core::Error, Model::AddEditRiskSyscallWhiteListResponse> AddEditRiskSyscallWhiteListOutcome; typedef std::future<AddEditRiskSyscallWhiteListOutcome> AddEditRiskSyscallWhiteListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddEditRiskSyscallWhiteListRequest&, AddEditRiskSyscallWhiteListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddEditRiskSyscallWhiteListAsyncHandler; typedef Outcome<Core::Error, Model::AddEditWarningRulesResponse> AddEditWarningRulesOutcome; typedef std::future<AddEditWarningRulesOutcome> AddEditWarningRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::AddEditWarningRulesRequest&, AddEditWarningRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> AddEditWarningRulesAsyncHandler; typedef Outcome<Core::Error, Model::CheckRepeatAssetImageRegistryResponse> CheckRepeatAssetImageRegistryOutcome; typedef std::future<CheckRepeatAssetImageRegistryOutcome> CheckRepeatAssetImageRegistryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CheckRepeatAssetImageRegistryRequest&, CheckRepeatAssetImageRegistryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CheckRepeatAssetImageRegistryAsyncHandler; typedef Outcome<Core::Error, Model::CreateAssetImageRegistryScanTaskResponse> CreateAssetImageRegistryScanTaskOutcome; typedef std::future<CreateAssetImageRegistryScanTaskOutcome> CreateAssetImageRegistryScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateAssetImageRegistryScanTaskRequest&, CreateAssetImageRegistryScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateAssetImageRegistryScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::CreateAssetImageRegistryScanTaskOneKeyResponse> CreateAssetImageRegistryScanTaskOneKeyOutcome; typedef std::future<CreateAssetImageRegistryScanTaskOneKeyOutcome> CreateAssetImageRegistryScanTaskOneKeyOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateAssetImageRegistryScanTaskOneKeyRequest&, CreateAssetImageRegistryScanTaskOneKeyOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateAssetImageRegistryScanTaskOneKeyAsyncHandler; typedef Outcome<Core::Error, Model::CreateAssetImageScanSettingResponse> CreateAssetImageScanSettingOutcome; typedef std::future<CreateAssetImageScanSettingOutcome> CreateAssetImageScanSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateAssetImageScanSettingRequest&, CreateAssetImageScanSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateAssetImageScanSettingAsyncHandler; typedef Outcome<Core::Error, Model::CreateAssetImageScanTaskResponse> CreateAssetImageScanTaskOutcome; typedef std::future<CreateAssetImageScanTaskOutcome> CreateAssetImageScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateAssetImageScanTaskRequest&, CreateAssetImageScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateAssetImageScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::CreateCheckComponentResponse> CreateCheckComponentOutcome; typedef std::future<CreateCheckComponentOutcome> CreateCheckComponentOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateCheckComponentRequest&, CreateCheckComponentOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateCheckComponentAsyncHandler; typedef Outcome<Core::Error, Model::CreateClusterCheckTaskResponse> CreateClusterCheckTaskOutcome; typedef std::future<CreateClusterCheckTaskOutcome> CreateClusterCheckTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateClusterCheckTaskRequest&, CreateClusterCheckTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateClusterCheckTaskAsyncHandler; typedef Outcome<Core::Error, Model::CreateComplianceTaskResponse> CreateComplianceTaskOutcome; typedef std::future<CreateComplianceTaskOutcome> CreateComplianceTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateComplianceTaskRequest&, CreateComplianceTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateComplianceTaskAsyncHandler; typedef Outcome<Core::Error, Model::CreateExportComplianceStatusListJobResponse> CreateExportComplianceStatusListJobOutcome; typedef std::future<CreateExportComplianceStatusListJobOutcome> CreateExportComplianceStatusListJobOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateExportComplianceStatusListJobRequest&, CreateExportComplianceStatusListJobOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateExportComplianceStatusListJobAsyncHandler; typedef Outcome<Core::Error, Model::CreateOrModifyPostPayCoresResponse> CreateOrModifyPostPayCoresOutcome; typedef std::future<CreateOrModifyPostPayCoresOutcome> CreateOrModifyPostPayCoresOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateOrModifyPostPayCoresRequest&, CreateOrModifyPostPayCoresOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateOrModifyPostPayCoresAsyncHandler; typedef Outcome<Core::Error, Model::CreateRefreshTaskResponse> CreateRefreshTaskOutcome; typedef std::future<CreateRefreshTaskOutcome> CreateRefreshTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateRefreshTaskRequest&, CreateRefreshTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateRefreshTaskAsyncHandler; typedef Outcome<Core::Error, Model::CreateVirusScanAgainResponse> CreateVirusScanAgainOutcome; typedef std::future<CreateVirusScanAgainOutcome> CreateVirusScanAgainOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateVirusScanAgainRequest&, CreateVirusScanAgainOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateVirusScanAgainAsyncHandler; typedef Outcome<Core::Error, Model::CreateVirusScanTaskResponse> CreateVirusScanTaskOutcome; typedef std::future<CreateVirusScanTaskOutcome> CreateVirusScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::CreateVirusScanTaskRequest&, CreateVirusScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateVirusScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::DeleteAbnormalProcessRulesResponse> DeleteAbnormalProcessRulesOutcome; typedef std::future<DeleteAbnormalProcessRulesOutcome> DeleteAbnormalProcessRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DeleteAbnormalProcessRulesRequest&, DeleteAbnormalProcessRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteAbnormalProcessRulesAsyncHandler; typedef Outcome<Core::Error, Model::DeleteAccessControlRulesResponse> DeleteAccessControlRulesOutcome; typedef std::future<DeleteAccessControlRulesOutcome> DeleteAccessControlRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DeleteAccessControlRulesRequest&, DeleteAccessControlRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteAccessControlRulesAsyncHandler; typedef Outcome<Core::Error, Model::DeleteCompliancePolicyItemFromWhitelistResponse> DeleteCompliancePolicyItemFromWhitelistOutcome; typedef std::future<DeleteCompliancePolicyItemFromWhitelistOutcome> DeleteCompliancePolicyItemFromWhitelistOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DeleteCompliancePolicyItemFromWhitelistRequest&, DeleteCompliancePolicyItemFromWhitelistOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteCompliancePolicyItemFromWhitelistAsyncHandler; typedef Outcome<Core::Error, Model::DeleteReverseShellWhiteListsResponse> DeleteReverseShellWhiteListsOutcome; typedef std::future<DeleteReverseShellWhiteListsOutcome> DeleteReverseShellWhiteListsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DeleteReverseShellWhiteListsRequest&, DeleteReverseShellWhiteListsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteReverseShellWhiteListsAsyncHandler; typedef Outcome<Core::Error, Model::DeleteRiskSyscallWhiteListsResponse> DeleteRiskSyscallWhiteListsOutcome; typedef std::future<DeleteRiskSyscallWhiteListsOutcome> DeleteRiskSyscallWhiteListsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DeleteRiskSyscallWhiteListsRequest&, DeleteRiskSyscallWhiteListsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteRiskSyscallWhiteListsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessDetailResponse> DescribeAbnormalProcessDetailOutcome; typedef std::future<DescribeAbnormalProcessDetailOutcome> DescribeAbnormalProcessDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessDetailRequest&, DescribeAbnormalProcessDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessEventsResponse> DescribeAbnormalProcessEventsOutcome; typedef std::future<DescribeAbnormalProcessEventsOutcome> DescribeAbnormalProcessEventsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessEventsRequest&, DescribeAbnormalProcessEventsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessEventsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessEventsExportResponse> DescribeAbnormalProcessEventsExportOutcome; typedef std::future<DescribeAbnormalProcessEventsExportOutcome> DescribeAbnormalProcessEventsExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessEventsExportRequest&, DescribeAbnormalProcessEventsExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessEventsExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessRuleDetailResponse> DescribeAbnormalProcessRuleDetailOutcome; typedef std::future<DescribeAbnormalProcessRuleDetailOutcome> DescribeAbnormalProcessRuleDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessRuleDetailRequest&, DescribeAbnormalProcessRuleDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessRuleDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessRulesResponse> DescribeAbnormalProcessRulesOutcome; typedef std::future<DescribeAbnormalProcessRulesOutcome> DescribeAbnormalProcessRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessRulesRequest&, DescribeAbnormalProcessRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessRulesAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAbnormalProcessRulesExportResponse> DescribeAbnormalProcessRulesExportOutcome; typedef std::future<DescribeAbnormalProcessRulesExportOutcome> DescribeAbnormalProcessRulesExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAbnormalProcessRulesExportRequest&, DescribeAbnormalProcessRulesExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAbnormalProcessRulesExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlDetailResponse> DescribeAccessControlDetailOutcome; typedef std::future<DescribeAccessControlDetailOutcome> DescribeAccessControlDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlDetailRequest&, DescribeAccessControlDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlEventsResponse> DescribeAccessControlEventsOutcome; typedef std::future<DescribeAccessControlEventsOutcome> DescribeAccessControlEventsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlEventsRequest&, DescribeAccessControlEventsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlEventsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlEventsExportResponse> DescribeAccessControlEventsExportOutcome; typedef std::future<DescribeAccessControlEventsExportOutcome> DescribeAccessControlEventsExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlEventsExportRequest&, DescribeAccessControlEventsExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlEventsExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlRuleDetailResponse> DescribeAccessControlRuleDetailOutcome; typedef std::future<DescribeAccessControlRuleDetailOutcome> DescribeAccessControlRuleDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlRuleDetailRequest&, DescribeAccessControlRuleDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlRuleDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlRulesResponse> DescribeAccessControlRulesOutcome; typedef std::future<DescribeAccessControlRulesOutcome> DescribeAccessControlRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlRulesRequest&, DescribeAccessControlRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlRulesAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAccessControlRulesExportResponse> DescribeAccessControlRulesExportOutcome; typedef std::future<DescribeAccessControlRulesExportOutcome> DescribeAccessControlRulesExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAccessControlRulesExportRequest&, DescribeAccessControlRulesExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAccessControlRulesExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAffectedClusterCountResponse> DescribeAffectedClusterCountOutcome; typedef std::future<DescribeAffectedClusterCountOutcome> DescribeAffectedClusterCountOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAffectedClusterCountRequest&, DescribeAffectedClusterCountOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAffectedClusterCountAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAffectedNodeListResponse> DescribeAffectedNodeListOutcome; typedef std::future<DescribeAffectedNodeListOutcome> DescribeAffectedNodeListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAffectedNodeListRequest&, DescribeAffectedNodeListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAffectedNodeListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAffectedWorkloadListResponse> DescribeAffectedWorkloadListOutcome; typedef std::future<DescribeAffectedWorkloadListOutcome> DescribeAffectedWorkloadListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAffectedWorkloadListRequest&, DescribeAffectedWorkloadListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAffectedWorkloadListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetAppServiceListResponse> DescribeAssetAppServiceListOutcome; typedef std::future<DescribeAssetAppServiceListOutcome> DescribeAssetAppServiceListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetAppServiceListRequest&, DescribeAssetAppServiceListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetAppServiceListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetComponentListResponse> DescribeAssetComponentListOutcome; typedef std::future<DescribeAssetComponentListOutcome> DescribeAssetComponentListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetComponentListRequest&, DescribeAssetComponentListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetComponentListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetContainerDetailResponse> DescribeAssetContainerDetailOutcome; typedef std::future<DescribeAssetContainerDetailOutcome> DescribeAssetContainerDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetContainerDetailRequest&, DescribeAssetContainerDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetContainerDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetContainerListResponse> DescribeAssetContainerListOutcome; typedef std::future<DescribeAssetContainerListOutcome> DescribeAssetContainerListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetContainerListRequest&, DescribeAssetContainerListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetContainerListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetDBServiceListResponse> DescribeAssetDBServiceListOutcome; typedef std::future<DescribeAssetDBServiceListOutcome> DescribeAssetDBServiceListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetDBServiceListRequest&, DescribeAssetDBServiceListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetDBServiceListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetHostDetailResponse> DescribeAssetHostDetailOutcome; typedef std::future<DescribeAssetHostDetailOutcome> DescribeAssetHostDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetHostDetailRequest&, DescribeAssetHostDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetHostDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetHostListResponse> DescribeAssetHostListOutcome; typedef std::future<DescribeAssetHostListOutcome> DescribeAssetHostListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetHostListRequest&, DescribeAssetHostListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetHostListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageBindRuleInfoResponse> DescribeAssetImageBindRuleInfoOutcome; typedef std::future<DescribeAssetImageBindRuleInfoOutcome> DescribeAssetImageBindRuleInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageBindRuleInfoRequest&, DescribeAssetImageBindRuleInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageBindRuleInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageDetailResponse> DescribeAssetImageDetailOutcome; typedef std::future<DescribeAssetImageDetailOutcome> DescribeAssetImageDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageDetailRequest&, DescribeAssetImageDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageHostListResponse> DescribeAssetImageHostListOutcome; typedef std::future<DescribeAssetImageHostListOutcome> DescribeAssetImageHostListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageHostListRequest&, DescribeAssetImageHostListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageHostListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageListResponse> DescribeAssetImageListOutcome; typedef std::future<DescribeAssetImageListOutcome> DescribeAssetImageListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageListRequest&, DescribeAssetImageListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageListExportResponse> DescribeAssetImageListExportOutcome; typedef std::future<DescribeAssetImageListExportOutcome> DescribeAssetImageListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageListExportRequest&, DescribeAssetImageListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryAssetStatusResponse> DescribeAssetImageRegistryAssetStatusOutcome; typedef std::future<DescribeAssetImageRegistryAssetStatusOutcome> DescribeAssetImageRegistryAssetStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryAssetStatusRequest&, DescribeAssetImageRegistryAssetStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryAssetStatusAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryDetailResponse> DescribeAssetImageRegistryDetailOutcome; typedef std::future<DescribeAssetImageRegistryDetailOutcome> DescribeAssetImageRegistryDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryDetailRequest&, DescribeAssetImageRegistryDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryListResponse> DescribeAssetImageRegistryListOutcome; typedef std::future<DescribeAssetImageRegistryListOutcome> DescribeAssetImageRegistryListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryListRequest&, DescribeAssetImageRegistryListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryListExportResponse> DescribeAssetImageRegistryListExportOutcome; typedef std::future<DescribeAssetImageRegistryListExportOutcome> DescribeAssetImageRegistryListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryListExportRequest&, DescribeAssetImageRegistryListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryRegistryDetailResponse> DescribeAssetImageRegistryRegistryDetailOutcome; typedef std::future<DescribeAssetImageRegistryRegistryDetailOutcome> DescribeAssetImageRegistryRegistryDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryRegistryDetailRequest&, DescribeAssetImageRegistryRegistryDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryRegistryDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryRegistryListResponse> DescribeAssetImageRegistryRegistryListOutcome; typedef std::future<DescribeAssetImageRegistryRegistryListOutcome> DescribeAssetImageRegistryRegistryListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryRegistryListRequest&, DescribeAssetImageRegistryRegistryListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryRegistryListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryRiskInfoListResponse> DescribeAssetImageRegistryRiskInfoListOutcome; typedef std::future<DescribeAssetImageRegistryRiskInfoListOutcome> DescribeAssetImageRegistryRiskInfoListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryRiskInfoListRequest&, DescribeAssetImageRegistryRiskInfoListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryRiskInfoListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryRiskListExportResponse> DescribeAssetImageRegistryRiskListExportOutcome; typedef std::future<DescribeAssetImageRegistryRiskListExportOutcome> DescribeAssetImageRegistryRiskListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryRiskListExportRequest&, DescribeAssetImageRegistryRiskListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryRiskListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryScanStatusOneKeyResponse> DescribeAssetImageRegistryScanStatusOneKeyOutcome; typedef std::future<DescribeAssetImageRegistryScanStatusOneKeyOutcome> DescribeAssetImageRegistryScanStatusOneKeyOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryScanStatusOneKeyRequest&, DescribeAssetImageRegistryScanStatusOneKeyOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryScanStatusOneKeyAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistrySummaryResponse> DescribeAssetImageRegistrySummaryOutcome; typedef std::future<DescribeAssetImageRegistrySummaryOutcome> DescribeAssetImageRegistrySummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistrySummaryRequest&, DescribeAssetImageRegistrySummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistrySummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryVirusListResponse> DescribeAssetImageRegistryVirusListOutcome; typedef std::future<DescribeAssetImageRegistryVirusListOutcome> DescribeAssetImageRegistryVirusListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryVirusListRequest&, DescribeAssetImageRegistryVirusListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryVirusListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryVirusListExportResponse> DescribeAssetImageRegistryVirusListExportOutcome; typedef std::future<DescribeAssetImageRegistryVirusListExportOutcome> DescribeAssetImageRegistryVirusListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryVirusListExportRequest&, DescribeAssetImageRegistryVirusListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryVirusListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryVulListResponse> DescribeAssetImageRegistryVulListOutcome; typedef std::future<DescribeAssetImageRegistryVulListOutcome> DescribeAssetImageRegistryVulListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryVulListRequest&, DescribeAssetImageRegistryVulListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryVulListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRegistryVulListExportResponse> DescribeAssetImageRegistryVulListExportOutcome; typedef std::future<DescribeAssetImageRegistryVulListExportOutcome> DescribeAssetImageRegistryVulListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRegistryVulListExportRequest&, DescribeAssetImageRegistryVulListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRegistryVulListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRiskListResponse> DescribeAssetImageRiskListOutcome; typedef std::future<DescribeAssetImageRiskListOutcome> DescribeAssetImageRiskListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRiskListRequest&, DescribeAssetImageRiskListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRiskListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageRiskListExportResponse> DescribeAssetImageRiskListExportOutcome; typedef std::future<DescribeAssetImageRiskListExportOutcome> DescribeAssetImageRiskListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageRiskListExportRequest&, DescribeAssetImageRiskListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageRiskListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageScanSettingResponse> DescribeAssetImageScanSettingOutcome; typedef std::future<DescribeAssetImageScanSettingOutcome> DescribeAssetImageScanSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageScanSettingRequest&, DescribeAssetImageScanSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageScanSettingAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageScanStatusResponse> DescribeAssetImageScanStatusOutcome; typedef std::future<DescribeAssetImageScanStatusOutcome> DescribeAssetImageScanStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageScanStatusRequest&, DescribeAssetImageScanStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageScanStatusAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageScanTaskResponse> DescribeAssetImageScanTaskOutcome; typedef std::future<DescribeAssetImageScanTaskOutcome> DescribeAssetImageScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageScanTaskRequest&, DescribeAssetImageScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageSimpleListResponse> DescribeAssetImageSimpleListOutcome; typedef std::future<DescribeAssetImageSimpleListOutcome> DescribeAssetImageSimpleListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageSimpleListRequest&, DescribeAssetImageSimpleListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageSimpleListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageVirusListResponse> DescribeAssetImageVirusListOutcome; typedef std::future<DescribeAssetImageVirusListOutcome> DescribeAssetImageVirusListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageVirusListRequest&, DescribeAssetImageVirusListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageVirusListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageVirusListExportResponse> DescribeAssetImageVirusListExportOutcome; typedef std::future<DescribeAssetImageVirusListExportOutcome> DescribeAssetImageVirusListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageVirusListExportRequest&, DescribeAssetImageVirusListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageVirusListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageVulListResponse> DescribeAssetImageVulListOutcome; typedef std::future<DescribeAssetImageVulListOutcome> DescribeAssetImageVulListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageVulListRequest&, DescribeAssetImageVulListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageVulListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetImageVulListExportResponse> DescribeAssetImageVulListExportOutcome; typedef std::future<DescribeAssetImageVulListExportOutcome> DescribeAssetImageVulListExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetImageVulListExportRequest&, DescribeAssetImageVulListExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetImageVulListExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetPortListResponse> DescribeAssetPortListOutcome; typedef std::future<DescribeAssetPortListOutcome> DescribeAssetPortListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetPortListRequest&, DescribeAssetPortListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetPortListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetProcessListResponse> DescribeAssetProcessListOutcome; typedef std::future<DescribeAssetProcessListOutcome> DescribeAssetProcessListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetProcessListRequest&, DescribeAssetProcessListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetProcessListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetSummaryResponse> DescribeAssetSummaryOutcome; typedef std::future<DescribeAssetSummaryOutcome> DescribeAssetSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetSummaryRequest&, DescribeAssetSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeAssetWebServiceListResponse> DescribeAssetWebServiceListOutcome; typedef std::future<DescribeAssetWebServiceListOutcome> DescribeAssetWebServiceListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeAssetWebServiceListRequest&, DescribeAssetWebServiceListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeAssetWebServiceListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeCheckItemListResponse> DescribeCheckItemListOutcome; typedef std::future<DescribeCheckItemListOutcome> DescribeCheckItemListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeCheckItemListRequest&, DescribeCheckItemListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeCheckItemListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeClusterDetailResponse> DescribeClusterDetailOutcome; typedef std::future<DescribeClusterDetailOutcome> DescribeClusterDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeClusterDetailRequest&, DescribeClusterDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeClusterDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeClusterSummaryResponse> DescribeClusterSummaryOutcome; typedef std::future<DescribeClusterSummaryOutcome> DescribeClusterSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeClusterSummaryRequest&, DescribeClusterSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeClusterSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceAssetDetailInfoResponse> DescribeComplianceAssetDetailInfoOutcome; typedef std::future<DescribeComplianceAssetDetailInfoOutcome> DescribeComplianceAssetDetailInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceAssetDetailInfoRequest&, DescribeComplianceAssetDetailInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceAssetDetailInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceAssetListResponse> DescribeComplianceAssetListOutcome; typedef std::future<DescribeComplianceAssetListOutcome> DescribeComplianceAssetListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceAssetListRequest&, DescribeComplianceAssetListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceAssetListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceAssetPolicyItemListResponse> DescribeComplianceAssetPolicyItemListOutcome; typedef std::future<DescribeComplianceAssetPolicyItemListOutcome> DescribeComplianceAssetPolicyItemListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceAssetPolicyItemListRequest&, DescribeComplianceAssetPolicyItemListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceAssetPolicyItemListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeCompliancePeriodTaskListResponse> DescribeCompliancePeriodTaskListOutcome; typedef std::future<DescribeCompliancePeriodTaskListOutcome> DescribeCompliancePeriodTaskListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeCompliancePeriodTaskListRequest&, DescribeCompliancePeriodTaskListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeCompliancePeriodTaskListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeCompliancePolicyItemAffectedAssetListResponse> DescribeCompliancePolicyItemAffectedAssetListOutcome; typedef std::future<DescribeCompliancePolicyItemAffectedAssetListOutcome> DescribeCompliancePolicyItemAffectedAssetListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeCompliancePolicyItemAffectedAssetListRequest&, DescribeCompliancePolicyItemAffectedAssetListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeCompliancePolicyItemAffectedAssetListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeCompliancePolicyItemAffectedSummaryResponse> DescribeCompliancePolicyItemAffectedSummaryOutcome; typedef std::future<DescribeCompliancePolicyItemAffectedSummaryOutcome> DescribeCompliancePolicyItemAffectedSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeCompliancePolicyItemAffectedSummaryRequest&, DescribeCompliancePolicyItemAffectedSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeCompliancePolicyItemAffectedSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceScanFailedAssetListResponse> DescribeComplianceScanFailedAssetListOutcome; typedef std::future<DescribeComplianceScanFailedAssetListOutcome> DescribeComplianceScanFailedAssetListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceScanFailedAssetListRequest&, DescribeComplianceScanFailedAssetListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceScanFailedAssetListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceTaskAssetSummaryResponse> DescribeComplianceTaskAssetSummaryOutcome; typedef std::future<DescribeComplianceTaskAssetSummaryOutcome> DescribeComplianceTaskAssetSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceTaskAssetSummaryRequest&, DescribeComplianceTaskAssetSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceTaskAssetSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceTaskPolicyItemSummaryListResponse> DescribeComplianceTaskPolicyItemSummaryListOutcome; typedef std::future<DescribeComplianceTaskPolicyItemSummaryListOutcome> DescribeComplianceTaskPolicyItemSummaryListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceTaskPolicyItemSummaryListRequest&, DescribeComplianceTaskPolicyItemSummaryListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceTaskPolicyItemSummaryListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeComplianceWhitelistItemListResponse> DescribeComplianceWhitelistItemListOutcome; typedef std::future<DescribeComplianceWhitelistItemListOutcome> DescribeComplianceWhitelistItemListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeComplianceWhitelistItemListRequest&, DescribeComplianceWhitelistItemListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeComplianceWhitelistItemListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeContainerAssetSummaryResponse> DescribeContainerAssetSummaryOutcome; typedef std::future<DescribeContainerAssetSummaryOutcome> DescribeContainerAssetSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeContainerAssetSummaryRequest&, DescribeContainerAssetSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeContainerAssetSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeContainerSecEventSummaryResponse> DescribeContainerSecEventSummaryOutcome; typedef std::future<DescribeContainerSecEventSummaryOutcome> DescribeContainerSecEventSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeContainerSecEventSummaryRequest&, DescribeContainerSecEventSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeContainerSecEventSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeEscapeEventDetailResponse> DescribeEscapeEventDetailOutcome; typedef std::future<DescribeEscapeEventDetailOutcome> DescribeEscapeEventDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeEscapeEventDetailRequest&, DescribeEscapeEventDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeEscapeEventDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeEscapeEventInfoResponse> DescribeEscapeEventInfoOutcome; typedef std::future<DescribeEscapeEventInfoOutcome> DescribeEscapeEventInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeEscapeEventInfoRequest&, DescribeEscapeEventInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeEscapeEventInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeEscapeEventsExportResponse> DescribeEscapeEventsExportOutcome; typedef std::future<DescribeEscapeEventsExportOutcome> DescribeEscapeEventsExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeEscapeEventsExportRequest&, DescribeEscapeEventsExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeEscapeEventsExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeEscapeRuleInfoResponse> DescribeEscapeRuleInfoOutcome; typedef std::future<DescribeEscapeRuleInfoOutcome> DescribeEscapeRuleInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeEscapeRuleInfoRequest&, DescribeEscapeRuleInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeEscapeRuleInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeEscapeSafeStateResponse> DescribeEscapeSafeStateOutcome; typedef std::future<DescribeEscapeSafeStateOutcome> DescribeEscapeSafeStateOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeEscapeSafeStateRequest&, DescribeEscapeSafeStateOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeEscapeSafeStateAsyncHandler; typedef Outcome<Core::Error, Model::DescribeExportJobResultResponse> DescribeExportJobResultOutcome; typedef std::future<DescribeExportJobResultOutcome> DescribeExportJobResultOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeExportJobResultRequest&, DescribeExportJobResultOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeExportJobResultAsyncHandler; typedef Outcome<Core::Error, Model::DescribeImageAuthorizedInfoResponse> DescribeImageAuthorizedInfoOutcome; typedef std::future<DescribeImageAuthorizedInfoOutcome> DescribeImageAuthorizedInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeImageAuthorizedInfoRequest&, DescribeImageAuthorizedInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeImageAuthorizedInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeImageRegistryTimingScanTaskResponse> DescribeImageRegistryTimingScanTaskOutcome; typedef std::future<DescribeImageRegistryTimingScanTaskOutcome> DescribeImageRegistryTimingScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeImageRegistryTimingScanTaskRequest&, DescribeImageRegistryTimingScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeImageRegistryTimingScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::DescribeImageRiskSummaryResponse> DescribeImageRiskSummaryOutcome; typedef std::future<DescribeImageRiskSummaryOutcome> DescribeImageRiskSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeImageRiskSummaryRequest&, DescribeImageRiskSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeImageRiskSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeImageRiskTendencyResponse> DescribeImageRiskTendencyOutcome; typedef std::future<DescribeImageRiskTendencyOutcome> DescribeImageRiskTendencyOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeImageRiskTendencyRequest&, DescribeImageRiskTendencyOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeImageRiskTendencyAsyncHandler; typedef Outcome<Core::Error, Model::DescribeImageSimpleListResponse> DescribeImageSimpleListOutcome; typedef std::future<DescribeImageSimpleListOutcome> DescribeImageSimpleListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeImageSimpleListRequest&, DescribeImageSimpleListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeImageSimpleListAsyncHandler; typedef Outcome<Core::Error, Model::DescribePostPayDetailResponse> DescribePostPayDetailOutcome; typedef std::future<DescribePostPayDetailOutcome> DescribePostPayDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribePostPayDetailRequest&, DescribePostPayDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribePostPayDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeProVersionInfoResponse> DescribeProVersionInfoOutcome; typedef std::future<DescribeProVersionInfoOutcome> DescribeProVersionInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeProVersionInfoRequest&, DescribeProVersionInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeProVersionInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribePurchaseStateInfoResponse> DescribePurchaseStateInfoOutcome; typedef std::future<DescribePurchaseStateInfoOutcome> DescribePurchaseStateInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribePurchaseStateInfoRequest&, DescribePurchaseStateInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribePurchaseStateInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRefreshTaskResponse> DescribeRefreshTaskOutcome; typedef std::future<DescribeRefreshTaskOutcome> DescribeRefreshTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRefreshTaskRequest&, DescribeRefreshTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRefreshTaskAsyncHandler; typedef Outcome<Core::Error, Model::DescribeReverseShellDetailResponse> DescribeReverseShellDetailOutcome; typedef std::future<DescribeReverseShellDetailOutcome> DescribeReverseShellDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeReverseShellDetailRequest&, DescribeReverseShellDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeReverseShellDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeReverseShellEventsResponse> DescribeReverseShellEventsOutcome; typedef std::future<DescribeReverseShellEventsOutcome> DescribeReverseShellEventsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeReverseShellEventsRequest&, DescribeReverseShellEventsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeReverseShellEventsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeReverseShellEventsExportResponse> DescribeReverseShellEventsExportOutcome; typedef std::future<DescribeReverseShellEventsExportOutcome> DescribeReverseShellEventsExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeReverseShellEventsExportRequest&, DescribeReverseShellEventsExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeReverseShellEventsExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeReverseShellWhiteListDetailResponse> DescribeReverseShellWhiteListDetailOutcome; typedef std::future<DescribeReverseShellWhiteListDetailOutcome> DescribeReverseShellWhiteListDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeReverseShellWhiteListDetailRequest&, DescribeReverseShellWhiteListDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeReverseShellWhiteListDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeReverseShellWhiteListsResponse> DescribeReverseShellWhiteListsOutcome; typedef std::future<DescribeReverseShellWhiteListsOutcome> DescribeReverseShellWhiteListsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeReverseShellWhiteListsRequest&, DescribeReverseShellWhiteListsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeReverseShellWhiteListsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskListResponse> DescribeRiskListOutcome; typedef std::future<DescribeRiskListOutcome> DescribeRiskListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskListRequest&, DescribeRiskListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallDetailResponse> DescribeRiskSyscallDetailOutcome; typedef std::future<DescribeRiskSyscallDetailOutcome> DescribeRiskSyscallDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallDetailRequest&, DescribeRiskSyscallDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallEventsResponse> DescribeRiskSyscallEventsOutcome; typedef std::future<DescribeRiskSyscallEventsOutcome> DescribeRiskSyscallEventsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallEventsRequest&, DescribeRiskSyscallEventsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallEventsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallEventsExportResponse> DescribeRiskSyscallEventsExportOutcome; typedef std::future<DescribeRiskSyscallEventsExportOutcome> DescribeRiskSyscallEventsExportOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallEventsExportRequest&, DescribeRiskSyscallEventsExportOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallEventsExportAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallNamesResponse> DescribeRiskSyscallNamesOutcome; typedef std::future<DescribeRiskSyscallNamesOutcome> DescribeRiskSyscallNamesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallNamesRequest&, DescribeRiskSyscallNamesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallNamesAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallWhiteListDetailResponse> DescribeRiskSyscallWhiteListDetailOutcome; typedef std::future<DescribeRiskSyscallWhiteListDetailOutcome> DescribeRiskSyscallWhiteListDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallWhiteListDetailRequest&, DescribeRiskSyscallWhiteListDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallWhiteListDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeRiskSyscallWhiteListsResponse> DescribeRiskSyscallWhiteListsOutcome; typedef std::future<DescribeRiskSyscallWhiteListsOutcome> DescribeRiskSyscallWhiteListsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeRiskSyscallWhiteListsRequest&, DescribeRiskSyscallWhiteListsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRiskSyscallWhiteListsAsyncHandler; typedef Outcome<Core::Error, Model::DescribeSecEventsTendencyResponse> DescribeSecEventsTendencyOutcome; typedef std::future<DescribeSecEventsTendencyOutcome> DescribeSecEventsTendencyOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeSecEventsTendencyRequest&, DescribeSecEventsTendencyOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeSecEventsTendencyAsyncHandler; typedef Outcome<Core::Error, Model::DescribeTaskResultSummaryResponse> DescribeTaskResultSummaryOutcome; typedef std::future<DescribeTaskResultSummaryOutcome> DescribeTaskResultSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeTaskResultSummaryRequest&, DescribeTaskResultSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeTaskResultSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeUnfinishRefreshTaskResponse> DescribeUnfinishRefreshTaskOutcome; typedef std::future<DescribeUnfinishRefreshTaskOutcome> DescribeUnfinishRefreshTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeUnfinishRefreshTaskRequest&, DescribeUnfinishRefreshTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeUnfinishRefreshTaskAsyncHandler; typedef Outcome<Core::Error, Model::DescribeUserClusterResponse> DescribeUserClusterOutcome; typedef std::future<DescribeUserClusterOutcome> DescribeUserClusterOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeUserClusterRequest&, DescribeUserClusterOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeUserClusterAsyncHandler; typedef Outcome<Core::Error, Model::DescribeValueAddedSrvInfoResponse> DescribeValueAddedSrvInfoOutcome; typedef std::future<DescribeValueAddedSrvInfoOutcome> DescribeValueAddedSrvInfoOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeValueAddedSrvInfoRequest&, DescribeValueAddedSrvInfoOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeValueAddedSrvInfoAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusDetailResponse> DescribeVirusDetailOutcome; typedef std::future<DescribeVirusDetailOutcome> DescribeVirusDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusDetailRequest&, DescribeVirusDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusDetailAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusListResponse> DescribeVirusListOutcome; typedef std::future<DescribeVirusListOutcome> DescribeVirusListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusListRequest&, DescribeVirusListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusMonitorSettingResponse> DescribeVirusMonitorSettingOutcome; typedef std::future<DescribeVirusMonitorSettingOutcome> DescribeVirusMonitorSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusMonitorSettingRequest&, DescribeVirusMonitorSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusMonitorSettingAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusScanSettingResponse> DescribeVirusScanSettingOutcome; typedef std::future<DescribeVirusScanSettingOutcome> DescribeVirusScanSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusScanSettingRequest&, DescribeVirusScanSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusScanSettingAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusScanTaskStatusResponse> DescribeVirusScanTaskStatusOutcome; typedef std::future<DescribeVirusScanTaskStatusOutcome> DescribeVirusScanTaskStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusScanTaskStatusRequest&, DescribeVirusScanTaskStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusScanTaskStatusAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusScanTimeoutSettingResponse> DescribeVirusScanTimeoutSettingOutcome; typedef std::future<DescribeVirusScanTimeoutSettingOutcome> DescribeVirusScanTimeoutSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusScanTimeoutSettingRequest&, DescribeVirusScanTimeoutSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusScanTimeoutSettingAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusSummaryResponse> DescribeVirusSummaryOutcome; typedef std::future<DescribeVirusSummaryOutcome> DescribeVirusSummaryOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusSummaryRequest&, DescribeVirusSummaryOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusSummaryAsyncHandler; typedef Outcome<Core::Error, Model::DescribeVirusTaskListResponse> DescribeVirusTaskListOutcome; typedef std::future<DescribeVirusTaskListOutcome> DescribeVirusTaskListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeVirusTaskListRequest&, DescribeVirusTaskListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeVirusTaskListAsyncHandler; typedef Outcome<Core::Error, Model::DescribeWarningRulesResponse> DescribeWarningRulesOutcome; typedef std::future<DescribeWarningRulesOutcome> DescribeWarningRulesOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::DescribeWarningRulesRequest&, DescribeWarningRulesOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeWarningRulesAsyncHandler; typedef Outcome<Core::Error, Model::ExportVirusListResponse> ExportVirusListOutcome; typedef std::future<ExportVirusListOutcome> ExportVirusListOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ExportVirusListRequest&, ExportVirusListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ExportVirusListAsyncHandler; typedef Outcome<Core::Error, Model::InitializeUserComplianceEnvironmentResponse> InitializeUserComplianceEnvironmentOutcome; typedef std::future<InitializeUserComplianceEnvironmentOutcome> InitializeUserComplianceEnvironmentOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::InitializeUserComplianceEnvironmentRequest&, InitializeUserComplianceEnvironmentOutcome, const std::shared_ptr<const AsyncCallerContext>&)> InitializeUserComplianceEnvironmentAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAbnormalProcessRuleStatusResponse> ModifyAbnormalProcessRuleStatusOutcome; typedef std::future<ModifyAbnormalProcessRuleStatusOutcome> ModifyAbnormalProcessRuleStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAbnormalProcessRuleStatusRequest&, ModifyAbnormalProcessRuleStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAbnormalProcessRuleStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAbnormalProcessStatusResponse> ModifyAbnormalProcessStatusOutcome; typedef std::future<ModifyAbnormalProcessStatusOutcome> ModifyAbnormalProcessStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAbnormalProcessStatusRequest&, ModifyAbnormalProcessStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAbnormalProcessStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAccessControlRuleStatusResponse> ModifyAccessControlRuleStatusOutcome; typedef std::future<ModifyAccessControlRuleStatusOutcome> ModifyAccessControlRuleStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAccessControlRuleStatusRequest&, ModifyAccessControlRuleStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAccessControlRuleStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAccessControlStatusResponse> ModifyAccessControlStatusOutcome; typedef std::future<ModifyAccessControlStatusOutcome> ModifyAccessControlStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAccessControlStatusRequest&, ModifyAccessControlStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAccessControlStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAssetResponse> ModifyAssetOutcome; typedef std::future<ModifyAssetOutcome> ModifyAssetOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAssetRequest&, ModifyAssetOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAssetAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAssetImageRegistryScanStopResponse> ModifyAssetImageRegistryScanStopOutcome; typedef std::future<ModifyAssetImageRegistryScanStopOutcome> ModifyAssetImageRegistryScanStopOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAssetImageRegistryScanStopRequest&, ModifyAssetImageRegistryScanStopOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAssetImageRegistryScanStopAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAssetImageRegistryScanStopOneKeyResponse> ModifyAssetImageRegistryScanStopOneKeyOutcome; typedef std::future<ModifyAssetImageRegistryScanStopOneKeyOutcome> ModifyAssetImageRegistryScanStopOneKeyOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAssetImageRegistryScanStopOneKeyRequest&, ModifyAssetImageRegistryScanStopOneKeyOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAssetImageRegistryScanStopOneKeyAsyncHandler; typedef Outcome<Core::Error, Model::ModifyAssetImageScanStopResponse> ModifyAssetImageScanStopOutcome; typedef std::future<ModifyAssetImageScanStopOutcome> ModifyAssetImageScanStopOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyAssetImageScanStopRequest&, ModifyAssetImageScanStopOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyAssetImageScanStopAsyncHandler; typedef Outcome<Core::Error, Model::ModifyCompliancePeriodTaskResponse> ModifyCompliancePeriodTaskOutcome; typedef std::future<ModifyCompliancePeriodTaskOutcome> ModifyCompliancePeriodTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyCompliancePeriodTaskRequest&, ModifyCompliancePeriodTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyCompliancePeriodTaskAsyncHandler; typedef Outcome<Core::Error, Model::ModifyEscapeEventStatusResponse> ModifyEscapeEventStatusOutcome; typedef std::future<ModifyEscapeEventStatusOutcome> ModifyEscapeEventStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyEscapeEventStatusRequest&, ModifyEscapeEventStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyEscapeEventStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyEscapeRuleResponse> ModifyEscapeRuleOutcome; typedef std::future<ModifyEscapeRuleOutcome> ModifyEscapeRuleOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyEscapeRuleRequest&, ModifyEscapeRuleOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyEscapeRuleAsyncHandler; typedef Outcome<Core::Error, Model::ModifyReverseShellStatusResponse> ModifyReverseShellStatusOutcome; typedef std::future<ModifyReverseShellStatusOutcome> ModifyReverseShellStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyReverseShellStatusRequest&, ModifyReverseShellStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyReverseShellStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyRiskSyscallStatusResponse> ModifyRiskSyscallStatusOutcome; typedef std::future<ModifyRiskSyscallStatusOutcome> ModifyRiskSyscallStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyRiskSyscallStatusRequest&, ModifyRiskSyscallStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyRiskSyscallStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyVirusFileStatusResponse> ModifyVirusFileStatusOutcome; typedef std::future<ModifyVirusFileStatusOutcome> ModifyVirusFileStatusOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyVirusFileStatusRequest&, ModifyVirusFileStatusOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyVirusFileStatusAsyncHandler; typedef Outcome<Core::Error, Model::ModifyVirusMonitorSettingResponse> ModifyVirusMonitorSettingOutcome; typedef std::future<ModifyVirusMonitorSettingOutcome> ModifyVirusMonitorSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyVirusMonitorSettingRequest&, ModifyVirusMonitorSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyVirusMonitorSettingAsyncHandler; typedef Outcome<Core::Error, Model::ModifyVirusScanSettingResponse> ModifyVirusScanSettingOutcome; typedef std::future<ModifyVirusScanSettingOutcome> ModifyVirusScanSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyVirusScanSettingRequest&, ModifyVirusScanSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyVirusScanSettingAsyncHandler; typedef Outcome<Core::Error, Model::ModifyVirusScanTimeoutSettingResponse> ModifyVirusScanTimeoutSettingOutcome; typedef std::future<ModifyVirusScanTimeoutSettingOutcome> ModifyVirusScanTimeoutSettingOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ModifyVirusScanTimeoutSettingRequest&, ModifyVirusScanTimeoutSettingOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ModifyVirusScanTimeoutSettingAsyncHandler; typedef Outcome<Core::Error, Model::RemoveAssetImageRegistryRegistryDetailResponse> RemoveAssetImageRegistryRegistryDetailOutcome; typedef std::future<RemoveAssetImageRegistryRegistryDetailOutcome> RemoveAssetImageRegistryRegistryDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::RemoveAssetImageRegistryRegistryDetailRequest&, RemoveAssetImageRegistryRegistryDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> RemoveAssetImageRegistryRegistryDetailAsyncHandler; typedef Outcome<Core::Error, Model::RenewImageAuthorizeStateResponse> RenewImageAuthorizeStateOutcome; typedef std::future<RenewImageAuthorizeStateOutcome> RenewImageAuthorizeStateOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::RenewImageAuthorizeStateRequest&, RenewImageAuthorizeStateOutcome, const std::shared_ptr<const AsyncCallerContext>&)> RenewImageAuthorizeStateAsyncHandler; typedef Outcome<Core::Error, Model::ScanComplianceAssetsResponse> ScanComplianceAssetsOutcome; typedef std::future<ScanComplianceAssetsOutcome> ScanComplianceAssetsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ScanComplianceAssetsRequest&, ScanComplianceAssetsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ScanComplianceAssetsAsyncHandler; typedef Outcome<Core::Error, Model::ScanComplianceAssetsByPolicyItemResponse> ScanComplianceAssetsByPolicyItemOutcome; typedef std::future<ScanComplianceAssetsByPolicyItemOutcome> ScanComplianceAssetsByPolicyItemOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ScanComplianceAssetsByPolicyItemRequest&, ScanComplianceAssetsByPolicyItemOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ScanComplianceAssetsByPolicyItemAsyncHandler; typedef Outcome<Core::Error, Model::ScanCompliancePolicyItemsResponse> ScanCompliancePolicyItemsOutcome; typedef std::future<ScanCompliancePolicyItemsOutcome> ScanCompliancePolicyItemsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ScanCompliancePolicyItemsRequest&, ScanCompliancePolicyItemsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ScanCompliancePolicyItemsAsyncHandler; typedef Outcome<Core::Error, Model::ScanComplianceScanFailedAssetsResponse> ScanComplianceScanFailedAssetsOutcome; typedef std::future<ScanComplianceScanFailedAssetsOutcome> ScanComplianceScanFailedAssetsOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::ScanComplianceScanFailedAssetsRequest&, ScanComplianceScanFailedAssetsOutcome, const std::shared_ptr<const AsyncCallerContext>&)> ScanComplianceScanFailedAssetsAsyncHandler; typedef Outcome<Core::Error, Model::SetCheckModeResponse> SetCheckModeOutcome; typedef std::future<SetCheckModeOutcome> SetCheckModeOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::SetCheckModeRequest&, SetCheckModeOutcome, const std::shared_ptr<const AsyncCallerContext>&)> SetCheckModeAsyncHandler; typedef Outcome<Core::Error, Model::StopVirusScanTaskResponse> StopVirusScanTaskOutcome; typedef std::future<StopVirusScanTaskOutcome> StopVirusScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::StopVirusScanTaskRequest&, StopVirusScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> StopVirusScanTaskAsyncHandler; typedef Outcome<Core::Error, Model::SyncAssetImageRegistryAssetResponse> SyncAssetImageRegistryAssetOutcome; typedef std::future<SyncAssetImageRegistryAssetOutcome> SyncAssetImageRegistryAssetOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::SyncAssetImageRegistryAssetRequest&, SyncAssetImageRegistryAssetOutcome, const std::shared_ptr<const AsyncCallerContext>&)> SyncAssetImageRegistryAssetAsyncHandler; typedef Outcome<Core::Error, Model::UpdateAssetImageRegistryRegistryDetailResponse> UpdateAssetImageRegistryRegistryDetailOutcome; typedef std::future<UpdateAssetImageRegistryRegistryDetailOutcome> UpdateAssetImageRegistryRegistryDetailOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::UpdateAssetImageRegistryRegistryDetailRequest&, UpdateAssetImageRegistryRegistryDetailOutcome, const std::shared_ptr<const AsyncCallerContext>&)> UpdateAssetImageRegistryRegistryDetailAsyncHandler; typedef Outcome<Core::Error, Model::UpdateImageRegistryTimingScanTaskResponse> UpdateImageRegistryTimingScanTaskOutcome; typedef std::future<UpdateImageRegistryTimingScanTaskOutcome> UpdateImageRegistryTimingScanTaskOutcomeCallable; typedef std::function<void(const TcssClient*, const Model::UpdateImageRegistryTimingScanTaskRequest&, UpdateImageRegistryTimingScanTaskOutcome, const std::shared_ptr<const AsyncCallerContext>&)> UpdateImageRegistryTimingScanTaskAsyncHandler; /** *新增单个镜像仓库详细信息 * @param req AddAssetImageRegistryRegistryDetailRequest * @return AddAssetImageRegistryRegistryDetailOutcome */ AddAssetImageRegistryRegistryDetailOutcome AddAssetImageRegistryRegistryDetail(const Model::AddAssetImageRegistryRegistryDetailRequest &request); void AddAssetImageRegistryRegistryDetailAsync(const Model::AddAssetImageRegistryRegistryDetailRequest& request, const AddAssetImageRegistryRegistryDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddAssetImageRegistryRegistryDetailOutcomeCallable AddAssetImageRegistryRegistryDetailCallable(const Model::AddAssetImageRegistryRegistryDetailRequest& request); /** *将指定的检测项添加到白名单中,不显示未通过结果。 * @param req AddCompliancePolicyItemToWhitelistRequest * @return AddCompliancePolicyItemToWhitelistOutcome */ AddCompliancePolicyItemToWhitelistOutcome AddCompliancePolicyItemToWhitelist(const Model::AddCompliancePolicyItemToWhitelistRequest &request); void AddCompliancePolicyItemToWhitelistAsync(const Model::AddCompliancePolicyItemToWhitelistRequest& request, const AddCompliancePolicyItemToWhitelistAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddCompliancePolicyItemToWhitelistOutcomeCallable AddCompliancePolicyItemToWhitelistCallable(const Model::AddCompliancePolicyItemToWhitelistRequest& request); /** *添加编辑运行时异常进程策略 * @param req AddEditAbnormalProcessRuleRequest * @return AddEditAbnormalProcessRuleOutcome */ AddEditAbnormalProcessRuleOutcome AddEditAbnormalProcessRule(const Model::AddEditAbnormalProcessRuleRequest &request); void AddEditAbnormalProcessRuleAsync(const Model::AddEditAbnormalProcessRuleRequest& request, const AddEditAbnormalProcessRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddEditAbnormalProcessRuleOutcomeCallable AddEditAbnormalProcessRuleCallable(const Model::AddEditAbnormalProcessRuleRequest& request); /** *添加编辑运行时访问控制策略 * @param req AddEditAccessControlRuleRequest * @return AddEditAccessControlRuleOutcome */ AddEditAccessControlRuleOutcome AddEditAccessControlRule(const Model::AddEditAccessControlRuleRequest &request); void AddEditAccessControlRuleAsync(const Model::AddEditAccessControlRuleRequest& request, const AddEditAccessControlRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddEditAccessControlRuleOutcomeCallable AddEditAccessControlRuleCallable(const Model::AddEditAccessControlRuleRequest& request); /** *添加编辑运行时反弹shell白名单 * @param req AddEditReverseShellWhiteListRequest * @return AddEditReverseShellWhiteListOutcome */ AddEditReverseShellWhiteListOutcome AddEditReverseShellWhiteList(const Model::AddEditReverseShellWhiteListRequest &request); void AddEditReverseShellWhiteListAsync(const Model::AddEditReverseShellWhiteListRequest& request, const AddEditReverseShellWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddEditReverseShellWhiteListOutcomeCallable AddEditReverseShellWhiteListCallable(const Model::AddEditReverseShellWhiteListRequest& request); /** *添加编辑运行时高危系统调用白名单 * @param req AddEditRiskSyscallWhiteListRequest * @return AddEditRiskSyscallWhiteListOutcome */ AddEditRiskSyscallWhiteListOutcome AddEditRiskSyscallWhiteList(const Model::AddEditRiskSyscallWhiteListRequest &request); void AddEditRiskSyscallWhiteListAsync(const Model::AddEditRiskSyscallWhiteListRequest& request, const AddEditRiskSyscallWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddEditRiskSyscallWhiteListOutcomeCallable AddEditRiskSyscallWhiteListCallable(const Model::AddEditRiskSyscallWhiteListRequest& request); /** *添加编辑告警策略 * @param req AddEditWarningRulesRequest * @return AddEditWarningRulesOutcome */ AddEditWarningRulesOutcome AddEditWarningRules(const Model::AddEditWarningRulesRequest &request); void AddEditWarningRulesAsync(const Model::AddEditWarningRulesRequest& request, const AddEditWarningRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); AddEditWarningRulesOutcomeCallable AddEditWarningRulesCallable(const Model::AddEditWarningRulesRequest& request); /** *检查单个镜像仓库名是否重复 * @param req CheckRepeatAssetImageRegistryRequest * @return CheckRepeatAssetImageRegistryOutcome */ CheckRepeatAssetImageRegistryOutcome CheckRepeatAssetImageRegistry(const Model::CheckRepeatAssetImageRegistryRequest &request); void CheckRepeatAssetImageRegistryAsync(const Model::CheckRepeatAssetImageRegistryRequest& request, const CheckRepeatAssetImageRegistryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CheckRepeatAssetImageRegistryOutcomeCallable CheckRepeatAssetImageRegistryCallable(const Model::CheckRepeatAssetImageRegistryRequest& request); /** *镜像仓库创建镜像扫描任务 * @param req CreateAssetImageRegistryScanTaskRequest * @return CreateAssetImageRegistryScanTaskOutcome */ CreateAssetImageRegistryScanTaskOutcome CreateAssetImageRegistryScanTask(const Model::CreateAssetImageRegistryScanTaskRequest &request); void CreateAssetImageRegistryScanTaskAsync(const Model::CreateAssetImageRegistryScanTaskRequest& request, const CreateAssetImageRegistryScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateAssetImageRegistryScanTaskOutcomeCallable CreateAssetImageRegistryScanTaskCallable(const Model::CreateAssetImageRegistryScanTaskRequest& request); /** *镜像仓库创建镜像一键扫描任务 * @param req CreateAssetImageRegistryScanTaskOneKeyRequest * @return CreateAssetImageRegistryScanTaskOneKeyOutcome */ CreateAssetImageRegistryScanTaskOneKeyOutcome CreateAssetImageRegistryScanTaskOneKey(const Model::CreateAssetImageRegistryScanTaskOneKeyRequest &request); void CreateAssetImageRegistryScanTaskOneKeyAsync(const Model::CreateAssetImageRegistryScanTaskOneKeyRequest& request, const CreateAssetImageRegistryScanTaskOneKeyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateAssetImageRegistryScanTaskOneKeyOutcomeCallable CreateAssetImageRegistryScanTaskOneKeyCallable(const Model::CreateAssetImageRegistryScanTaskOneKeyRequest& request); /** *添加容器安全镜像扫描设置 * @param req CreateAssetImageScanSettingRequest * @return CreateAssetImageScanSettingOutcome */ CreateAssetImageScanSettingOutcome CreateAssetImageScanSetting(const Model::CreateAssetImageScanSettingRequest &request); void CreateAssetImageScanSettingAsync(const Model::CreateAssetImageScanSettingRequest& request, const CreateAssetImageScanSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateAssetImageScanSettingOutcomeCallable CreateAssetImageScanSettingCallable(const Model::CreateAssetImageScanSettingRequest& request); /** *容器安全创建镜像扫描任务 * @param req CreateAssetImageScanTaskRequest * @return CreateAssetImageScanTaskOutcome */ CreateAssetImageScanTaskOutcome CreateAssetImageScanTask(const Model::CreateAssetImageScanTaskRequest &request); void CreateAssetImageScanTaskAsync(const Model::CreateAssetImageScanTaskRequest& request, const CreateAssetImageScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateAssetImageScanTaskOutcomeCallable CreateAssetImageScanTaskCallable(const Model::CreateAssetImageScanTaskRequest& request); /** *安装检查组件,创建防护容器 * @param req CreateCheckComponentRequest * @return CreateCheckComponentOutcome */ CreateCheckComponentOutcome CreateCheckComponent(const Model::CreateCheckComponentRequest &request); void CreateCheckComponentAsync(const Model::CreateCheckComponentRequest& request, const CreateCheckComponentAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateCheckComponentOutcomeCallable CreateCheckComponentCallable(const Model::CreateCheckComponentRequest& request); /** *创建集群检查任务,用户检查用户的集群相关风险项 * @param req CreateClusterCheckTaskRequest * @return CreateClusterCheckTaskOutcome */ CreateClusterCheckTaskOutcome CreateClusterCheckTask(const Model::CreateClusterCheckTaskRequest &request); void CreateClusterCheckTaskAsync(const Model::CreateClusterCheckTaskRequest& request, const CreateClusterCheckTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateClusterCheckTaskOutcomeCallable CreateClusterCheckTaskCallable(const Model::CreateClusterCheckTaskRequest& request); /** *创建合规检查任务,在资产级别触发重新检测时使用。 * @param req CreateComplianceTaskRequest * @return CreateComplianceTaskOutcome */ CreateComplianceTaskOutcome CreateComplianceTask(const Model::CreateComplianceTaskRequest &request); void CreateComplianceTaskAsync(const Model::CreateComplianceTaskRequest& request, const CreateComplianceTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateComplianceTaskOutcomeCallable CreateComplianceTaskCallable(const Model::CreateComplianceTaskRequest& request); /** *创建一个导出安全合规信息的任务 * @param req CreateExportComplianceStatusListJobRequest * @return CreateExportComplianceStatusListJobOutcome */ CreateExportComplianceStatusListJobOutcome CreateExportComplianceStatusListJob(const Model::CreateExportComplianceStatusListJobRequest &request); void CreateExportComplianceStatusListJobAsync(const Model::CreateExportComplianceStatusListJobRequest& request, const CreateExportComplianceStatusListJobAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateExportComplianceStatusListJobOutcomeCallable CreateExportComplianceStatusListJobCallable(const Model::CreateExportComplianceStatusListJobRequest& request); /** *CreateOrModifyPostPayCores 创建或者编辑弹性计费上限 * @param req CreateOrModifyPostPayCoresRequest * @return CreateOrModifyPostPayCoresOutcome */ CreateOrModifyPostPayCoresOutcome CreateOrModifyPostPayCores(const Model::CreateOrModifyPostPayCoresRequest &request); void CreateOrModifyPostPayCoresAsync(const Model::CreateOrModifyPostPayCoresRequest& request, const CreateOrModifyPostPayCoresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateOrModifyPostPayCoresOutcomeCallable CreateOrModifyPostPayCoresCallable(const Model::CreateOrModifyPostPayCoresRequest& request); /** *下发刷新任务,会刷新资产信息 * @param req CreateRefreshTaskRequest * @return CreateRefreshTaskOutcome */ CreateRefreshTaskOutcome CreateRefreshTask(const Model::CreateRefreshTaskRequest &request); void CreateRefreshTaskAsync(const Model::CreateRefreshTaskRequest& request, const CreateRefreshTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateRefreshTaskOutcomeCallable CreateRefreshTaskCallable(const Model::CreateRefreshTaskRequest& request); /** *运行时文件查杀重新检测 * @param req CreateVirusScanAgainRequest * @return CreateVirusScanAgainOutcome */ CreateVirusScanAgainOutcome CreateVirusScanAgain(const Model::CreateVirusScanAgainRequest &request); void CreateVirusScanAgainAsync(const Model::CreateVirusScanAgainRequest& request, const CreateVirusScanAgainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateVirusScanAgainOutcomeCallable CreateVirusScanAgainCallable(const Model::CreateVirusScanAgainRequest& request); /** *运行时文件查杀一键扫描 * @param req CreateVirusScanTaskRequest * @return CreateVirusScanTaskOutcome */ CreateVirusScanTaskOutcome CreateVirusScanTask(const Model::CreateVirusScanTaskRequest &request); void CreateVirusScanTaskAsync(const Model::CreateVirusScanTaskRequest& request, const CreateVirusScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); CreateVirusScanTaskOutcomeCallable CreateVirusScanTaskCallable(const Model::CreateVirusScanTaskRequest& request); /** *删除运行异常进程策略 * @param req DeleteAbnormalProcessRulesRequest * @return DeleteAbnormalProcessRulesOutcome */ DeleteAbnormalProcessRulesOutcome DeleteAbnormalProcessRules(const Model::DeleteAbnormalProcessRulesRequest &request); void DeleteAbnormalProcessRulesAsync(const Model::DeleteAbnormalProcessRulesRequest& request, const DeleteAbnormalProcessRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DeleteAbnormalProcessRulesOutcomeCallable DeleteAbnormalProcessRulesCallable(const Model::DeleteAbnormalProcessRulesRequest& request); /** *删除运行访问控制策略 * @param req DeleteAccessControlRulesRequest * @return DeleteAccessControlRulesOutcome */ DeleteAccessControlRulesOutcome DeleteAccessControlRules(const Model::DeleteAccessControlRulesRequest &request); void DeleteAccessControlRulesAsync(const Model::DeleteAccessControlRulesRequest& request, const DeleteAccessControlRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DeleteAccessControlRulesOutcomeCallable DeleteAccessControlRulesCallable(const Model::DeleteAccessControlRulesRequest& request); /** *从白名单中删除将指定的检测项。 * @param req DeleteCompliancePolicyItemFromWhitelistRequest * @return DeleteCompliancePolicyItemFromWhitelistOutcome */ DeleteCompliancePolicyItemFromWhitelistOutcome DeleteCompliancePolicyItemFromWhitelist(const Model::DeleteCompliancePolicyItemFromWhitelistRequest &request); void DeleteCompliancePolicyItemFromWhitelistAsync(const Model::DeleteCompliancePolicyItemFromWhitelistRequest& request, const DeleteCompliancePolicyItemFromWhitelistAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DeleteCompliancePolicyItemFromWhitelistOutcomeCallable DeleteCompliancePolicyItemFromWhitelistCallable(const Model::DeleteCompliancePolicyItemFromWhitelistRequest& request); /** *删除运行时反弹shell白名单 * @param req DeleteReverseShellWhiteListsRequest * @return DeleteReverseShellWhiteListsOutcome */ DeleteReverseShellWhiteListsOutcome DeleteReverseShellWhiteLists(const Model::DeleteReverseShellWhiteListsRequest &request); void DeleteReverseShellWhiteListsAsync(const Model::DeleteReverseShellWhiteListsRequest& request, const DeleteReverseShellWhiteListsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DeleteReverseShellWhiteListsOutcomeCallable DeleteReverseShellWhiteListsCallable(const Model::DeleteReverseShellWhiteListsRequest& request); /** *删除运行时高危系统调用白名单 * @param req DeleteRiskSyscallWhiteListsRequest * @return DeleteRiskSyscallWhiteListsOutcome */ DeleteRiskSyscallWhiteListsOutcome DeleteRiskSyscallWhiteLists(const Model::DeleteRiskSyscallWhiteListsRequest &request); void DeleteRiskSyscallWhiteListsAsync(const Model::DeleteRiskSyscallWhiteListsRequest& request, const DeleteRiskSyscallWhiteListsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DeleteRiskSyscallWhiteListsOutcomeCallable DeleteRiskSyscallWhiteListsCallable(const Model::DeleteRiskSyscallWhiteListsRequest& request); /** *查询运行时异常进程事件详细信息 * @param req DescribeAbnormalProcessDetailRequest * @return DescribeAbnormalProcessDetailOutcome */ DescribeAbnormalProcessDetailOutcome DescribeAbnormalProcessDetail(const Model::DescribeAbnormalProcessDetailRequest &request); void DescribeAbnormalProcessDetailAsync(const Model::DescribeAbnormalProcessDetailRequest& request, const DescribeAbnormalProcessDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessDetailOutcomeCallable DescribeAbnormalProcessDetailCallable(const Model::DescribeAbnormalProcessDetailRequest& request); /** *查询运行时异常进程事件列表信息 * @param req DescribeAbnormalProcessEventsRequest * @return DescribeAbnormalProcessEventsOutcome */ DescribeAbnormalProcessEventsOutcome DescribeAbnormalProcessEvents(const Model::DescribeAbnormalProcessEventsRequest &request); void DescribeAbnormalProcessEventsAsync(const Model::DescribeAbnormalProcessEventsRequest& request, const DescribeAbnormalProcessEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessEventsOutcomeCallable DescribeAbnormalProcessEventsCallable(const Model::DescribeAbnormalProcessEventsRequest& request); /** *查询运行时异常进程事件列表信息导出 * @param req DescribeAbnormalProcessEventsExportRequest * @return DescribeAbnormalProcessEventsExportOutcome */ DescribeAbnormalProcessEventsExportOutcome DescribeAbnormalProcessEventsExport(const Model::DescribeAbnormalProcessEventsExportRequest &request); void DescribeAbnormalProcessEventsExportAsync(const Model::DescribeAbnormalProcessEventsExportRequest& request, const DescribeAbnormalProcessEventsExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessEventsExportOutcomeCallable DescribeAbnormalProcessEventsExportCallable(const Model::DescribeAbnormalProcessEventsExportRequest& request); /** *查询运行时异常策略详细信息 * @param req DescribeAbnormalProcessRuleDetailRequest * @return DescribeAbnormalProcessRuleDetailOutcome */ DescribeAbnormalProcessRuleDetailOutcome DescribeAbnormalProcessRuleDetail(const Model::DescribeAbnormalProcessRuleDetailRequest &request); void DescribeAbnormalProcessRuleDetailAsync(const Model::DescribeAbnormalProcessRuleDetailRequest& request, const DescribeAbnormalProcessRuleDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessRuleDetailOutcomeCallable DescribeAbnormalProcessRuleDetailCallable(const Model::DescribeAbnormalProcessRuleDetailRequest& request); /** *查询运行时异常进程策略列表信息 * @param req DescribeAbnormalProcessRulesRequest * @return DescribeAbnormalProcessRulesOutcome */ DescribeAbnormalProcessRulesOutcome DescribeAbnormalProcessRules(const Model::DescribeAbnormalProcessRulesRequest &request); void DescribeAbnormalProcessRulesAsync(const Model::DescribeAbnormalProcessRulesRequest& request, const DescribeAbnormalProcessRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessRulesOutcomeCallable DescribeAbnormalProcessRulesCallable(const Model::DescribeAbnormalProcessRulesRequest& request); /** *查询运行时异常进程策略列表信息导出 * @param req DescribeAbnormalProcessRulesExportRequest * @return DescribeAbnormalProcessRulesExportOutcome */ DescribeAbnormalProcessRulesExportOutcome DescribeAbnormalProcessRulesExport(const Model::DescribeAbnormalProcessRulesExportRequest &request); void DescribeAbnormalProcessRulesExportAsync(const Model::DescribeAbnormalProcessRulesExportRequest& request, const DescribeAbnormalProcessRulesExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAbnormalProcessRulesExportOutcomeCallable DescribeAbnormalProcessRulesExportCallable(const Model::DescribeAbnormalProcessRulesExportRequest& request); /** *查询运行时访问控制事件的详细信息 * @param req DescribeAccessControlDetailRequest * @return DescribeAccessControlDetailOutcome */ DescribeAccessControlDetailOutcome DescribeAccessControlDetail(const Model::DescribeAccessControlDetailRequest &request); void DescribeAccessControlDetailAsync(const Model::DescribeAccessControlDetailRequest& request, const DescribeAccessControlDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlDetailOutcomeCallable DescribeAccessControlDetailCallable(const Model::DescribeAccessControlDetailRequest& request); /** *查询运行时访问控制事件列表 * @param req DescribeAccessControlEventsRequest * @return DescribeAccessControlEventsOutcome */ DescribeAccessControlEventsOutcome DescribeAccessControlEvents(const Model::DescribeAccessControlEventsRequest &request); void DescribeAccessControlEventsAsync(const Model::DescribeAccessControlEventsRequest& request, const DescribeAccessControlEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlEventsOutcomeCallable DescribeAccessControlEventsCallable(const Model::DescribeAccessControlEventsRequest& request); /** *查询运行时访问控制事件列表导出 * @param req DescribeAccessControlEventsExportRequest * @return DescribeAccessControlEventsExportOutcome */ DescribeAccessControlEventsExportOutcome DescribeAccessControlEventsExport(const Model::DescribeAccessControlEventsExportRequest &request); void DescribeAccessControlEventsExportAsync(const Model::DescribeAccessControlEventsExportRequest& request, const DescribeAccessControlEventsExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlEventsExportOutcomeCallable DescribeAccessControlEventsExportCallable(const Model::DescribeAccessControlEventsExportRequest& request); /** *查询运行时访问控制策略详细信息 * @param req DescribeAccessControlRuleDetailRequest * @return DescribeAccessControlRuleDetailOutcome */ DescribeAccessControlRuleDetailOutcome DescribeAccessControlRuleDetail(const Model::DescribeAccessControlRuleDetailRequest &request); void DescribeAccessControlRuleDetailAsync(const Model::DescribeAccessControlRuleDetailRequest& request, const DescribeAccessControlRuleDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlRuleDetailOutcomeCallable DescribeAccessControlRuleDetailCallable(const Model::DescribeAccessControlRuleDetailRequest& request); /** *查询运行访问控制策略列表信息 * @param req DescribeAccessControlRulesRequest * @return DescribeAccessControlRulesOutcome */ DescribeAccessControlRulesOutcome DescribeAccessControlRules(const Model::DescribeAccessControlRulesRequest &request); void DescribeAccessControlRulesAsync(const Model::DescribeAccessControlRulesRequest& request, const DescribeAccessControlRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlRulesOutcomeCallable DescribeAccessControlRulesCallable(const Model::DescribeAccessControlRulesRequest& request); /** *查询运行时访问控制策略列表导出 * @param req DescribeAccessControlRulesExportRequest * @return DescribeAccessControlRulesExportOutcome */ DescribeAccessControlRulesExportOutcome DescribeAccessControlRulesExport(const Model::DescribeAccessControlRulesExportRequest &request); void DescribeAccessControlRulesExportAsync(const Model::DescribeAccessControlRulesExportRequest& request, const DescribeAccessControlRulesExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAccessControlRulesExportOutcomeCallable DescribeAccessControlRulesExportCallable(const Model::DescribeAccessControlRulesExportRequest& request); /** *获取受影响的集群数量,返回数量 * @param req DescribeAffectedClusterCountRequest * @return DescribeAffectedClusterCountOutcome */ DescribeAffectedClusterCountOutcome DescribeAffectedClusterCount(const Model::DescribeAffectedClusterCountRequest &request); void DescribeAffectedClusterCountAsync(const Model::DescribeAffectedClusterCountRequest& request, const DescribeAffectedClusterCountAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAffectedClusterCountOutcomeCallable DescribeAffectedClusterCountCallable(const Model::DescribeAffectedClusterCountRequest& request); /** *查询节点类型的影响范围,返回节点列表 * @param req DescribeAffectedNodeListRequest * @return DescribeAffectedNodeListOutcome */ DescribeAffectedNodeListOutcome DescribeAffectedNodeList(const Model::DescribeAffectedNodeListRequest &request); void DescribeAffectedNodeListAsync(const Model::DescribeAffectedNodeListRequest& request, const DescribeAffectedNodeListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAffectedNodeListOutcomeCallable DescribeAffectedNodeListCallable(const Model::DescribeAffectedNodeListRequest& request); /** *查询workload类型的影响范围,返回workload列表 * @param req DescribeAffectedWorkloadListRequest * @return DescribeAffectedWorkloadListOutcome */ DescribeAffectedWorkloadListOutcome DescribeAffectedWorkloadList(const Model::DescribeAffectedWorkloadListRequest &request); void DescribeAffectedWorkloadListAsync(const Model::DescribeAffectedWorkloadListRequest& request, const DescribeAffectedWorkloadListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAffectedWorkloadListOutcomeCallable DescribeAffectedWorkloadListCallable(const Model::DescribeAffectedWorkloadListRequest& request); /** *容器安全查询app服务列表 * @param req DescribeAssetAppServiceListRequest * @return DescribeAssetAppServiceListOutcome */ DescribeAssetAppServiceListOutcome DescribeAssetAppServiceList(const Model::DescribeAssetAppServiceListRequest &request); void DescribeAssetAppServiceListAsync(const Model::DescribeAssetAppServiceListRequest& request, const DescribeAssetAppServiceListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetAppServiceListOutcomeCallable DescribeAssetAppServiceListCallable(const Model::DescribeAssetAppServiceListRequest& request); /** *容器安全搜索查询容器组件列表 * @param req DescribeAssetComponentListRequest * @return DescribeAssetComponentListOutcome */ DescribeAssetComponentListOutcome DescribeAssetComponentList(const Model::DescribeAssetComponentListRequest &request); void DescribeAssetComponentListAsync(const Model::DescribeAssetComponentListRequest& request, const DescribeAssetComponentListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetComponentListOutcomeCallable DescribeAssetComponentListCallable(const Model::DescribeAssetComponentListRequest& request); /** *查询容器详细信息 * @param req DescribeAssetContainerDetailRequest * @return DescribeAssetContainerDetailOutcome */ DescribeAssetContainerDetailOutcome DescribeAssetContainerDetail(const Model::DescribeAssetContainerDetailRequest &request); void DescribeAssetContainerDetailAsync(const Model::DescribeAssetContainerDetailRequest& request, const DescribeAssetContainerDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetContainerDetailOutcomeCallable DescribeAssetContainerDetailCallable(const Model::DescribeAssetContainerDetailRequest& request); /** *搜索查询容器列表 * @param req DescribeAssetContainerListRequest * @return DescribeAssetContainerListOutcome */ DescribeAssetContainerListOutcome DescribeAssetContainerList(const Model::DescribeAssetContainerListRequest &request); void DescribeAssetContainerListAsync(const Model::DescribeAssetContainerListRequest& request, const DescribeAssetContainerListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetContainerListOutcomeCallable DescribeAssetContainerListCallable(const Model::DescribeAssetContainerListRequest& request); /** *容器安全查询db服务列表 * @param req DescribeAssetDBServiceListRequest * @return DescribeAssetDBServiceListOutcome */ DescribeAssetDBServiceListOutcome DescribeAssetDBServiceList(const Model::DescribeAssetDBServiceListRequest &request); void DescribeAssetDBServiceListAsync(const Model::DescribeAssetDBServiceListRequest& request, const DescribeAssetDBServiceListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetDBServiceListOutcomeCallable DescribeAssetDBServiceListCallable(const Model::DescribeAssetDBServiceListRequest& request); /** *查询主机详细信息 * @param req DescribeAssetHostDetailRequest * @return DescribeAssetHostDetailOutcome */ DescribeAssetHostDetailOutcome DescribeAssetHostDetail(const Model::DescribeAssetHostDetailRequest &request); void DescribeAssetHostDetailAsync(const Model::DescribeAssetHostDetailRequest& request, const DescribeAssetHostDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetHostDetailOutcomeCallable DescribeAssetHostDetailCallable(const Model::DescribeAssetHostDetailRequest& request); /** *容器安全搜索查询主机列表 * @param req DescribeAssetHostListRequest * @return DescribeAssetHostListOutcome */ DescribeAssetHostListOutcome DescribeAssetHostList(const Model::DescribeAssetHostListRequest &request); void DescribeAssetHostListAsync(const Model::DescribeAssetHostListRequest& request, const DescribeAssetHostListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetHostListOutcomeCallable DescribeAssetHostListCallable(const Model::DescribeAssetHostListRequest& request); /** *镜像绑定规则列表信息,包含运行时访问控制和异常进程公用 * @param req DescribeAssetImageBindRuleInfoRequest * @return DescribeAssetImageBindRuleInfoOutcome */ DescribeAssetImageBindRuleInfoOutcome DescribeAssetImageBindRuleInfo(const Model::DescribeAssetImageBindRuleInfoRequest &request); void DescribeAssetImageBindRuleInfoAsync(const Model::DescribeAssetImageBindRuleInfoRequest& request, const DescribeAssetImageBindRuleInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageBindRuleInfoOutcomeCallable DescribeAssetImageBindRuleInfoCallable(const Model::DescribeAssetImageBindRuleInfoRequest& request); /** *查询镜像详细信息 * @param req DescribeAssetImageDetailRequest * @return DescribeAssetImageDetailOutcome */ DescribeAssetImageDetailOutcome DescribeAssetImageDetail(const Model::DescribeAssetImageDetailRequest &request); void DescribeAssetImageDetailAsync(const Model::DescribeAssetImageDetailRequest& request, const DescribeAssetImageDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageDetailOutcomeCallable DescribeAssetImageDetailCallable(const Model::DescribeAssetImageDetailRequest& request); /** *容器安全查询镜像关联主机 * @param req DescribeAssetImageHostListRequest * @return DescribeAssetImageHostListOutcome */ DescribeAssetImageHostListOutcome DescribeAssetImageHostList(const Model::DescribeAssetImageHostListRequest &request); void DescribeAssetImageHostListAsync(const Model::DescribeAssetImageHostListRequest& request, const DescribeAssetImageHostListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageHostListOutcomeCallable DescribeAssetImageHostListCallable(const Model::DescribeAssetImageHostListRequest& request); /** *容器安全搜索查询镜像列表 * @param req DescribeAssetImageListRequest * @return DescribeAssetImageListOutcome */ DescribeAssetImageListOutcome DescribeAssetImageList(const Model::DescribeAssetImageListRequest &request); void DescribeAssetImageListAsync(const Model::DescribeAssetImageListRequest& request, const DescribeAssetImageListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageListOutcomeCallable DescribeAssetImageListCallable(const Model::DescribeAssetImageListRequest& request); /** *容器安全搜索查询镜像列表导出 * @param req DescribeAssetImageListExportRequest * @return DescribeAssetImageListExportOutcome */ DescribeAssetImageListExportOutcome DescribeAssetImageListExport(const Model::DescribeAssetImageListExportRequest &request); void DescribeAssetImageListExportAsync(const Model::DescribeAssetImageListExportRequest& request, const DescribeAssetImageListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageListExportOutcomeCallable DescribeAssetImageListExportCallable(const Model::DescribeAssetImageListExportRequest& request); /** *查看镜像仓库资产更新进度状态 * @param req DescribeAssetImageRegistryAssetStatusRequest * @return DescribeAssetImageRegistryAssetStatusOutcome */ DescribeAssetImageRegistryAssetStatusOutcome DescribeAssetImageRegistryAssetStatus(const Model::DescribeAssetImageRegistryAssetStatusRequest &request); void DescribeAssetImageRegistryAssetStatusAsync(const Model::DescribeAssetImageRegistryAssetStatusRequest& request, const DescribeAssetImageRegistryAssetStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryAssetStatusOutcomeCallable DescribeAssetImageRegistryAssetStatusCallable(const Model::DescribeAssetImageRegistryAssetStatusRequest& request); /** *镜像仓库镜像仓库列表详情 * @param req DescribeAssetImageRegistryDetailRequest * @return DescribeAssetImageRegistryDetailOutcome */ DescribeAssetImageRegistryDetailOutcome DescribeAssetImageRegistryDetail(const Model::DescribeAssetImageRegistryDetailRequest &request); void DescribeAssetImageRegistryDetailAsync(const Model::DescribeAssetImageRegistryDetailRequest& request, const DescribeAssetImageRegistryDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryDetailOutcomeCallable DescribeAssetImageRegistryDetailCallable(const Model::DescribeAssetImageRegistryDetailRequest& request); /** *镜像仓库镜像仓库列表 * @param req DescribeAssetImageRegistryListRequest * @return DescribeAssetImageRegistryListOutcome */ DescribeAssetImageRegistryListOutcome DescribeAssetImageRegistryList(const Model::DescribeAssetImageRegistryListRequest &request); void DescribeAssetImageRegistryListAsync(const Model::DescribeAssetImageRegistryListRequest& request, const DescribeAssetImageRegistryListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryListOutcomeCallable DescribeAssetImageRegistryListCallable(const Model::DescribeAssetImageRegistryListRequest& request); /** *镜像仓库镜像列表导出 * @param req DescribeAssetImageRegistryListExportRequest * @return DescribeAssetImageRegistryListExportOutcome */ DescribeAssetImageRegistryListExportOutcome DescribeAssetImageRegistryListExport(const Model::DescribeAssetImageRegistryListExportRequest &request); void DescribeAssetImageRegistryListExportAsync(const Model::DescribeAssetImageRegistryListExportRequest& request, const DescribeAssetImageRegistryListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryListExportOutcomeCallable DescribeAssetImageRegistryListExportCallable(const Model::DescribeAssetImageRegistryListExportRequest& request); /** *查看单个镜像仓库详细信息 * @param req DescribeAssetImageRegistryRegistryDetailRequest * @return DescribeAssetImageRegistryRegistryDetailOutcome */ DescribeAssetImageRegistryRegistryDetailOutcome DescribeAssetImageRegistryRegistryDetail(const Model::DescribeAssetImageRegistryRegistryDetailRequest &request); void DescribeAssetImageRegistryRegistryDetailAsync(const Model::DescribeAssetImageRegistryRegistryDetailRequest& request, const DescribeAssetImageRegistryRegistryDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryRegistryDetailOutcomeCallable DescribeAssetImageRegistryRegistryDetailCallable(const Model::DescribeAssetImageRegistryRegistryDetailRequest& request); /** *镜像仓库仓库列表 * @param req DescribeAssetImageRegistryRegistryListRequest * @return DescribeAssetImageRegistryRegistryListOutcome */ DescribeAssetImageRegistryRegistryListOutcome DescribeAssetImageRegistryRegistryList(const Model::DescribeAssetImageRegistryRegistryListRequest &request); void DescribeAssetImageRegistryRegistryListAsync(const Model::DescribeAssetImageRegistryRegistryListRequest& request, const DescribeAssetImageRegistryRegistryListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryRegistryListOutcomeCallable DescribeAssetImageRegistryRegistryListCallable(const Model::DescribeAssetImageRegistryRegistryListRequest& request); /** *镜像仓库查询镜像高危行为列表 * @param req DescribeAssetImageRegistryRiskInfoListRequest * @return DescribeAssetImageRegistryRiskInfoListOutcome */ DescribeAssetImageRegistryRiskInfoListOutcome DescribeAssetImageRegistryRiskInfoList(const Model::DescribeAssetImageRegistryRiskInfoListRequest &request); void DescribeAssetImageRegistryRiskInfoListAsync(const Model::DescribeAssetImageRegistryRiskInfoListRequest& request, const DescribeAssetImageRegistryRiskInfoListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryRiskInfoListOutcomeCallable DescribeAssetImageRegistryRiskInfoListCallable(const Model::DescribeAssetImageRegistryRiskInfoListRequest& request); /** *镜像仓库敏感信息列表导出 * @param req DescribeAssetImageRegistryRiskListExportRequest * @return DescribeAssetImageRegistryRiskListExportOutcome */ DescribeAssetImageRegistryRiskListExportOutcome DescribeAssetImageRegistryRiskListExport(const Model::DescribeAssetImageRegistryRiskListExportRequest &request); void DescribeAssetImageRegistryRiskListExportAsync(const Model::DescribeAssetImageRegistryRiskListExportRequest& request, const DescribeAssetImageRegistryRiskListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryRiskListExportOutcomeCallable DescribeAssetImageRegistryRiskListExportCallable(const Model::DescribeAssetImageRegistryRiskListExportRequest& request); /** *镜像仓库查询一键镜像扫描状态 * @param req DescribeAssetImageRegistryScanStatusOneKeyRequest * @return DescribeAssetImageRegistryScanStatusOneKeyOutcome */ DescribeAssetImageRegistryScanStatusOneKeyOutcome DescribeAssetImageRegistryScanStatusOneKey(const Model::DescribeAssetImageRegistryScanStatusOneKeyRequest &request); void DescribeAssetImageRegistryScanStatusOneKeyAsync(const Model::DescribeAssetImageRegistryScanStatusOneKeyRequest& request, const DescribeAssetImageRegistryScanStatusOneKeyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryScanStatusOneKeyOutcomeCallable DescribeAssetImageRegistryScanStatusOneKeyCallable(const Model::DescribeAssetImageRegistryScanStatusOneKeyRequest& request); /** *镜像仓库查询镜像统计信息 * @param req DescribeAssetImageRegistrySummaryRequest * @return DescribeAssetImageRegistrySummaryOutcome */ DescribeAssetImageRegistrySummaryOutcome DescribeAssetImageRegistrySummary(const Model::DescribeAssetImageRegistrySummaryRequest &request); void DescribeAssetImageRegistrySummaryAsync(const Model::DescribeAssetImageRegistrySummaryRequest& request, const DescribeAssetImageRegistrySummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistrySummaryOutcomeCallable DescribeAssetImageRegistrySummaryCallable(const Model::DescribeAssetImageRegistrySummaryRequest& request); /** *镜像仓库查询木马病毒列表 * @param req DescribeAssetImageRegistryVirusListRequest * @return DescribeAssetImageRegistryVirusListOutcome */ DescribeAssetImageRegistryVirusListOutcome DescribeAssetImageRegistryVirusList(const Model::DescribeAssetImageRegistryVirusListRequest &request); void DescribeAssetImageRegistryVirusListAsync(const Model::DescribeAssetImageRegistryVirusListRequest& request, const DescribeAssetImageRegistryVirusListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryVirusListOutcomeCallable DescribeAssetImageRegistryVirusListCallable(const Model::DescribeAssetImageRegistryVirusListRequest& request); /** *镜像仓库木马信息列表导出 * @param req DescribeAssetImageRegistryVirusListExportRequest * @return DescribeAssetImageRegistryVirusListExportOutcome */ DescribeAssetImageRegistryVirusListExportOutcome DescribeAssetImageRegistryVirusListExport(const Model::DescribeAssetImageRegistryVirusListExportRequest &request); void DescribeAssetImageRegistryVirusListExportAsync(const Model::DescribeAssetImageRegistryVirusListExportRequest& request, const DescribeAssetImageRegistryVirusListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryVirusListExportOutcomeCallable DescribeAssetImageRegistryVirusListExportCallable(const Model::DescribeAssetImageRegistryVirusListExportRequest& request); /** *镜像仓库查询镜像漏洞列表 * @param req DescribeAssetImageRegistryVulListRequest * @return DescribeAssetImageRegistryVulListOutcome */ DescribeAssetImageRegistryVulListOutcome DescribeAssetImageRegistryVulList(const Model::DescribeAssetImageRegistryVulListRequest &request); void DescribeAssetImageRegistryVulListAsync(const Model::DescribeAssetImageRegistryVulListRequest& request, const DescribeAssetImageRegistryVulListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryVulListOutcomeCallable DescribeAssetImageRegistryVulListCallable(const Model::DescribeAssetImageRegistryVulListRequest& request); /** *镜像仓库漏洞列表导出 * @param req DescribeAssetImageRegistryVulListExportRequest * @return DescribeAssetImageRegistryVulListExportOutcome */ DescribeAssetImageRegistryVulListExportOutcome DescribeAssetImageRegistryVulListExport(const Model::DescribeAssetImageRegistryVulListExportRequest &request); void DescribeAssetImageRegistryVulListExportAsync(const Model::DescribeAssetImageRegistryVulListExportRequest& request, const DescribeAssetImageRegistryVulListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRegistryVulListExportOutcomeCallable DescribeAssetImageRegistryVulListExportCallable(const Model::DescribeAssetImageRegistryVulListExportRequest& request); /** *容器安全查询镜像风险列表 * @param req DescribeAssetImageRiskListRequest * @return DescribeAssetImageRiskListOutcome */ DescribeAssetImageRiskListOutcome DescribeAssetImageRiskList(const Model::DescribeAssetImageRiskListRequest &request); void DescribeAssetImageRiskListAsync(const Model::DescribeAssetImageRiskListRequest& request, const DescribeAssetImageRiskListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRiskListOutcomeCallable DescribeAssetImageRiskListCallable(const Model::DescribeAssetImageRiskListRequest& request); /** *容器安全搜索查询镜像风险列表导出 * @param req DescribeAssetImageRiskListExportRequest * @return DescribeAssetImageRiskListExportOutcome */ DescribeAssetImageRiskListExportOutcome DescribeAssetImageRiskListExport(const Model::DescribeAssetImageRiskListExportRequest &request); void DescribeAssetImageRiskListExportAsync(const Model::DescribeAssetImageRiskListExportRequest& request, const DescribeAssetImageRiskListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageRiskListExportOutcomeCallable DescribeAssetImageRiskListExportCallable(const Model::DescribeAssetImageRiskListExportRequest& request); /** *获取镜像扫描设置信息 * @param req DescribeAssetImageScanSettingRequest * @return DescribeAssetImageScanSettingOutcome */ DescribeAssetImageScanSettingOutcome DescribeAssetImageScanSetting(const Model::DescribeAssetImageScanSettingRequest &request); void DescribeAssetImageScanSettingAsync(const Model::DescribeAssetImageScanSettingRequest& request, const DescribeAssetImageScanSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageScanSettingOutcomeCallable DescribeAssetImageScanSettingCallable(const Model::DescribeAssetImageScanSettingRequest& request); /** *容器安全查询镜像扫描状态 * @param req DescribeAssetImageScanStatusRequest * @return DescribeAssetImageScanStatusOutcome */ DescribeAssetImageScanStatusOutcome DescribeAssetImageScanStatus(const Model::DescribeAssetImageScanStatusRequest &request); void DescribeAssetImageScanStatusAsync(const Model::DescribeAssetImageScanStatusRequest& request, const DescribeAssetImageScanStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageScanStatusOutcomeCallable DescribeAssetImageScanStatusCallable(const Model::DescribeAssetImageScanStatusRequest& request); /** *查询正在一键扫描的镜像扫描taskid * @param req DescribeAssetImageScanTaskRequest * @return DescribeAssetImageScanTaskOutcome */ DescribeAssetImageScanTaskOutcome DescribeAssetImageScanTask(const Model::DescribeAssetImageScanTaskRequest &request); void DescribeAssetImageScanTaskAsync(const Model::DescribeAssetImageScanTaskRequest& request, const DescribeAssetImageScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageScanTaskOutcomeCallable DescribeAssetImageScanTaskCallable(const Model::DescribeAssetImageScanTaskRequest& request); /** *容器安全搜索查询镜像简略信息列表 * @param req DescribeAssetImageSimpleListRequest * @return DescribeAssetImageSimpleListOutcome */ DescribeAssetImageSimpleListOutcome DescribeAssetImageSimpleList(const Model::DescribeAssetImageSimpleListRequest &request); void DescribeAssetImageSimpleListAsync(const Model::DescribeAssetImageSimpleListRequest& request, const DescribeAssetImageSimpleListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageSimpleListOutcomeCallable DescribeAssetImageSimpleListCallable(const Model::DescribeAssetImageSimpleListRequest& request); /** *容器安全查询镜像病毒列表 * @param req DescribeAssetImageVirusListRequest * @return DescribeAssetImageVirusListOutcome */ DescribeAssetImageVirusListOutcome DescribeAssetImageVirusList(const Model::DescribeAssetImageVirusListRequest &request); void DescribeAssetImageVirusListAsync(const Model::DescribeAssetImageVirusListRequest& request, const DescribeAssetImageVirusListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageVirusListOutcomeCallable DescribeAssetImageVirusListCallable(const Model::DescribeAssetImageVirusListRequest& request); /** *容器安全搜索查询镜像木马列表导出 * @param req DescribeAssetImageVirusListExportRequest * @return DescribeAssetImageVirusListExportOutcome */ DescribeAssetImageVirusListExportOutcome DescribeAssetImageVirusListExport(const Model::DescribeAssetImageVirusListExportRequest &request); void DescribeAssetImageVirusListExportAsync(const Model::DescribeAssetImageVirusListExportRequest& request, const DescribeAssetImageVirusListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageVirusListExportOutcomeCallable DescribeAssetImageVirusListExportCallable(const Model::DescribeAssetImageVirusListExportRequest& request); /** *容器安全查询镜像漏洞列表 * @param req DescribeAssetImageVulListRequest * @return DescribeAssetImageVulListOutcome */ DescribeAssetImageVulListOutcome DescribeAssetImageVulList(const Model::DescribeAssetImageVulListRequest &request); void DescribeAssetImageVulListAsync(const Model::DescribeAssetImageVulListRequest& request, const DescribeAssetImageVulListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageVulListOutcomeCallable DescribeAssetImageVulListCallable(const Model::DescribeAssetImageVulListRequest& request); /** *容器安全搜索查询镜像漏洞列表导出 * @param req DescribeAssetImageVulListExportRequest * @return DescribeAssetImageVulListExportOutcome */ DescribeAssetImageVulListExportOutcome DescribeAssetImageVulListExport(const Model::DescribeAssetImageVulListExportRequest &request); void DescribeAssetImageVulListExportAsync(const Model::DescribeAssetImageVulListExportRequest& request, const DescribeAssetImageVulListExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetImageVulListExportOutcomeCallable DescribeAssetImageVulListExportCallable(const Model::DescribeAssetImageVulListExportRequest& request); /** *容器安全搜索查询端口占用列表 * @param req DescribeAssetPortListRequest * @return DescribeAssetPortListOutcome */ DescribeAssetPortListOutcome DescribeAssetPortList(const Model::DescribeAssetPortListRequest &request); void DescribeAssetPortListAsync(const Model::DescribeAssetPortListRequest& request, const DescribeAssetPortListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetPortListOutcomeCallable DescribeAssetPortListCallable(const Model::DescribeAssetPortListRequest& request); /** *容器安全搜索查询进程列表 * @param req DescribeAssetProcessListRequest * @return DescribeAssetProcessListOutcome */ DescribeAssetProcessListOutcome DescribeAssetProcessList(const Model::DescribeAssetProcessListRequest &request); void DescribeAssetProcessListAsync(const Model::DescribeAssetProcessListRequest& request, const DescribeAssetProcessListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetProcessListOutcomeCallable DescribeAssetProcessListCallable(const Model::DescribeAssetProcessListRequest& request); /** *查询账户容器、镜像等统计信息 * @param req DescribeAssetSummaryRequest * @return DescribeAssetSummaryOutcome */ DescribeAssetSummaryOutcome DescribeAssetSummary(const Model::DescribeAssetSummaryRequest &request); void DescribeAssetSummaryAsync(const Model::DescribeAssetSummaryRequest& request, const DescribeAssetSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetSummaryOutcomeCallable DescribeAssetSummaryCallable(const Model::DescribeAssetSummaryRequest& request); /** *容器安全查询web服务列表 * @param req DescribeAssetWebServiceListRequest * @return DescribeAssetWebServiceListOutcome */ DescribeAssetWebServiceListOutcome DescribeAssetWebServiceList(const Model::DescribeAssetWebServiceListRequest &request); void DescribeAssetWebServiceListAsync(const Model::DescribeAssetWebServiceListRequest& request, const DescribeAssetWebServiceListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeAssetWebServiceListOutcomeCallable DescribeAssetWebServiceListCallable(const Model::DescribeAssetWebServiceListRequest& request); /** *查询所有检查项接口,返回总数和检查项列表 * @param req DescribeCheckItemListRequest * @return DescribeCheckItemListOutcome */ DescribeCheckItemListOutcome DescribeCheckItemList(const Model::DescribeCheckItemListRequest &request); void DescribeCheckItemListAsync(const Model::DescribeCheckItemListRequest& request, const DescribeCheckItemListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeCheckItemListOutcomeCallable DescribeCheckItemListCallable(const Model::DescribeCheckItemListRequest& request); /** *查询单个集群的详细信息 * @param req DescribeClusterDetailRequest * @return DescribeClusterDetailOutcome */ DescribeClusterDetailOutcome DescribeClusterDetail(const Model::DescribeClusterDetailRequest &request); void DescribeClusterDetailAsync(const Model::DescribeClusterDetailRequest& request, const DescribeClusterDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeClusterDetailOutcomeCallable DescribeClusterDetailCallable(const Model::DescribeClusterDetailRequest& request); /** *查询用户集群资产总览 * @param req DescribeClusterSummaryRequest * @return DescribeClusterSummaryOutcome */ DescribeClusterSummaryOutcome DescribeClusterSummary(const Model::DescribeClusterSummaryRequest &request); void DescribeClusterSummaryAsync(const Model::DescribeClusterSummaryRequest& request, const DescribeClusterSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeClusterSummaryOutcomeCallable DescribeClusterSummaryCallable(const Model::DescribeClusterSummaryRequest& request); /** *查询某个资产的详情 * @param req DescribeComplianceAssetDetailInfoRequest * @return DescribeComplianceAssetDetailInfoOutcome */ DescribeComplianceAssetDetailInfoOutcome DescribeComplianceAssetDetailInfo(const Model::DescribeComplianceAssetDetailInfoRequest &request); void DescribeComplianceAssetDetailInfoAsync(const Model::DescribeComplianceAssetDetailInfoRequest& request, const DescribeComplianceAssetDetailInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceAssetDetailInfoOutcomeCallable DescribeComplianceAssetDetailInfoCallable(const Model::DescribeComplianceAssetDetailInfoRequest& request); /** *查询某类资产的列表 * @param req DescribeComplianceAssetListRequest * @return DescribeComplianceAssetListOutcome */ DescribeComplianceAssetListOutcome DescribeComplianceAssetList(const Model::DescribeComplianceAssetListRequest &request); void DescribeComplianceAssetListAsync(const Model::DescribeComplianceAssetListRequest& request, const DescribeComplianceAssetListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceAssetListOutcomeCallable DescribeComplianceAssetListCallable(const Model::DescribeComplianceAssetListRequest& request); /** *查询某资产下的检测项列表 * @param req DescribeComplianceAssetPolicyItemListRequest * @return DescribeComplianceAssetPolicyItemListOutcome */ DescribeComplianceAssetPolicyItemListOutcome DescribeComplianceAssetPolicyItemList(const Model::DescribeComplianceAssetPolicyItemListRequest &request); void DescribeComplianceAssetPolicyItemListAsync(const Model::DescribeComplianceAssetPolicyItemListRequest& request, const DescribeComplianceAssetPolicyItemListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceAssetPolicyItemListOutcomeCallable DescribeComplianceAssetPolicyItemListCallable(const Model::DescribeComplianceAssetPolicyItemListRequest& request); /** *查询合规检测的定时任务列表 * @param req DescribeCompliancePeriodTaskListRequest * @return DescribeCompliancePeriodTaskListOutcome */ DescribeCompliancePeriodTaskListOutcome DescribeCompliancePeriodTaskList(const Model::DescribeCompliancePeriodTaskListRequest &request); void DescribeCompliancePeriodTaskListAsync(const Model::DescribeCompliancePeriodTaskListRequest& request, const DescribeCompliancePeriodTaskListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeCompliancePeriodTaskListOutcomeCallable DescribeCompliancePeriodTaskListCallable(const Model::DescribeCompliancePeriodTaskListRequest& request); /** *按照 检测项 → 资产 的两级层次展开的第二层级:资产层级。 * @param req DescribeCompliancePolicyItemAffectedAssetListRequest * @return DescribeCompliancePolicyItemAffectedAssetListOutcome */ DescribeCompliancePolicyItemAffectedAssetListOutcome DescribeCompliancePolicyItemAffectedAssetList(const Model::DescribeCompliancePolicyItemAffectedAssetListRequest &request); void DescribeCompliancePolicyItemAffectedAssetListAsync(const Model::DescribeCompliancePolicyItemAffectedAssetListRequest& request, const DescribeCompliancePolicyItemAffectedAssetListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeCompliancePolicyItemAffectedAssetListOutcomeCallable DescribeCompliancePolicyItemAffectedAssetListCallable(const Model::DescribeCompliancePolicyItemAffectedAssetListRequest& request); /** *按照 检测项 → 资产 的两级层次展开的第一层级:检测项层级。 * @param req DescribeCompliancePolicyItemAffectedSummaryRequest * @return DescribeCompliancePolicyItemAffectedSummaryOutcome */ DescribeCompliancePolicyItemAffectedSummaryOutcome DescribeCompliancePolicyItemAffectedSummary(const Model::DescribeCompliancePolicyItemAffectedSummaryRequest &request); void DescribeCompliancePolicyItemAffectedSummaryAsync(const Model::DescribeCompliancePolicyItemAffectedSummaryRequest& request, const DescribeCompliancePolicyItemAffectedSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeCompliancePolicyItemAffectedSummaryOutcomeCallable DescribeCompliancePolicyItemAffectedSummaryCallable(const Model::DescribeCompliancePolicyItemAffectedSummaryRequest& request); /** *按照 资产 → 检测项 二层结构展示的信息。这里查询第一层 资产的通过率汇总信息。 * @param req DescribeComplianceScanFailedAssetListRequest * @return DescribeComplianceScanFailedAssetListOutcome */ DescribeComplianceScanFailedAssetListOutcome DescribeComplianceScanFailedAssetList(const Model::DescribeComplianceScanFailedAssetListRequest &request); void DescribeComplianceScanFailedAssetListAsync(const Model::DescribeComplianceScanFailedAssetListRequest& request, const DescribeComplianceScanFailedAssetListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceScanFailedAssetListOutcomeCallable DescribeComplianceScanFailedAssetListCallable(const Model::DescribeComplianceScanFailedAssetListRequest& request); /** *查询上次任务的资产通过率汇总信息 * @param req DescribeComplianceTaskAssetSummaryRequest * @return DescribeComplianceTaskAssetSummaryOutcome */ DescribeComplianceTaskAssetSummaryOutcome DescribeComplianceTaskAssetSummary(const Model::DescribeComplianceTaskAssetSummaryRequest &request); void DescribeComplianceTaskAssetSummaryAsync(const Model::DescribeComplianceTaskAssetSummaryRequest& request, const DescribeComplianceTaskAssetSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceTaskAssetSummaryOutcomeCallable DescribeComplianceTaskAssetSummaryCallable(const Model::DescribeComplianceTaskAssetSummaryRequest& request); /** *查询最近一次任务发现的检测项的汇总信息列表,按照 检测项 → 资产 的两级层次展开。 * @param req DescribeComplianceTaskPolicyItemSummaryListRequest * @return DescribeComplianceTaskPolicyItemSummaryListOutcome */ DescribeComplianceTaskPolicyItemSummaryListOutcome DescribeComplianceTaskPolicyItemSummaryList(const Model::DescribeComplianceTaskPolicyItemSummaryListRequest &request); void DescribeComplianceTaskPolicyItemSummaryListAsync(const Model::DescribeComplianceTaskPolicyItemSummaryListRequest& request, const DescribeComplianceTaskPolicyItemSummaryListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceTaskPolicyItemSummaryListOutcomeCallable DescribeComplianceTaskPolicyItemSummaryListCallable(const Model::DescribeComplianceTaskPolicyItemSummaryListRequest& request); /** *查询白名单列表 * @param req DescribeComplianceWhitelistItemListRequest * @return DescribeComplianceWhitelistItemListOutcome */ DescribeComplianceWhitelistItemListOutcome DescribeComplianceWhitelistItemList(const Model::DescribeComplianceWhitelistItemListRequest &request); void DescribeComplianceWhitelistItemListAsync(const Model::DescribeComplianceWhitelistItemListRequest& request, const DescribeComplianceWhitelistItemListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeComplianceWhitelistItemListOutcomeCallable DescribeComplianceWhitelistItemListCallable(const Model::DescribeComplianceWhitelistItemListRequest& request); /** *查询容器资产概览信息 * @param req DescribeContainerAssetSummaryRequest * @return DescribeContainerAssetSummaryOutcome */ DescribeContainerAssetSummaryOutcome DescribeContainerAssetSummary(const Model::DescribeContainerAssetSummaryRequest &request); void DescribeContainerAssetSummaryAsync(const Model::DescribeContainerAssetSummaryRequest& request, const DescribeContainerAssetSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeContainerAssetSummaryOutcomeCallable DescribeContainerAssetSummaryCallable(const Model::DescribeContainerAssetSummaryRequest& request); /** *查询容器安全未处理事件信息 * @param req DescribeContainerSecEventSummaryRequest * @return DescribeContainerSecEventSummaryOutcome */ DescribeContainerSecEventSummaryOutcome DescribeContainerSecEventSummary(const Model::DescribeContainerSecEventSummaryRequest &request); void DescribeContainerSecEventSummaryAsync(const Model::DescribeContainerSecEventSummaryRequest& request, const DescribeContainerSecEventSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeContainerSecEventSummaryOutcomeCallable DescribeContainerSecEventSummaryCallable(const Model::DescribeContainerSecEventSummaryRequest& request); /** *DescribeEscapeEventDetail 查询容器逃逸事件详情 * @param req DescribeEscapeEventDetailRequest * @return DescribeEscapeEventDetailOutcome */ DescribeEscapeEventDetailOutcome DescribeEscapeEventDetail(const Model::DescribeEscapeEventDetailRequest &request); void DescribeEscapeEventDetailAsync(const Model::DescribeEscapeEventDetailRequest& request, const DescribeEscapeEventDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeEscapeEventDetailOutcomeCallable DescribeEscapeEventDetailCallable(const Model::DescribeEscapeEventDetailRequest& request); /** *DescribeEscapeEventInfo 查询容器逃逸事件列表 * @param req DescribeEscapeEventInfoRequest * @return DescribeEscapeEventInfoOutcome */ DescribeEscapeEventInfoOutcome DescribeEscapeEventInfo(const Model::DescribeEscapeEventInfoRequest &request); void DescribeEscapeEventInfoAsync(const Model::DescribeEscapeEventInfoRequest& request, const DescribeEscapeEventInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeEscapeEventInfoOutcomeCallable DescribeEscapeEventInfoCallable(const Model::DescribeEscapeEventInfoRequest& request); /** *DescribeEscapeEventsExport 查询容器逃逸事件列表导出 * @param req DescribeEscapeEventsExportRequest * @return DescribeEscapeEventsExportOutcome */ DescribeEscapeEventsExportOutcome DescribeEscapeEventsExport(const Model::DescribeEscapeEventsExportRequest &request); void DescribeEscapeEventsExportAsync(const Model::DescribeEscapeEventsExportRequest& request, const DescribeEscapeEventsExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeEscapeEventsExportOutcomeCallable DescribeEscapeEventsExportCallable(const Model::DescribeEscapeEventsExportRequest& request); /** *DescribeEscapeRuleInfo 查询容器逃逸扫描规则信息 * @param req DescribeEscapeRuleInfoRequest * @return DescribeEscapeRuleInfoOutcome */ DescribeEscapeRuleInfoOutcome DescribeEscapeRuleInfo(const Model::DescribeEscapeRuleInfoRequest &request); void DescribeEscapeRuleInfoAsync(const Model::DescribeEscapeRuleInfoRequest& request, const DescribeEscapeRuleInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeEscapeRuleInfoOutcomeCallable DescribeEscapeRuleInfoCallable(const Model::DescribeEscapeRuleInfoRequest& request); /** *DescribeEscapeSafeState 查询容器逃逸安全状态 * @param req DescribeEscapeSafeStateRequest * @return DescribeEscapeSafeStateOutcome */ DescribeEscapeSafeStateOutcome DescribeEscapeSafeState(const Model::DescribeEscapeSafeStateRequest &request); void DescribeEscapeSafeStateAsync(const Model::DescribeEscapeSafeStateRequest& request, const DescribeEscapeSafeStateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeEscapeSafeStateOutcomeCallable DescribeEscapeSafeStateCallable(const Model::DescribeEscapeSafeStateRequest& request); /** *查询导出任务的结果 * @param req DescribeExportJobResultRequest * @return DescribeExportJobResultOutcome */ DescribeExportJobResultOutcome DescribeExportJobResult(const Model::DescribeExportJobResultRequest &request); void DescribeExportJobResultAsync(const Model::DescribeExportJobResultRequest& request, const DescribeExportJobResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeExportJobResultOutcomeCallable DescribeExportJobResultCallable(const Model::DescribeExportJobResultRequest& request); /** *DescribeImageAuthorizedInfo 查询镜像授权信息 * @param req DescribeImageAuthorizedInfoRequest * @return DescribeImageAuthorizedInfoOutcome */ DescribeImageAuthorizedInfoOutcome DescribeImageAuthorizedInfo(const Model::DescribeImageAuthorizedInfoRequest &request); void DescribeImageAuthorizedInfoAsync(const Model::DescribeImageAuthorizedInfoRequest& request, const DescribeImageAuthorizedInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeImageAuthorizedInfoOutcomeCallable DescribeImageAuthorizedInfoCallable(const Model::DescribeImageAuthorizedInfoRequest& request); /** *镜像仓库查看定时任务 * @param req DescribeImageRegistryTimingScanTaskRequest * @return DescribeImageRegistryTimingScanTaskOutcome */ DescribeImageRegistryTimingScanTaskOutcome DescribeImageRegistryTimingScanTask(const Model::DescribeImageRegistryTimingScanTaskRequest &request); void DescribeImageRegistryTimingScanTaskAsync(const Model::DescribeImageRegistryTimingScanTaskRequest& request, const DescribeImageRegistryTimingScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeImageRegistryTimingScanTaskOutcomeCallable DescribeImageRegistryTimingScanTaskCallable(const Model::DescribeImageRegistryTimingScanTaskRequest& request); /** *查询本地镜像风险概览 * @param req DescribeImageRiskSummaryRequest * @return DescribeImageRiskSummaryOutcome */ DescribeImageRiskSummaryOutcome DescribeImageRiskSummary(const Model::DescribeImageRiskSummaryRequest &request); void DescribeImageRiskSummaryAsync(const Model::DescribeImageRiskSummaryRequest& request, const DescribeImageRiskSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeImageRiskSummaryOutcomeCallable DescribeImageRiskSummaryCallable(const Model::DescribeImageRiskSummaryRequest& request); /** *查询容器安全本地镜像风险趋势 * @param req DescribeImageRiskTendencyRequest * @return DescribeImageRiskTendencyOutcome */ DescribeImageRiskTendencyOutcome DescribeImageRiskTendency(const Model::DescribeImageRiskTendencyRequest &request); void DescribeImageRiskTendencyAsync(const Model::DescribeImageRiskTendencyRequest& request, const DescribeImageRiskTendencyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeImageRiskTendencyOutcomeCallable DescribeImageRiskTendencyCallable(const Model::DescribeImageRiskTendencyRequest& request); /** *DescribeImageSimpleList 查询全部镜像列表 * @param req DescribeImageSimpleListRequest * @return DescribeImageSimpleListOutcome */ DescribeImageSimpleListOutcome DescribeImageSimpleList(const Model::DescribeImageSimpleListRequest &request); void DescribeImageSimpleListAsync(const Model::DescribeImageSimpleListRequest& request, const DescribeImageSimpleListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeImageSimpleListOutcomeCallable DescribeImageSimpleListCallable(const Model::DescribeImageSimpleListRequest& request); /** *DescribePostPayDetail 查询后付费详情 * @param req DescribePostPayDetailRequest * @return DescribePostPayDetailOutcome */ DescribePostPayDetailOutcome DescribePostPayDetail(const Model::DescribePostPayDetailRequest &request); void DescribePostPayDetailAsync(const Model::DescribePostPayDetailRequest& request, const DescribePostPayDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribePostPayDetailOutcomeCallable DescribePostPayDetailCallable(const Model::DescribePostPayDetailRequest& request); /** *DescribeProVersionInfo 查询专业版需购买信息 * @param req DescribeProVersionInfoRequest * @return DescribeProVersionInfoOutcome */ DescribeProVersionInfoOutcome DescribeProVersionInfo(const Model::DescribeProVersionInfoRequest &request); void DescribeProVersionInfoAsync(const Model::DescribeProVersionInfoRequest& request, const DescribeProVersionInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeProVersionInfoOutcomeCallable DescribeProVersionInfoCallable(const Model::DescribeProVersionInfoRequest& request); /** *DescribePurchaseStateInfo 查询容器安全服务已购买信息 * @param req DescribePurchaseStateInfoRequest * @return DescribePurchaseStateInfoOutcome */ DescribePurchaseStateInfoOutcome DescribePurchaseStateInfo(const Model::DescribePurchaseStateInfoRequest &request); void DescribePurchaseStateInfoAsync(const Model::DescribePurchaseStateInfoRequest& request, const DescribePurchaseStateInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribePurchaseStateInfoOutcomeCallable DescribePurchaseStateInfoCallable(const Model::DescribePurchaseStateInfoRequest& request); /** *查询刷新任务 * @param req DescribeRefreshTaskRequest * @return DescribeRefreshTaskOutcome */ DescribeRefreshTaskOutcome DescribeRefreshTask(const Model::DescribeRefreshTaskRequest &request); void DescribeRefreshTaskAsync(const Model::DescribeRefreshTaskRequest& request, const DescribeRefreshTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRefreshTaskOutcomeCallable DescribeRefreshTaskCallable(const Model::DescribeRefreshTaskRequest& request); /** *查询运行时反弹shell事件详细信息 * @param req DescribeReverseShellDetailRequest * @return DescribeReverseShellDetailOutcome */ DescribeReverseShellDetailOutcome DescribeReverseShellDetail(const Model::DescribeReverseShellDetailRequest &request); void DescribeReverseShellDetailAsync(const Model::DescribeReverseShellDetailRequest& request, const DescribeReverseShellDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeReverseShellDetailOutcomeCallable DescribeReverseShellDetailCallable(const Model::DescribeReverseShellDetailRequest& request); /** *查询运行时反弹shell事件列表信息 * @param req DescribeReverseShellEventsRequest * @return DescribeReverseShellEventsOutcome */ DescribeReverseShellEventsOutcome DescribeReverseShellEvents(const Model::DescribeReverseShellEventsRequest &request); void DescribeReverseShellEventsAsync(const Model::DescribeReverseShellEventsRequest& request, const DescribeReverseShellEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeReverseShellEventsOutcomeCallable DescribeReverseShellEventsCallable(const Model::DescribeReverseShellEventsRequest& request); /** *查询运行时反弹shell事件列表信息导出 * @param req DescribeReverseShellEventsExportRequest * @return DescribeReverseShellEventsExportOutcome */ DescribeReverseShellEventsExportOutcome DescribeReverseShellEventsExport(const Model::DescribeReverseShellEventsExportRequest &request); void DescribeReverseShellEventsExportAsync(const Model::DescribeReverseShellEventsExportRequest& request, const DescribeReverseShellEventsExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeReverseShellEventsExportOutcomeCallable DescribeReverseShellEventsExportCallable(const Model::DescribeReverseShellEventsExportRequest& request); /** *查询运行时反弹shell白名单详细信息 * @param req DescribeReverseShellWhiteListDetailRequest * @return DescribeReverseShellWhiteListDetailOutcome */ DescribeReverseShellWhiteListDetailOutcome DescribeReverseShellWhiteListDetail(const Model::DescribeReverseShellWhiteListDetailRequest &request); void DescribeReverseShellWhiteListDetailAsync(const Model::DescribeReverseShellWhiteListDetailRequest& request, const DescribeReverseShellWhiteListDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeReverseShellWhiteListDetailOutcomeCallable DescribeReverseShellWhiteListDetailCallable(const Model::DescribeReverseShellWhiteListDetailRequest& request); /** *查询运行时运行时反弹shell白名单列表信息 * @param req DescribeReverseShellWhiteListsRequest * @return DescribeReverseShellWhiteListsOutcome */ DescribeReverseShellWhiteListsOutcome DescribeReverseShellWhiteLists(const Model::DescribeReverseShellWhiteListsRequest &request); void DescribeReverseShellWhiteListsAsync(const Model::DescribeReverseShellWhiteListsRequest& request, const DescribeReverseShellWhiteListsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeReverseShellWhiteListsOutcomeCallable DescribeReverseShellWhiteListsCallable(const Model::DescribeReverseShellWhiteListsRequest& request); /** *查询最近一次任务发现的风险项的信息列表,支持根据特殊字段进行过滤 * @param req DescribeRiskListRequest * @return DescribeRiskListOutcome */ DescribeRiskListOutcome DescribeRiskList(const Model::DescribeRiskListRequest &request); void DescribeRiskListAsync(const Model::DescribeRiskListRequest& request, const DescribeRiskListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskListOutcomeCallable DescribeRiskListCallable(const Model::DescribeRiskListRequest& request); /** *查询高危系统调用事件详细信息 * @param req DescribeRiskSyscallDetailRequest * @return DescribeRiskSyscallDetailOutcome */ DescribeRiskSyscallDetailOutcome DescribeRiskSyscallDetail(const Model::DescribeRiskSyscallDetailRequest &request); void DescribeRiskSyscallDetailAsync(const Model::DescribeRiskSyscallDetailRequest& request, const DescribeRiskSyscallDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallDetailOutcomeCallable DescribeRiskSyscallDetailCallable(const Model::DescribeRiskSyscallDetailRequest& request); /** *查询运行时运行时高危系统调用列表信息 * @param req DescribeRiskSyscallEventsRequest * @return DescribeRiskSyscallEventsOutcome */ DescribeRiskSyscallEventsOutcome DescribeRiskSyscallEvents(const Model::DescribeRiskSyscallEventsRequest &request); void DescribeRiskSyscallEventsAsync(const Model::DescribeRiskSyscallEventsRequest& request, const DescribeRiskSyscallEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallEventsOutcomeCallable DescribeRiskSyscallEventsCallable(const Model::DescribeRiskSyscallEventsRequest& request); /** *运行时高危系统调用列表导出 * @param req DescribeRiskSyscallEventsExportRequest * @return DescribeRiskSyscallEventsExportOutcome */ DescribeRiskSyscallEventsExportOutcome DescribeRiskSyscallEventsExport(const Model::DescribeRiskSyscallEventsExportRequest &request); void DescribeRiskSyscallEventsExportAsync(const Model::DescribeRiskSyscallEventsExportRequest& request, const DescribeRiskSyscallEventsExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallEventsExportOutcomeCallable DescribeRiskSyscallEventsExportCallable(const Model::DescribeRiskSyscallEventsExportRequest& request); /** *查询运行时高危系统调用系统名称列表 * @param req DescribeRiskSyscallNamesRequest * @return DescribeRiskSyscallNamesOutcome */ DescribeRiskSyscallNamesOutcome DescribeRiskSyscallNames(const Model::DescribeRiskSyscallNamesRequest &request); void DescribeRiskSyscallNamesAsync(const Model::DescribeRiskSyscallNamesRequest& request, const DescribeRiskSyscallNamesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallNamesOutcomeCallable DescribeRiskSyscallNamesCallable(const Model::DescribeRiskSyscallNamesRequest& request); /** *查询运行时高危系统调用白名单详细信息 * @param req DescribeRiskSyscallWhiteListDetailRequest * @return DescribeRiskSyscallWhiteListDetailOutcome */ DescribeRiskSyscallWhiteListDetailOutcome DescribeRiskSyscallWhiteListDetail(const Model::DescribeRiskSyscallWhiteListDetailRequest &request); void DescribeRiskSyscallWhiteListDetailAsync(const Model::DescribeRiskSyscallWhiteListDetailRequest& request, const DescribeRiskSyscallWhiteListDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallWhiteListDetailOutcomeCallable DescribeRiskSyscallWhiteListDetailCallable(const Model::DescribeRiskSyscallWhiteListDetailRequest& request); /** *查询运行时高危系统调用白名单列表信息 * @param req DescribeRiskSyscallWhiteListsRequest * @return DescribeRiskSyscallWhiteListsOutcome */ DescribeRiskSyscallWhiteListsOutcome DescribeRiskSyscallWhiteLists(const Model::DescribeRiskSyscallWhiteListsRequest &request); void DescribeRiskSyscallWhiteListsAsync(const Model::DescribeRiskSyscallWhiteListsRequest& request, const DescribeRiskSyscallWhiteListsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeRiskSyscallWhiteListsOutcomeCallable DescribeRiskSyscallWhiteListsCallable(const Model::DescribeRiskSyscallWhiteListsRequest& request); /** *查询容器运行时安全事件趋势 * @param req DescribeSecEventsTendencyRequest * @return DescribeSecEventsTendencyOutcome */ DescribeSecEventsTendencyOutcome DescribeSecEventsTendency(const Model::DescribeSecEventsTendencyRequest &request); void DescribeSecEventsTendencyAsync(const Model::DescribeSecEventsTendencyRequest& request, const DescribeSecEventsTendencyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeSecEventsTendencyOutcomeCallable DescribeSecEventsTendencyCallable(const Model::DescribeSecEventsTendencyRequest& request); /** *查询检查结果总览,返回受影响的节点数量,返回7天的数据,总共7个 * @param req DescribeTaskResultSummaryRequest * @return DescribeTaskResultSummaryOutcome */ DescribeTaskResultSummaryOutcome DescribeTaskResultSummary(const Model::DescribeTaskResultSummaryRequest &request); void DescribeTaskResultSummaryAsync(const Model::DescribeTaskResultSummaryRequest& request, const DescribeTaskResultSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeTaskResultSummaryOutcomeCallable DescribeTaskResultSummaryCallable(const Model::DescribeTaskResultSummaryRequest& request); /** *查询未完成的刷新资产任务信息 * @param req DescribeUnfinishRefreshTaskRequest * @return DescribeUnfinishRefreshTaskOutcome */ DescribeUnfinishRefreshTaskOutcome DescribeUnfinishRefreshTask(const Model::DescribeUnfinishRefreshTaskRequest &request); void DescribeUnfinishRefreshTaskAsync(const Model::DescribeUnfinishRefreshTaskRequest& request, const DescribeUnfinishRefreshTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeUnfinishRefreshTaskOutcomeCallable DescribeUnfinishRefreshTaskCallable(const Model::DescribeUnfinishRefreshTaskRequest& request); /** *安全概览和集群安全页进入调用该接口,查询用户集群相关信息。 * @param req DescribeUserClusterRequest * @return DescribeUserClusterOutcome */ DescribeUserClusterOutcome DescribeUserCluster(const Model::DescribeUserClusterRequest &request); void DescribeUserClusterAsync(const Model::DescribeUserClusterRequest& request, const DescribeUserClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeUserClusterOutcomeCallable DescribeUserClusterCallable(const Model::DescribeUserClusterRequest& request); /** *DescribeValueAddedSrvInfo查询增值服务需购买信息 * @param req DescribeValueAddedSrvInfoRequest * @return DescribeValueAddedSrvInfoOutcome */ DescribeValueAddedSrvInfoOutcome DescribeValueAddedSrvInfo(const Model::DescribeValueAddedSrvInfoRequest &request); void DescribeValueAddedSrvInfoAsync(const Model::DescribeValueAddedSrvInfoRequest& request, const DescribeValueAddedSrvInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeValueAddedSrvInfoOutcomeCallable DescribeValueAddedSrvInfoCallable(const Model::DescribeValueAddedSrvInfoRequest& request); /** *运行时查询木马文件信息 * @param req DescribeVirusDetailRequest * @return DescribeVirusDetailOutcome */ DescribeVirusDetailOutcome DescribeVirusDetail(const Model::DescribeVirusDetailRequest &request); void DescribeVirusDetailAsync(const Model::DescribeVirusDetailRequest& request, const DescribeVirusDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusDetailOutcomeCallable DescribeVirusDetailCallable(const Model::DescribeVirusDetailRequest& request); /** *运行时文件查杀事件列表 * @param req DescribeVirusListRequest * @return DescribeVirusListOutcome */ DescribeVirusListOutcome DescribeVirusList(const Model::DescribeVirusListRequest &request); void DescribeVirusListAsync(const Model::DescribeVirusListRequest& request, const DescribeVirusListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusListOutcomeCallable DescribeVirusListCallable(const Model::DescribeVirusListRequest& request); /** *运行时查询文件查杀实时监控设置 * @param req DescribeVirusMonitorSettingRequest * @return DescribeVirusMonitorSettingOutcome */ DescribeVirusMonitorSettingOutcome DescribeVirusMonitorSetting(const Model::DescribeVirusMonitorSettingRequest &request); void DescribeVirusMonitorSettingAsync(const Model::DescribeVirusMonitorSettingRequest& request, const DescribeVirusMonitorSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusMonitorSettingOutcomeCallable DescribeVirusMonitorSettingCallable(const Model::DescribeVirusMonitorSettingRequest& request); /** *运行时查询文件查杀设置 * @param req DescribeVirusScanSettingRequest * @return DescribeVirusScanSettingOutcome */ DescribeVirusScanSettingOutcome DescribeVirusScanSetting(const Model::DescribeVirusScanSettingRequest &request); void DescribeVirusScanSettingAsync(const Model::DescribeVirusScanSettingRequest& request, const DescribeVirusScanSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusScanSettingOutcomeCallable DescribeVirusScanSettingCallable(const Model::DescribeVirusScanSettingRequest& request); /** *运行时查询文件查杀任务状态 * @param req DescribeVirusScanTaskStatusRequest * @return DescribeVirusScanTaskStatusOutcome */ DescribeVirusScanTaskStatusOutcome DescribeVirusScanTaskStatus(const Model::DescribeVirusScanTaskStatusRequest &request); void DescribeVirusScanTaskStatusAsync(const Model::DescribeVirusScanTaskStatusRequest& request, const DescribeVirusScanTaskStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusScanTaskStatusOutcomeCallable DescribeVirusScanTaskStatusCallable(const Model::DescribeVirusScanTaskStatusRequest& request); /** *运行时文件扫描超时设置查询 * @param req DescribeVirusScanTimeoutSettingRequest * @return DescribeVirusScanTimeoutSettingOutcome */ DescribeVirusScanTimeoutSettingOutcome DescribeVirusScanTimeoutSetting(const Model::DescribeVirusScanTimeoutSettingRequest &request); void DescribeVirusScanTimeoutSettingAsync(const Model::DescribeVirusScanTimeoutSettingRequest& request, const DescribeVirusScanTimeoutSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusScanTimeoutSettingOutcomeCallable DescribeVirusScanTimeoutSettingCallable(const Model::DescribeVirusScanTimeoutSettingRequest& request); /** *运行时查询木马概览信息 * @param req DescribeVirusSummaryRequest * @return DescribeVirusSummaryOutcome */ DescribeVirusSummaryOutcome DescribeVirusSummary(const Model::DescribeVirusSummaryRequest &request); void DescribeVirusSummaryAsync(const Model::DescribeVirusSummaryRequest& request, const DescribeVirusSummaryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusSummaryOutcomeCallable DescribeVirusSummaryCallable(const Model::DescribeVirusSummaryRequest& request); /** *运行时查询文件查杀任务列表 * @param req DescribeVirusTaskListRequest * @return DescribeVirusTaskListOutcome */ DescribeVirusTaskListOutcome DescribeVirusTaskList(const Model::DescribeVirusTaskListRequest &request); void DescribeVirusTaskListAsync(const Model::DescribeVirusTaskListRequest& request, const DescribeVirusTaskListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeVirusTaskListOutcomeCallable DescribeVirusTaskListCallable(const Model::DescribeVirusTaskListRequest& request); /** *获取告警策略列表 * @param req DescribeWarningRulesRequest * @return DescribeWarningRulesOutcome */ DescribeWarningRulesOutcome DescribeWarningRules(const Model::DescribeWarningRulesRequest &request); void DescribeWarningRulesAsync(const Model::DescribeWarningRulesRequest& request, const DescribeWarningRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); DescribeWarningRulesOutcomeCallable DescribeWarningRulesCallable(const Model::DescribeWarningRulesRequest& request); /** *运行时文件查杀事件列表导出 * @param req ExportVirusListRequest * @return ExportVirusListOutcome */ ExportVirusListOutcome ExportVirusList(const Model::ExportVirusListRequest &request); void ExportVirusListAsync(const Model::ExportVirusListRequest& request, const ExportVirusListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ExportVirusListOutcomeCallable ExportVirusListCallable(const Model::ExportVirusListRequest& request); /** *为客户初始化合规基线的使用环境,创建必要的数据和选项。 * @param req InitializeUserComplianceEnvironmentRequest * @return InitializeUserComplianceEnvironmentOutcome */ InitializeUserComplianceEnvironmentOutcome InitializeUserComplianceEnvironment(const Model::InitializeUserComplianceEnvironmentRequest &request); void InitializeUserComplianceEnvironmentAsync(const Model::InitializeUserComplianceEnvironmentRequest& request, const InitializeUserComplianceEnvironmentAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); InitializeUserComplianceEnvironmentOutcomeCallable InitializeUserComplianceEnvironmentCallable(const Model::InitializeUserComplianceEnvironmentRequest& request); /** *修改运行时异常进程策略的开启关闭状态 * @param req ModifyAbnormalProcessRuleStatusRequest * @return ModifyAbnormalProcessRuleStatusOutcome */ ModifyAbnormalProcessRuleStatusOutcome ModifyAbnormalProcessRuleStatus(const Model::ModifyAbnormalProcessRuleStatusRequest &request); void ModifyAbnormalProcessRuleStatusAsync(const Model::ModifyAbnormalProcessRuleStatusRequest& request, const ModifyAbnormalProcessRuleStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAbnormalProcessRuleStatusOutcomeCallable ModifyAbnormalProcessRuleStatusCallable(const Model::ModifyAbnormalProcessRuleStatusRequest& request); /** *修改异常进程事件的状态信息 * @param req ModifyAbnormalProcessStatusRequest * @return ModifyAbnormalProcessStatusOutcome */ ModifyAbnormalProcessStatusOutcome ModifyAbnormalProcessStatus(const Model::ModifyAbnormalProcessStatusRequest &request); void ModifyAbnormalProcessStatusAsync(const Model::ModifyAbnormalProcessStatusRequest& request, const ModifyAbnormalProcessStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAbnormalProcessStatusOutcomeCallable ModifyAbnormalProcessStatusCallable(const Model::ModifyAbnormalProcessStatusRequest& request); /** *修改运行时访问控制策略的状态,启用或者禁用 * @param req ModifyAccessControlRuleStatusRequest * @return ModifyAccessControlRuleStatusOutcome */ ModifyAccessControlRuleStatusOutcome ModifyAccessControlRuleStatus(const Model::ModifyAccessControlRuleStatusRequest &request); void ModifyAccessControlRuleStatusAsync(const Model::ModifyAccessControlRuleStatusRequest& request, const ModifyAccessControlRuleStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAccessControlRuleStatusOutcomeCallable ModifyAccessControlRuleStatusCallable(const Model::ModifyAccessControlRuleStatusRequest& request); /** *修改运行时访问控制事件状态信息 * @param req ModifyAccessControlStatusRequest * @return ModifyAccessControlStatusOutcome */ ModifyAccessControlStatusOutcome ModifyAccessControlStatus(const Model::ModifyAccessControlStatusRequest &request); void ModifyAccessControlStatusAsync(const Model::ModifyAccessControlStatusRequest& request, const ModifyAccessControlStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAccessControlStatusOutcomeCallable ModifyAccessControlStatusCallable(const Model::ModifyAccessControlStatusRequest& request); /** *容器安全主机资产刷新 * @param req ModifyAssetRequest * @return ModifyAssetOutcome */ ModifyAssetOutcome ModifyAsset(const Model::ModifyAssetRequest &request); void ModifyAssetAsync(const Model::ModifyAssetRequest& request, const ModifyAssetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAssetOutcomeCallable ModifyAssetCallable(const Model::ModifyAssetRequest& request); /** *镜像仓库停止镜像扫描任务 * @param req ModifyAssetImageRegistryScanStopRequest * @return ModifyAssetImageRegistryScanStopOutcome */ ModifyAssetImageRegistryScanStopOutcome ModifyAssetImageRegistryScanStop(const Model::ModifyAssetImageRegistryScanStopRequest &request); void ModifyAssetImageRegistryScanStopAsync(const Model::ModifyAssetImageRegistryScanStopRequest& request, const ModifyAssetImageRegistryScanStopAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAssetImageRegistryScanStopOutcomeCallable ModifyAssetImageRegistryScanStopCallable(const Model::ModifyAssetImageRegistryScanStopRequest& request); /** *镜像仓库停止镜像一键扫描任务 * @param req ModifyAssetImageRegistryScanStopOneKeyRequest * @return ModifyAssetImageRegistryScanStopOneKeyOutcome */ ModifyAssetImageRegistryScanStopOneKeyOutcome ModifyAssetImageRegistryScanStopOneKey(const Model::ModifyAssetImageRegistryScanStopOneKeyRequest &request); void ModifyAssetImageRegistryScanStopOneKeyAsync(const Model::ModifyAssetImageRegistryScanStopOneKeyRequest& request, const ModifyAssetImageRegistryScanStopOneKeyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAssetImageRegistryScanStopOneKeyOutcomeCallable ModifyAssetImageRegistryScanStopOneKeyCallable(const Model::ModifyAssetImageRegistryScanStopOneKeyRequest& request); /** *容器安全停止镜像扫描 * @param req ModifyAssetImageScanStopRequest * @return ModifyAssetImageScanStopOutcome */ ModifyAssetImageScanStopOutcome ModifyAssetImageScanStop(const Model::ModifyAssetImageScanStopRequest &request); void ModifyAssetImageScanStopAsync(const Model::ModifyAssetImageScanStopRequest& request, const ModifyAssetImageScanStopAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyAssetImageScanStopOutcomeCallable ModifyAssetImageScanStopCallable(const Model::ModifyAssetImageScanStopRequest& request); /** *修改定时任务的设置,包括检测周期、开启/禁用合规基准。 * @param req ModifyCompliancePeriodTaskRequest * @return ModifyCompliancePeriodTaskOutcome */ ModifyCompliancePeriodTaskOutcome ModifyCompliancePeriodTask(const Model::ModifyCompliancePeriodTaskRequest &request); void ModifyCompliancePeriodTaskAsync(const Model::ModifyCompliancePeriodTaskRequest& request, const ModifyCompliancePeriodTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyCompliancePeriodTaskOutcomeCallable ModifyCompliancePeriodTaskCallable(const Model::ModifyCompliancePeriodTaskRequest& request); /** *ModifyEscapeEventStatus 修改容器逃逸扫描事件状态 * @param req ModifyEscapeEventStatusRequest * @return ModifyEscapeEventStatusOutcome */ ModifyEscapeEventStatusOutcome ModifyEscapeEventStatus(const Model::ModifyEscapeEventStatusRequest &request); void ModifyEscapeEventStatusAsync(const Model::ModifyEscapeEventStatusRequest& request, const ModifyEscapeEventStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyEscapeEventStatusOutcomeCallable ModifyEscapeEventStatusCallable(const Model::ModifyEscapeEventStatusRequest& request); /** *ModifyEscapeRule 修改容器逃逸扫描规则信息 * @param req ModifyEscapeRuleRequest * @return ModifyEscapeRuleOutcome */ ModifyEscapeRuleOutcome ModifyEscapeRule(const Model::ModifyEscapeRuleRequest &request); void ModifyEscapeRuleAsync(const Model::ModifyEscapeRuleRequest& request, const ModifyEscapeRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyEscapeRuleOutcomeCallable ModifyEscapeRuleCallable(const Model::ModifyEscapeRuleRequest& request); /** *修改反弹shell事件的状态信息 * @param req ModifyReverseShellStatusRequest * @return ModifyReverseShellStatusOutcome */ ModifyReverseShellStatusOutcome ModifyReverseShellStatus(const Model::ModifyReverseShellStatusRequest &request); void ModifyReverseShellStatusAsync(const Model::ModifyReverseShellStatusRequest& request, const ModifyReverseShellStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyReverseShellStatusOutcomeCallable ModifyReverseShellStatusCallable(const Model::ModifyReverseShellStatusRequest& request); /** *修改高危系统调用事件的状态信息 * @param req ModifyRiskSyscallStatusRequest * @return ModifyRiskSyscallStatusOutcome */ ModifyRiskSyscallStatusOutcome ModifyRiskSyscallStatus(const Model::ModifyRiskSyscallStatusRequest &request); void ModifyRiskSyscallStatusAsync(const Model::ModifyRiskSyscallStatusRequest& request, const ModifyRiskSyscallStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyRiskSyscallStatusOutcomeCallable ModifyRiskSyscallStatusCallable(const Model::ModifyRiskSyscallStatusRequest& request); /** *运行时更新木马文件事件状态 * @param req ModifyVirusFileStatusRequest * @return ModifyVirusFileStatusOutcome */ ModifyVirusFileStatusOutcome ModifyVirusFileStatus(const Model::ModifyVirusFileStatusRequest &request); void ModifyVirusFileStatusAsync(const Model::ModifyVirusFileStatusRequest& request, const ModifyVirusFileStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyVirusFileStatusOutcomeCallable ModifyVirusFileStatusCallable(const Model::ModifyVirusFileStatusRequest& request); /** *运行时更新文件查杀实时监控设置 * @param req ModifyVirusMonitorSettingRequest * @return ModifyVirusMonitorSettingOutcome */ ModifyVirusMonitorSettingOutcome ModifyVirusMonitorSetting(const Model::ModifyVirusMonitorSettingRequest &request); void ModifyVirusMonitorSettingAsync(const Model::ModifyVirusMonitorSettingRequest& request, const ModifyVirusMonitorSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyVirusMonitorSettingOutcomeCallable ModifyVirusMonitorSettingCallable(const Model::ModifyVirusMonitorSettingRequest& request); /** *运行时更新文件查杀设置 * @param req ModifyVirusScanSettingRequest * @return ModifyVirusScanSettingOutcome */ ModifyVirusScanSettingOutcome ModifyVirusScanSetting(const Model::ModifyVirusScanSettingRequest &request); void ModifyVirusScanSettingAsync(const Model::ModifyVirusScanSettingRequest& request, const ModifyVirusScanSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyVirusScanSettingOutcomeCallable ModifyVirusScanSettingCallable(const Model::ModifyVirusScanSettingRequest& request); /** *运行时文件扫描超时设置 * @param req ModifyVirusScanTimeoutSettingRequest * @return ModifyVirusScanTimeoutSettingOutcome */ ModifyVirusScanTimeoutSettingOutcome ModifyVirusScanTimeoutSetting(const Model::ModifyVirusScanTimeoutSettingRequest &request); void ModifyVirusScanTimeoutSettingAsync(const Model::ModifyVirusScanTimeoutSettingRequest& request, const ModifyVirusScanTimeoutSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ModifyVirusScanTimeoutSettingOutcomeCallable ModifyVirusScanTimeoutSettingCallable(const Model::ModifyVirusScanTimeoutSettingRequest& request); /** *删除单个镜像仓库详细信息 * @param req RemoveAssetImageRegistryRegistryDetailRequest * @return RemoveAssetImageRegistryRegistryDetailOutcome */ RemoveAssetImageRegistryRegistryDetailOutcome RemoveAssetImageRegistryRegistryDetail(const Model::RemoveAssetImageRegistryRegistryDetailRequest &request); void RemoveAssetImageRegistryRegistryDetailAsync(const Model::RemoveAssetImageRegistryRegistryDetailRequest& request, const RemoveAssetImageRegistryRegistryDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); RemoveAssetImageRegistryRegistryDetailOutcomeCallable RemoveAssetImageRegistryRegistryDetailCallable(const Model::RemoveAssetImageRegistryRegistryDetailRequest& request); /** *RenewImageAuthorizeState 授权镜像扫描 * @param req RenewImageAuthorizeStateRequest * @return RenewImageAuthorizeStateOutcome */ RenewImageAuthorizeStateOutcome RenewImageAuthorizeState(const Model::RenewImageAuthorizeStateRequest &request); void RenewImageAuthorizeStateAsync(const Model::RenewImageAuthorizeStateRequest& request, const RenewImageAuthorizeStateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); RenewImageAuthorizeStateOutcomeCallable RenewImageAuthorizeStateCallable(const Model::RenewImageAuthorizeStateRequest& request); /** *重新检测选定的资产 * @param req ScanComplianceAssetsRequest * @return ScanComplianceAssetsOutcome */ ScanComplianceAssetsOutcome ScanComplianceAssets(const Model::ScanComplianceAssetsRequest &request); void ScanComplianceAssetsAsync(const Model::ScanComplianceAssetsRequest& request, const ScanComplianceAssetsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ScanComplianceAssetsOutcomeCallable ScanComplianceAssetsCallable(const Model::ScanComplianceAssetsRequest& request); /** *用指定的检测项重新检测选定的资产,返回创建的合规检查任务的ID。 * @param req ScanComplianceAssetsByPolicyItemRequest * @return ScanComplianceAssetsByPolicyItemOutcome */ ScanComplianceAssetsByPolicyItemOutcome ScanComplianceAssetsByPolicyItem(const Model::ScanComplianceAssetsByPolicyItemRequest &request); void ScanComplianceAssetsByPolicyItemAsync(const Model::ScanComplianceAssetsByPolicyItemRequest& request, const ScanComplianceAssetsByPolicyItemAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ScanComplianceAssetsByPolicyItemOutcomeCallable ScanComplianceAssetsByPolicyItemCallable(const Model::ScanComplianceAssetsByPolicyItemRequest& request); /** *重新检测选的检测项下的所有资产,返回创建的合规检查任务的ID。 * @param req ScanCompliancePolicyItemsRequest * @return ScanCompliancePolicyItemsOutcome */ ScanCompliancePolicyItemsOutcome ScanCompliancePolicyItems(const Model::ScanCompliancePolicyItemsRequest &request); void ScanCompliancePolicyItemsAsync(const Model::ScanCompliancePolicyItemsRequest& request, const ScanCompliancePolicyItemsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ScanCompliancePolicyItemsOutcomeCallable ScanCompliancePolicyItemsCallable(const Model::ScanCompliancePolicyItemsRequest& request); /** *重新检测选定的检测失败的资产下的所有失败的检测项,返回创建的合规检查任务的ID。 * @param req ScanComplianceScanFailedAssetsRequest * @return ScanComplianceScanFailedAssetsOutcome */ ScanComplianceScanFailedAssetsOutcome ScanComplianceScanFailedAssets(const Model::ScanComplianceScanFailedAssetsRequest &request); void ScanComplianceScanFailedAssetsAsync(const Model::ScanComplianceScanFailedAssetsRequest& request, const ScanComplianceScanFailedAssetsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); ScanComplianceScanFailedAssetsOutcomeCallable ScanComplianceScanFailedAssetsCallable(const Model::ScanComplianceScanFailedAssetsRequest& request); /** *设置检测模式和自动检查 * @param req SetCheckModeRequest * @return SetCheckModeOutcome */ SetCheckModeOutcome SetCheckMode(const Model::SetCheckModeRequest &request); void SetCheckModeAsync(const Model::SetCheckModeRequest& request, const SetCheckModeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); SetCheckModeOutcomeCallable SetCheckModeCallable(const Model::SetCheckModeRequest& request); /** *运行时停止木马查杀任务 * @param req StopVirusScanTaskRequest * @return StopVirusScanTaskOutcome */ StopVirusScanTaskOutcome StopVirusScanTask(const Model::StopVirusScanTaskRequest &request); void StopVirusScanTaskAsync(const Model::StopVirusScanTaskRequest& request, const StopVirusScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); StopVirusScanTaskOutcomeCallable StopVirusScanTaskCallable(const Model::StopVirusScanTaskRequest& request); /** *镜像仓库资产刷新 * @param req SyncAssetImageRegistryAssetRequest * @return SyncAssetImageRegistryAssetOutcome */ SyncAssetImageRegistryAssetOutcome SyncAssetImageRegistryAsset(const Model::SyncAssetImageRegistryAssetRequest &request); void SyncAssetImageRegistryAssetAsync(const Model::SyncAssetImageRegistryAssetRequest& request, const SyncAssetImageRegistryAssetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); SyncAssetImageRegistryAssetOutcomeCallable SyncAssetImageRegistryAssetCallable(const Model::SyncAssetImageRegistryAssetRequest& request); /** *更新单个镜像仓库详细信息 * @param req UpdateAssetImageRegistryRegistryDetailRequest * @return UpdateAssetImageRegistryRegistryDetailOutcome */ UpdateAssetImageRegistryRegistryDetailOutcome UpdateAssetImageRegistryRegistryDetail(const Model::UpdateAssetImageRegistryRegistryDetailRequest &request); void UpdateAssetImageRegistryRegistryDetailAsync(const Model::UpdateAssetImageRegistryRegistryDetailRequest& request, const UpdateAssetImageRegistryRegistryDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); UpdateAssetImageRegistryRegistryDetailOutcomeCallable UpdateAssetImageRegistryRegistryDetailCallable(const Model::UpdateAssetImageRegistryRegistryDetailRequest& request); /** *镜像仓库更新定时任务 * @param req UpdateImageRegistryTimingScanTaskRequest * @return UpdateImageRegistryTimingScanTaskOutcome */ UpdateImageRegistryTimingScanTaskOutcome UpdateImageRegistryTimingScanTask(const Model::UpdateImageRegistryTimingScanTaskRequest &request); void UpdateImageRegistryTimingScanTaskAsync(const Model::UpdateImageRegistryTimingScanTaskRequest& request, const UpdateImageRegistryTimingScanTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr); UpdateImageRegistryTimingScanTaskOutcomeCallable UpdateImageRegistryTimingScanTaskCallable(const Model::UpdateImageRegistryTimingScanTaskRequest& request); }; } } } #endif // !TENCENTCLOUD_TCSS_V20201101_TCSSCLIENT_H_
98.010957
293
0.770883
[ "model" ]
f013e0a392c4eb89ea641596f7eda30ba3d2232a
34,205
c
C
signal.c
Omegaphora/external_strace
a2adbed6e2d3ce85ebb167e16ae370681a8b5188
[ "BSD-3-Clause" ]
null
null
null
signal.c
Omegaphora/external_strace
a2adbed6e2d3ce85ebb167e16ae370681a8b5188
[ "BSD-3-Clause" ]
null
null
null
signal.c
Omegaphora/external_strace
a2adbed6e2d3ce85ebb167e16ae370681a8b5188
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl> * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl> * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com> * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl> * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation * Linux for s390 port by D.J. Barrow * <barrow_dj@mail.yahoo.com,djbarrow@de.ibm.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "defs.h" #include <sys/user.h> #include <fcntl.h> #ifdef HAVE_SYS_REG_H # include <sys/reg.h> #elif defined(HAVE_LINUX_PTRACE_H) # undef PTRACE_SYSCALL # ifdef HAVE_STRUCT_IA64_FPREG # define ia64_fpreg XXX_ia64_fpreg # endif # ifdef HAVE_STRUCT_PT_ALL_USER_REGS # define pt_all_user_regs XXX_pt_all_user_regs # endif # ifdef HAVE_STRUCT_PTRACE_PEEKSIGINFO_ARGS # define ptrace_peeksiginfo_args XXX_ptrace_peeksiginfo_args # endif # include <linux/ptrace.h> # undef ptrace_peeksiginfo_args # undef ia64_fpreg # undef pt_all_user_regs #endif #ifdef IA64 # include <asm/ptrace_offsets.h> #endif #if defined(SPARC) || defined(SPARC64) || defined(MIPS) typedef struct { struct pt_regs si_regs; int si_mask; } m_siginfo_t; #elif defined HAVE_ASM_SIGCONTEXT_H # if !defined(IA64) && !defined(X86_64) && !defined(X32) # include <asm/sigcontext.h> # endif #else /* !HAVE_ASM_SIGCONTEXT_H */ # if defined M68K && !defined HAVE_STRUCT_SIGCONTEXT struct sigcontext { unsigned long sc_mask; unsigned long sc_usp; unsigned long sc_d0; unsigned long sc_d1; unsigned long sc_a0; unsigned long sc_a1; unsigned short sc_sr; unsigned long sc_pc; unsigned short sc_formatvec; }; # endif /* M68K */ #endif /* !HAVE_ASM_SIGCONTEXT_H */ #ifndef NSIG # warning: NSIG is not defined, using 32 # define NSIG 32 #elif NSIG < 32 # error: NSIG < 32 #endif #ifdef HAVE_SIGACTION /* The libc headers do not define this constant since it should only be used by the implementation. So we define it here. */ #ifndef SA_RESTORER # ifdef ASM_SA_RESTORER # define SA_RESTORER ASM_SA_RESTORER # endif #endif #include "xlat/sigact_flags.h" #include "xlat/sigprocmaskcmds.h" #endif /* HAVE_SIGACTION */ /* Anonymous realtime signals. */ /* Under glibc 2.1, SIGRTMIN et al are functions, but __SIGRTMIN is a constant. This is what we want. Otherwise, just use SIGRTMIN. */ #ifdef SIGRTMIN #ifndef __SIGRTMIN #define __SIGRTMIN SIGRTMIN #define __SIGRTMAX SIGRTMAX /* likewise */ #endif #endif /* Note on the size of sigset_t: * * In glibc, sigset_t is an array with space for 1024 bits (!), * even though all arches supported by Linux have only 64 signals * except MIPS, which has 128. IOW, it is 128 bytes long. * * In-kernel sigset_t is sized correctly (it is either 64 or 128 bit long). * However, some old syscall return only 32 lower bits (one word). * Example: sys_sigpending vs sys_rt_sigpending. * * Be aware of this fact when you try to * memcpy(&tcp->u_arg[1], &something, sizeof(sigset_t)) * - sizeof(sigset_t) is much bigger than you think, * it may overflow tcp->u_arg[] array, and it may try to copy more data * than is really available in <something>. * Similarly, * umoven(tcp, addr, sizeof(sigset_t), &sigset) * may be a bad idea: it'll try to read much more data than needed * to fetch a sigset_t. * Use (NSIG / 8) as a size instead. */ const char * signame(int sig) { static char buf[sizeof("SIGRT_%d") + sizeof(int)*3]; if (sig >= 0 && sig < nsignals) return signalent[sig]; #ifdef SIGRTMIN if (sig >= __SIGRTMIN && sig <= __SIGRTMAX) { sprintf(buf, "SIGRT_%d", (int)(sig - __SIGRTMIN)); return buf; } #endif sprintf(buf, "%d", sig); return buf; } static unsigned int popcount32(const uint32_t *a, unsigned int size) { unsigned int count = 0; for (; size; ++a, --size) { uint32_t x = *a; #ifdef HAVE___BUILTIN_POPCOUNT count += __builtin_popcount(x); #else for (; x; ++count) x &= x - 1; #endif } return count; } static const char * sprintsigmask_n(const char *prefix, const void *sig_mask, unsigned int bytes) { /* * The maximum number of signal names to be printed is NSIG * 2 / 3. * Most of signal names have length 7, * average length of signal names is less than 7. * The length of prefix string does not exceed 16. */ static char outstr[128 + 8 * (NSIG * 2 / 3)]; char *s; const uint32_t *mask; uint32_t inverted_mask[NSIG / 32]; unsigned int size; int i; char sep; s = stpcpy(outstr, prefix); mask = sig_mask; /* length of signal mask in 4-byte words */ size = (bytes >= NSIG / 8) ? NSIG / 32 : (bytes + 3) / 4; /* check whether 2/3 or more bits are set */ if (popcount32(mask, size) >= size * 32 * 2 / 3) { /* show those signals that are NOT in the mask */ unsigned int j; for (j = 0; j < size; ++j) inverted_mask[j] = ~mask[j]; mask = inverted_mask; *s++ = '~'; } sep = '['; for (i = 0; (i = next_set_bit(mask, i, size * 32)) >= 0; ) { ++i; *s++ = sep; if (i < nsignals) { s = stpcpy(s, signalent[i] + 3); } #ifdef SIGRTMIN else if (i >= __SIGRTMIN && i <= __SIGRTMAX) { s += sprintf(s, "RT_%u", i - __SIGRTMIN); } #endif else { s += sprintf(s, "%u", i); } sep = ' '; } if (sep == '[') *s++ = sep; *s++ = ']'; *s = '\0'; return outstr; } #define tprintsigmask_addr(prefix, mask) \ tprints(sprintsigmask_n((prefix), (mask), sizeof(mask))) #define sprintsigmask_val(prefix, mask) \ sprintsigmask_n((prefix), &(mask), sizeof(mask)) #define tprintsigmask_val(prefix, mask) \ tprints(sprintsigmask_n((prefix), &(mask), sizeof(mask))) void printsignal(int nr) { tprints(signame(nr)); } void print_sigset_addr_len(struct tcb *tcp, long addr, long len) { char mask[NSIG / 8]; if (!addr) { tprints("NULL"); return; } /* Here len is usually equals NSIG / 8 or current_wordsize. * But we code this defensively: */ if (len < 0) { bad: tprintf("%#lx", addr); return; } if (len >= NSIG / 8) len = NSIG / 8; else len = (len + 3) & ~3; if (umoven(tcp, addr, len, mask) < 0) goto bad; tprints(sprintsigmask_n("", mask, len)); } #ifndef ILL_ILLOPC #define ILL_ILLOPC 1 /* illegal opcode */ #define ILL_ILLOPN 2 /* illegal operand */ #define ILL_ILLADR 3 /* illegal addressing mode */ #define ILL_ILLTRP 4 /* illegal trap */ #define ILL_PRVOPC 5 /* privileged opcode */ #define ILL_PRVREG 6 /* privileged register */ #define ILL_COPROC 7 /* coprocessor error */ #define ILL_BADSTK 8 /* internal stack error */ #define FPE_INTDIV 1 /* integer divide by zero */ #define FPE_INTOVF 2 /* integer overflow */ #define FPE_FLTDIV 3 /* floating point divide by zero */ #define FPE_FLTOVF 4 /* floating point overflow */ #define FPE_FLTUND 5 /* floating point underflow */ #define FPE_FLTRES 6 /* floating point inexact result */ #define FPE_FLTINV 7 /* floating point invalid operation */ #define FPE_FLTSUB 8 /* subscript out of range */ #define SEGV_MAPERR 1 /* address not mapped to object */ #define SEGV_ACCERR 2 /* invalid permissions for mapped object */ #define BUS_ADRALN 1 /* invalid address alignment */ #define BUS_ADRERR 2 /* non-existant physical address */ #define BUS_OBJERR 3 /* object specific hardware error */ #define SYS_SECCOMP 1 /* seccomp triggered */ #define TRAP_BRKPT 1 /* process breakpoint */ #define TRAP_TRACE 2 /* process trace trap */ #define CLD_EXITED 1 /* child has exited */ #define CLD_KILLED 2 /* child was killed */ #define CLD_DUMPED 3 /* child terminated abnormally */ #define CLD_TRAPPED 4 /* traced child has trapped */ #define CLD_STOPPED 5 /* child has stopped */ #define CLD_CONTINUED 6 /* stopped child has continued */ #define POLL_IN 1 /* data input available */ #define POLL_OUT 2 /* output buffers available */ #define POLL_MSG 3 /* input message available */ #define POLL_ERR 4 /* i/o error */ #define POLL_PRI 5 /* high priority input available */ #define POLL_HUP 6 /* device disconnected */ #define SI_KERNEL 0x80 /* sent by kernel */ #define SI_USER 0 /* sent by kill, sigsend, raise */ #define SI_QUEUE -1 /* sent by sigqueue */ #define SI_TIMER -2 /* sent by timer expiration */ #define SI_MESGQ -3 /* sent by real time mesq state change */ #define SI_ASYNCIO -4 /* sent by AIO completion */ #define SI_SIGIO -5 /* sent by SIGIO */ #define SI_TKILL -6 /* sent by tkill */ #define SI_DETHREAD -7 /* sent by execve killing subsidiary threads */ #define SI_ASYNCNL -60 /* sent by asynch name lookup completion */ #endif #ifndef SI_FROMUSER # define SI_FROMUSER(sip) ((sip)->si_code <= 0) #endif #include "xlat/siginfo_codes.h" #include "xlat/sigill_codes.h" #include "xlat/sigfpe_codes.h" #include "xlat/sigtrap_codes.h" #include "xlat/sigchld_codes.h" #include "xlat/sigpoll_codes.h" #include "xlat/sigprof_codes.h" #ifdef SIGEMT #include "xlat/sigemt_codes.h" #endif #include "xlat/sigsegv_codes.h" #include "xlat/sigbus_codes.h" #ifndef SYS_SECCOMP # define SYS_SECCOMP 1 #endif #include "xlat/sigsys_codes.h" static void printsigsource(const siginfo_t *sip) { tprintf(", si_pid=%lu, si_uid=%lu", (unsigned long) sip->si_pid, (unsigned long) sip->si_uid); } static void printsigval(const siginfo_t *sip, int verbose) { if (!verbose) tprints(", ..."); else tprintf(", si_value={int=%u, ptr=%#lx}", sip->si_int, (unsigned long) sip->si_ptr); } void printsiginfo(siginfo_t *sip, int verbose) { const char *code; if (sip->si_signo == 0) { tprints("{}"); return; } tprints("{si_signo="); printsignal(sip->si_signo); code = xlookup(siginfo_codes, sip->si_code); if (!code) { switch (sip->si_signo) { case SIGTRAP: code = xlookup(sigtrap_codes, sip->si_code); break; case SIGCHLD: code = xlookup(sigchld_codes, sip->si_code); break; case SIGPOLL: code = xlookup(sigpoll_codes, sip->si_code); break; case SIGPROF: code = xlookup(sigprof_codes, sip->si_code); break; case SIGILL: code = xlookup(sigill_codes, sip->si_code); break; #ifdef SIGEMT case SIGEMT: code = xlookup(sigemt_codes, sip->si_code); break; #endif case SIGFPE: code = xlookup(sigfpe_codes, sip->si_code); break; case SIGSEGV: code = xlookup(sigsegv_codes, sip->si_code); break; case SIGBUS: code = xlookup(sigbus_codes, sip->si_code); break; case SIGSYS: code = xlookup(sigsys_codes, sip->si_code); break; } } if (code) tprintf(", si_code=%s", code); else tprintf(", si_code=%#x", sip->si_code); #ifdef SI_NOINFO if (sip->si_code != SI_NOINFO) #endif { if (sip->si_errno) { if (sip->si_errno < 0 || sip->si_errno >= nerrnos) tprintf(", si_errno=%d", sip->si_errno); else tprintf(", si_errno=%s", errnoent[sip->si_errno]); } #ifdef SI_FROMUSER if (SI_FROMUSER(sip)) { switch (sip->si_code) { #ifdef SI_USER case SI_USER: printsigsource(sip); break; #endif #ifdef SI_TKILL case SI_TKILL: printsigsource(sip); break; #endif #ifdef SI_TIMER case SI_TIMER: tprintf(", si_timerid=%#x, si_overrun=%d", sip->si_timerid, sip->si_overrun); printsigval(sip, verbose); break; #endif default: printsigsource(sip); if (sip->si_ptr) printsigval(sip, verbose); break; } } else #endif /* SI_FROMUSER */ { switch (sip->si_signo) { case SIGCHLD: printsigsource(sip); tprints(", si_status="); if (sip->si_code == CLD_EXITED) tprintf("%d", sip->si_status); else printsignal(sip->si_status); if (!verbose) tprints(", ..."); else tprintf(", si_utime=%llu, si_stime=%llu", (unsigned long long) sip->si_utime, (unsigned long long) sip->si_stime); break; case SIGILL: case SIGFPE: case SIGSEGV: case SIGBUS: tprintf(", si_addr=%#lx", (unsigned long) sip->si_addr); break; case SIGPOLL: switch (sip->si_code) { case POLL_IN: case POLL_OUT: case POLL_MSG: tprintf(", si_band=%ld", (long) sip->si_band); break; } break; #ifdef HAVE_SIGINFO_T_SI_SYSCALL case SIGSYS: tprintf(", si_call_addr=%#lx, si_syscall=%d, si_arch=%u", (unsigned long) sip->si_call_addr, sip->si_syscall, sip->si_arch); break; #endif default: if (sip->si_pid || sip->si_uid) printsigsource(sip); if (sip->si_ptr) printsigval(sip, verbose); } } } tprints("}"); } void printsiginfo_at(struct tcb *tcp, long addr) { siginfo_t si; if (!addr) { tprints("NULL"); return; } if (syserror(tcp)) { tprintf("%#lx", addr); return; } if (umove(tcp, addr, &si) < 0) { tprints("{???}"); return; } printsiginfo(&si, verbose(tcp)); } int sys_sigsetmask(struct tcb *tcp) { if (entering(tcp)) { tprintsigmask_val("", tcp->u_arg[0]); } else if (!syserror(tcp)) { tcp->auxstr = sprintsigmask_val("old mask ", tcp->u_rval); return RVAL_HEX | RVAL_STR; } return 0; } #ifdef HAVE_SIGACTION struct old_sigaction { /* sa_handler may be a libc #define, need to use other name: */ #ifdef MIPS unsigned int sa_flags; void (*__sa_handler)(int); /* Kernel treats sa_mask as an array of longs. */ unsigned long sa_mask[NSIG / sizeof(long) ? NSIG / sizeof(long) : 1]; #else void (*__sa_handler)(int); unsigned long sa_mask; unsigned long sa_flags; void (*sa_restorer)(void); #endif /* !MIPS */ }; struct old_sigaction32 { /* sa_handler may be a libc #define, need to use other name: */ uint32_t __sa_handler; uint32_t sa_mask; uint32_t sa_flags; uint32_t sa_restorer; }; static void decode_old_sigaction(struct tcb *tcp, long addr) { struct old_sigaction sa; int r; if (!addr) { tprints("NULL"); return; } if (!verbose(tcp) || (exiting(tcp) && syserror(tcp))) { tprintf("%#lx", addr); return; } #if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4 if (current_wordsize != sizeof(sa.__sa_handler) && current_wordsize == 4) { struct old_sigaction32 sa32; r = umove(tcp, addr, &sa32); if (r >= 0) { memset(&sa, 0, sizeof(sa)); sa.__sa_handler = (void*)(uintptr_t)sa32.__sa_handler; sa.sa_flags = sa32.sa_flags; sa.sa_restorer = (void*)(uintptr_t)sa32.sa_restorer; sa.sa_mask = sa32.sa_mask; } } else #endif { r = umove(tcp, addr, &sa); } if (r < 0) { tprints("{...}"); return; } /* Architectures using function pointers, like * hppa, may need to manipulate the function pointer * to compute the result of a comparison. However, * the __sa_handler function pointer exists only in * the address space of the traced process, and can't * be manipulated by strace. In order to prevent the * compiler from generating code to manipulate * __sa_handler we cast the function pointers to long. */ if ((long)sa.__sa_handler == (long)SIG_ERR) tprints("{SIG_ERR, "); else if ((long)sa.__sa_handler == (long)SIG_DFL) tprints("{SIG_DFL, "); else if ((long)sa.__sa_handler == (long)SIG_IGN) tprints("{SIG_IGN, "); else tprintf("{%#lx, ", (long) sa.__sa_handler); #ifdef MIPS tprintsigmask_addr("", sa.sa_mask); #else tprintsigmask_val("", sa.sa_mask); #endif tprints(", "); printflags(sigact_flags, sa.sa_flags, "SA_???"); #ifdef SA_RESTORER if (sa.sa_flags & SA_RESTORER) tprintf(", %p", sa.sa_restorer); #endif tprints("}"); } int sys_sigaction(struct tcb *tcp) { if (entering(tcp)) { printsignal(tcp->u_arg[0]); tprints(", "); decode_old_sigaction(tcp, tcp->u_arg[1]); tprints(", "); } else decode_old_sigaction(tcp, tcp->u_arg[2]); return 0; } int sys_signal(struct tcb *tcp) { if (entering(tcp)) { printsignal(tcp->u_arg[0]); tprints(", "); switch (tcp->u_arg[1]) { case (long) SIG_ERR: tprints("SIG_ERR"); break; case (long) SIG_DFL: tprints("SIG_DFL"); break; case (long) SIG_IGN: tprints("SIG_IGN"); break; default: tprintf("%#lx", tcp->u_arg[1]); } return 0; } else if (!syserror(tcp)) { switch (tcp->u_rval) { case (long) SIG_ERR: tcp->auxstr = "SIG_ERR"; break; case (long) SIG_DFL: tcp->auxstr = "SIG_DFL"; break; case (long) SIG_IGN: tcp->auxstr = "SIG_IGN"; break; default: tcp->auxstr = NULL; } return RVAL_HEX | RVAL_STR; } return 0; } #endif /* HAVE_SIGACTION */ int sys_sigreturn(struct tcb *tcp) { #if defined(ARM) if (entering(tcp)) { struct arm_sigcontext { unsigned long trap_no; unsigned long error_code; unsigned long oldmask; unsigned long arm_r0; unsigned long arm_r1; unsigned long arm_r2; unsigned long arm_r3; unsigned long arm_r4; unsigned long arm_r5; unsigned long arm_r6; unsigned long arm_r7; unsigned long arm_r8; unsigned long arm_r9; unsigned long arm_r10; unsigned long arm_fp; unsigned long arm_ip; unsigned long arm_sp; unsigned long arm_lr; unsigned long arm_pc; unsigned long arm_cpsr; unsigned long fault_address; }; struct arm_ucontext { unsigned long uc_flags; unsigned long uc_link; /* struct ucontext* */ /* The next three members comprise stack_t struct: */ unsigned long ss_sp; /* void* */ unsigned long ss_flags; /* int */ unsigned long ss_size; /* size_t */ struct arm_sigcontext sc; /* These two members are sigset_t: */ unsigned long uc_sigmask[2]; /* more fields follow, which we aren't interested in */ }; struct arm_ucontext uc; if (umove(tcp, arm_regs.ARM_sp, &uc) < 0) return 0; /* * Kernel fills out uc.sc.oldmask too when it sets up signal stack, * but for sigmask restore, sigreturn syscall uses uc.uc_sigmask instead. */ tprintsigmask_addr(") (mask ", uc.uc_sigmask); } #elif defined(S390) || defined(S390X) if (entering(tcp)) { long usp; struct sigcontext sc; if (upeek(tcp->pid, PT_GPR15, &usp) < 0) return 0; if (umove(tcp, usp + __SIGNAL_FRAMESIZE, &sc) < 0) return 0; tprintsigmask_addr(") (mask ", sc.oldmask); } #elif defined(I386) || defined(X86_64) # if defined(X86_64) if (current_personality == 0) /* 64-bit */ return 0; # endif if (entering(tcp)) { struct i386_sigcontext_struct { uint16_t gs, __gsh; uint16_t fs, __fsh; uint16_t es, __esh; uint16_t ds, __dsh; uint32_t edi; uint32_t esi; uint32_t ebp; uint32_t esp; uint32_t ebx; uint32_t edx; uint32_t ecx; uint32_t eax; uint32_t trapno; uint32_t err; uint32_t eip; uint16_t cs, __csh; uint32_t eflags; uint32_t esp_at_signal; uint16_t ss, __ssh; uint32_t i387; uint32_t oldmask; uint32_t cr2; }; struct i386_fpstate { uint32_t cw; uint32_t sw; uint32_t tag; uint32_t ipoff; uint32_t cssel; uint32_t dataoff; uint32_t datasel; uint8_t st[8][10]; /* 8*10 bytes: FP regs */ uint16_t status; uint16_t magic; uint32_t fxsr_env[6]; uint32_t mxcsr; uint32_t reserved; uint8_t stx[8][16]; /* 8*16 bytes: FP regs, each padded to 16 bytes */ uint8_t xmm[8][16]; /* 8 XMM regs */ uint32_t padding1[44]; uint32_t padding2[12]; /* union with struct _fpx_sw_bytes */ }; struct { struct i386_sigcontext_struct sc; struct i386_fpstate fp; uint32_t extramask[1]; } signal_stack; /* On i386, sc is followed on stack by struct fpstate * and after it an additional u32 extramask[1] which holds * upper half of the mask. */ uint32_t sigmask[2]; if (umove(tcp, *i386_esp_ptr, &signal_stack) < 0) return 0; sigmask[0] = signal_stack.sc.oldmask; sigmask[1] = signal_stack.extramask[0]; tprintsigmask_addr(") (mask ", sigmask); } #elif defined(IA64) if (entering(tcp)) { struct sigcontext sc; long sp; /* offset of sigcontext in the kernel's sigframe structure: */ # define SIGFRAME_SC_OFFSET 0x90 if (upeek(tcp->pid, PT_R12, &sp) < 0) return 0; if (umove(tcp, sp + 16 + SIGFRAME_SC_OFFSET, &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.sc_mask); } #elif defined(POWERPC) if (entering(tcp)) { long esp; struct sigcontext sc; esp = ppc_regs.gpr[1]; /* Skip dummy stack frame. */ #ifdef POWERPC64 if (current_personality == 0) esp += 128; else esp += 64; #else esp += 64; #endif if (umove(tcp, esp, &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.oldmask); } #elif defined(M68K) if (entering(tcp)) { long usp; struct sigcontext sc; if (upeek(tcp->pid, 4*PT_USP, &usp) < 0) return 0; if (umove(tcp, usp, &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.sc_mask); } #elif defined(ALPHA) if (entering(tcp)) { long fp; struct sigcontext sc; if (upeek(tcp->pid, REG_FP, &fp) < 0) return 0; if (umove(tcp, fp, &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.sc_mask); } #elif defined(SPARC) || defined(SPARC64) if (entering(tcp)) { long i1; m_siginfo_t si; i1 = sparc_regs.u_regs[U_REG_O1]; if (umove(tcp, i1, &si) < 0) { perror_msg("sigreturn: umove"); return 0; } tprintsigmask_val(") (mask ", si.si_mask); } #elif defined(LINUX_MIPSN32) || defined(LINUX_MIPSN64) /* This decodes rt_sigreturn. The 64-bit ABIs do not have sigreturn. */ if (entering(tcp)) { long sp; struct ucontext uc; if (upeek(tcp->pid, REG_SP, &sp) < 0) return 0; /* There are six words followed by a 128-byte siginfo. */ sp = sp + 6 * 4 + 128; if (umove(tcp, sp, &uc) < 0) return 0; tprintsigmask_val(") (mask ", uc.uc_sigmask); } #elif defined(MIPS) if (entering(tcp)) { long sp; struct pt_regs regs; m_siginfo_t si; if (ptrace(PTRACE_GETREGS, tcp->pid, (char *)&regs, 0) < 0) { perror_msg("sigreturn: PTRACE_GETREGS"); return 0; } sp = regs.regs[29]; if (umove(tcp, sp, &si) < 0) return 0; tprintsigmask_val(") (mask ", si.si_mask); } #elif defined(CRISV10) || defined(CRISV32) if (entering(tcp)) { struct sigcontext sc; long regs[PT_MAX+1]; if (ptrace(PTRACE_GETREGS, tcp->pid, NULL, (long)regs) < 0) { perror_msg("sigreturn: PTRACE_GETREGS"); return 0; } if (umove(tcp, regs[PT_USP], &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.oldmask); } #elif defined(TILE) if (entering(tcp)) { struct ucontext uc; /* offset of ucontext in the kernel's sigframe structure */ # define SIGFRAME_UC_OFFSET C_ABI_SAVE_AREA_SIZE + sizeof(siginfo_t) if (umove(tcp, tile_regs.sp + SIGFRAME_UC_OFFSET, &uc) < 0) return 0; tprintsigmask_val(") (mask ", uc.uc_sigmask); } #elif defined(MICROBLAZE) /* TODO: Verify that this is correct... */ if (entering(tcp)) { struct sigcontext sc; long sp; /* Read r1, the stack pointer. */ if (upeek(tcp->pid, 1 * 4, &sp) < 0) return 0; if (umove(tcp, sp, &sc) < 0) return 0; tprintsigmask_val(") (mask ", sc.oldmask); } #elif defined(XTENSA) /* Xtensa only has rt_sys_sigreturn */ #elif defined(ARC) /* ARC syscall ABI only supports rt_sys_sigreturn */ #else # warning No sys_sigreturn() for this architecture # warning (no problem, just a reminder :-) #endif return 0; } int sys_siggetmask(struct tcb *tcp) { if (exiting(tcp)) { tcp->auxstr = sprintsigmask_val("mask ", tcp->u_rval); } return RVAL_HEX | RVAL_STR; } int sys_sigsuspend(struct tcb *tcp) { if (entering(tcp)) { tprintsigmask_val("", tcp->u_arg[2]); } return 0; } #if !defined SS_ONSTACK #define SS_ONSTACK 1 #define SS_DISABLE 2 #endif #include "xlat/sigaltstack_flags.h" static void print_stack_t(struct tcb *tcp, unsigned long addr) { stack_t ss; int r; if (!addr) { tprints("NULL"); return; } #if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4 if (current_wordsize != sizeof(ss.ss_sp) && current_wordsize == 4) { struct { uint32_t ss_sp; int32_t ss_flags; uint32_t ss_size; } ss32; r = umove(tcp, addr, &ss32); if (r >= 0) { memset(&ss, 0, sizeof(ss)); ss.ss_sp = (void*)(unsigned long) ss32.ss_sp; ss.ss_flags = ss32.ss_flags; ss.ss_size = (unsigned long) ss32.ss_size; } } else #endif { r = umove(tcp, addr, &ss); } if (r < 0) { tprintf("%#lx", addr); } else { tprintf("{ss_sp=%#lx, ss_flags=", (unsigned long) ss.ss_sp); printflags(sigaltstack_flags, ss.ss_flags, "SS_???"); tprintf(", ss_size=%lu}", (unsigned long) ss.ss_size); } } int sys_sigaltstack(struct tcb *tcp) { if (entering(tcp)) { print_stack_t(tcp, tcp->u_arg[0]); } else { tprints(", "); print_stack_t(tcp, tcp->u_arg[1]); } return 0; } #ifdef HAVE_SIGACTION /* "Old" sigprocmask, which operates with word-sized signal masks */ int sys_sigprocmask(struct tcb *tcp) { # ifdef ALPHA if (entering(tcp)) { /* * Alpha/OSF is different: it doesn't pass in two pointers, * but rather passes in the new bitmask as an argument and * then returns the old bitmask. This "works" because we * only have 64 signals to worry about. If you want more, * use of the rt_sigprocmask syscall is required. * Alpha: * old = osf_sigprocmask(how, new); * Everyone else: * ret = sigprocmask(how, &new, &old, ...); */ printxval(sigprocmaskcmds, tcp->u_arg[0], "SIG_???"); tprintsigmask_val(", ", tcp->u_arg[1]); } else if (!syserror(tcp)) { tcp->auxstr = sprintsigmask_val("old mask ", tcp->u_rval); return RVAL_HEX | RVAL_STR; } # else /* !ALPHA */ if (entering(tcp)) { printxval(sigprocmaskcmds, tcp->u_arg[0], "SIG_???"); tprints(", "); print_sigset_addr_len(tcp, tcp->u_arg[1], current_wordsize); tprints(", "); } else { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[2]); else print_sigset_addr_len(tcp, tcp->u_arg[2], current_wordsize); } # endif /* !ALPHA */ return 0; } #endif /* HAVE_SIGACTION */ int sys_kill(struct tcb *tcp) { if (entering(tcp)) { tprintf("%ld, %s", widen_to_long(tcp->u_arg[0]), signame(tcp->u_arg[1]) ); } return 0; } int sys_tgkill(struct tcb *tcp) { if (entering(tcp)) { tprintf("%ld, %ld, %s", widen_to_long(tcp->u_arg[0]), widen_to_long(tcp->u_arg[1]), signame(tcp->u_arg[2]) ); } return 0; } int sys_sigpending(struct tcb *tcp) { if (exiting(tcp)) { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[0]); else print_sigset_addr_len(tcp, tcp->u_arg[0], current_wordsize); } return 0; } int sys_rt_sigprocmask(struct tcb *tcp) { /* Note: arg[3] is the length of the sigset. Kernel requires NSIG / 8 */ if (entering(tcp)) { printxval(sigprocmaskcmds, tcp->u_arg[0], "SIG_???"); tprints(", "); print_sigset_addr_len(tcp, tcp->u_arg[1], tcp->u_arg[3]); tprints(", "); } else { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[2]); else print_sigset_addr_len(tcp, tcp->u_arg[2], tcp->u_arg[3]); tprintf(", %lu", tcp->u_arg[3]); } return 0; } /* Structure describing the action to be taken when a signal arrives. */ struct new_sigaction { /* sa_handler may be a libc #define, need to use other name: */ #ifdef MIPS unsigned int sa_flags; void (*__sa_handler)(int); #else void (*__sa_handler)(int); unsigned long sa_flags; void (*sa_restorer)(void); #endif /* !MIPS */ /* Kernel treats sa_mask as an array of longs. */ unsigned long sa_mask[NSIG / sizeof(long) ? NSIG / sizeof(long) : 1]; }; /* Same for i386-on-x86_64 and similar cases */ struct new_sigaction32 { uint32_t __sa_handler; uint32_t sa_flags; uint32_t sa_restorer; uint32_t sa_mask[2 * (NSIG / sizeof(long) ? NSIG / sizeof(long) : 1)]; }; static void decode_new_sigaction(struct tcb *tcp, long addr) { struct new_sigaction sa; int r; if (!addr) { tprints("NULL"); return; } if (!verbose(tcp) || (exiting(tcp) && syserror(tcp))) { tprintf("%#lx", addr); return; } #if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4 if (current_wordsize != sizeof(sa.sa_flags) && current_wordsize == 4) { struct new_sigaction32 sa32; r = umove(tcp, addr, &sa32); if (r >= 0) { memset(&sa, 0, sizeof(sa)); sa.__sa_handler = (void*)(unsigned long)sa32.__sa_handler; sa.sa_flags = sa32.sa_flags; sa.sa_restorer = (void*)(unsigned long)sa32.sa_restorer; /* Kernel treats sa_mask as an array of longs. * For 32-bit process, "long" is uint32_t, thus, for example, * 32th bit in sa_mask will end up as bit 0 in sa_mask[1]. * But for (64-bit) kernel, 32th bit in sa_mask is * 32th bit in 0th (64-bit) long! * For little-endian, it's the same. * For big-endian, we swap 32-bit words. */ sa.sa_mask[0] = sa32.sa_mask[0] + ((long)(sa32.sa_mask[1]) << 32); } } else #endif { r = umove(tcp, addr, &sa); } if (r < 0) { tprints("{...}"); return; } /* Architectures using function pointers, like * hppa, may need to manipulate the function pointer * to compute the result of a comparison. However, * the __sa_handler function pointer exists only in * the address space of the traced process, and can't * be manipulated by strace. In order to prevent the * compiler from generating code to manipulate * __sa_handler we cast the function pointers to long. */ if ((long)sa.__sa_handler == (long)SIG_ERR) tprints("{SIG_ERR, "); else if ((long)sa.__sa_handler == (long)SIG_DFL) tprints("{SIG_DFL, "); else if ((long)sa.__sa_handler == (long)SIG_IGN) tprints("{SIG_IGN, "); else tprintf("{%#lx, ", (long) sa.__sa_handler); /* * Sigset size is in tcp->u_arg[4] (SPARC) * or in tcp->u_arg[3] (all other), * but kernel won't handle sys_rt_sigaction * with wrong sigset size (just returns EINVAL instead). * We just fetch the right size, which is NSIG / 8. */ tprintsigmask_val("", sa.sa_mask); tprints(", "); printflags(sigact_flags, sa.sa_flags, "SA_???"); #ifdef SA_RESTORER if (sa.sa_flags & SA_RESTORER) tprintf(", %p", sa.sa_restorer); #endif tprints("}"); } int sys_rt_sigaction(struct tcb *tcp) { if (entering(tcp)) { printsignal(tcp->u_arg[0]); tprints(", "); decode_new_sigaction(tcp, tcp->u_arg[1]); tprints(", "); } else { decode_new_sigaction(tcp, tcp->u_arg[2]); #if defined(SPARC) || defined(SPARC64) tprintf(", %#lx, %lu", tcp->u_arg[3], tcp->u_arg[4]); #elif defined(ALPHA) tprintf(", %lu, %#lx", tcp->u_arg[3], tcp->u_arg[4]); #else tprintf(", %lu", tcp->u_arg[3]); #endif } return 0; } int sys_rt_sigpending(struct tcb *tcp) { if (exiting(tcp)) { /* * One of the few syscalls where sigset size (arg[1]) * is allowed to be <= NSIG / 8, not strictly ==. * This allows non-rt sigpending() syscall * to reuse rt_sigpending() code in kernel. */ if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[0]); else print_sigset_addr_len(tcp, tcp->u_arg[0], tcp->u_arg[1]); tprintf(", %lu", tcp->u_arg[1]); } return 0; } int sys_rt_sigsuspend(struct tcb *tcp) { if (entering(tcp)) { /* NB: kernel requires arg[1] == NSIG / 8 */ print_sigset_addr_len(tcp, tcp->u_arg[0], tcp->u_arg[1]); tprintf(", %lu", tcp->u_arg[1]); } return 0; } static void print_sigqueueinfo(struct tcb *tcp, int sig, unsigned long uinfo) { printsignal(sig); tprints(", "); printsiginfo_at(tcp, uinfo); } int sys_rt_sigqueueinfo(struct tcb *tcp) { if (entering(tcp)) { tprintf("%lu, ", tcp->u_arg[0]); print_sigqueueinfo(tcp, tcp->u_arg[1], tcp->u_arg[2]); } return 0; } int sys_rt_tgsigqueueinfo(struct tcb *tcp) { if (entering(tcp)) { tprintf("%lu, %lu, ", tcp->u_arg[0], tcp->u_arg[1]); print_sigqueueinfo(tcp, tcp->u_arg[2], tcp->u_arg[3]); } return 0; } int sys_rt_sigtimedwait(struct tcb *tcp) { /* NB: kernel requires arg[3] == NSIG / 8 */ if (entering(tcp)) { print_sigset_addr_len(tcp, tcp->u_arg[0], tcp->u_arg[3]); tprints(", "); /* This is the only "return" parameter, */ if (tcp->u_arg[1] != 0) return 0; /* ... if it's NULL, can decode all on entry */ tprints("NULL, "); } else if (tcp->u_arg[1] != 0) { /* syscall exit, and u_arg[1] wasn't NULL */ printsiginfo_at(tcp, tcp->u_arg[1]); tprints(", "); } else { /* syscall exit, and u_arg[1] was NULL */ return 0; } print_timespec(tcp, tcp->u_arg[2]); tprintf(", %lu", tcp->u_arg[3]); return 0; }; int sys_restart_syscall(struct tcb *tcp) { if (entering(tcp)) tprints("<... resuming interrupted call ...>"); return 0; } static int do_signalfd(struct tcb *tcp, int flags_arg) { /* NB: kernel requires arg[2] == NSIG / 8 */ if (entering(tcp)) { printfd(tcp, tcp->u_arg[0]); tprints(", "); print_sigset_addr_len(tcp, tcp->u_arg[1], tcp->u_arg[2]); tprintf(", %lu", tcp->u_arg[2]); if (flags_arg >= 0) { tprints(", "); printflags(open_mode_flags, tcp->u_arg[flags_arg], "O_???"); } } return 0; } int sys_signalfd(struct tcb *tcp) { return do_signalfd(tcp, -1); } int sys_signalfd4(struct tcb *tcp) { return do_signalfd(tcp, 3); }
25.113803
77
0.654144
[ "object" ]
f015e22b28e60a049726376a0b938f28b1599b70
28,097
c
C
tests/api/test-dev-lightfunc.c
jacobmarshall-etc/duktape
62ef74d0dd64edcd518c588dd88780ea4312144a
[ "MIT" ]
null
null
null
tests/api/test-dev-lightfunc.c
jacobmarshall-etc/duktape
62ef74d0dd64edcd518c588dd88780ea4312144a
[ "MIT" ]
null
null
null
tests/api/test-dev-lightfunc.c
jacobmarshall-etc/duktape
62ef74d0dd64edcd518c588dd88780ea4312144a
[ "MIT" ]
null
null
null
/* * Behavior of lightweight functions from C code in various situations. * * Also documents the detailed behavior and limitations of lightfuncs. */ static duk_ret_t my_addtwo_lfunc(duk_context *ctx) { printf("addtwo entry top: %ld\n", (long) duk_get_top(ctx)); duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, "length"); printf("addtwo 'length' property: %s\n", duk_safe_to_string(ctx, -1)); duk_pop(ctx); printf("addtwo duk_get_length: %ld\n", (long) duk_get_length(ctx, -1)); printf("addtwo magic: %ld\n", (long) duk_get_magic(ctx, -1)); printf("current magic: %ld\n", (long) duk_get_current_magic(ctx)); duk_pop(ctx); duk_push_number(ctx, duk_require_number(ctx, 0) + duk_require_number(ctx, 1)); printf("addtwo final top: %ld\n", (long) duk_get_top(ctx)); return 1; } static duk_ret_t my_dummy_func(duk_context *ctx) { (void) ctx; return DUK_RET_ERROR; } /*=== *** test_is_lightfunc (duk_safe_call) 0: is_lightfunc: 0 1: is_lightfunc: 0 2: is_lightfunc: 0 3: is_lightfunc: 0 4: is_lightfunc: 1 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_is_lightfunc(duk_context *ctx, void *udata) { duk_idx_t i, n; (void) udata; /* Just a few spot checks. */ duk_push_undefined(ctx); duk_push_null(ctx); duk_push_object(ctx); duk_push_c_function(ctx, my_dummy_func, 0); duk_push_c_lightfunc(ctx, my_dummy_func, 0, 0, 0); for (i = 0, n = duk_get_top(ctx); i < n; i++) { printf("%ld: is_lightfunc: %ld\n", (long) i, (long) duk_is_lightfunc(ctx, i)); } return 0; } /*=== *** test_simple_push (duk_safe_call) top before lfunc push: 2 push retval: 2 top after lfunc push: 3 type at top: 9 typemask at top: 0x0200 addtwo entry top: 2 addtwo 'length' property: 3 addtwo duk_get_length: 3 addtwo magic: -66 current magic: -66 addtwo final top: 3 result: 357 final top: 3 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_simple_push(duk_context *ctx, void *udata) { duk_idx_t ret; (void) udata; duk_set_top(ctx, 0); duk_push_undefined(ctx); /* dummy padding */ duk_push_undefined(ctx); printf("top before lfunc push: %ld\n", (long) duk_get_top(ctx)); ret = duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, -0x42 /*magic*/); printf("push retval: %ld\n", (long) ret); printf("top after lfunc push: %ld\n", (long) duk_get_top(ctx)); printf("type at top: %ld\n", (long) duk_get_type(ctx, -1)); printf("typemask at top: 0x%04lx\n", (long) duk_get_type_mask(ctx, -1)); duk_push_string(ctx, "dummy this"); duk_push_int(ctx, 123); duk_push_int(ctx, 234); duk_push_int(ctx, 345); duk_call_method(ctx, 3 /*nargs*/); /* [ ... lfunc this 123 234 345 ] -> [ ... retval ] */ printf("result: %s\n", duk_safe_to_string(ctx, -1)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_magic (duk_safe_call) i=-256, res=TypeError: invalid call args i=-255, res=TypeError: invalid call args i=-254, res=TypeError: invalid call args i=-253, res=TypeError: invalid call args i=-252, res=TypeError: invalid call args i=-251, res=TypeError: invalid call args i=-250, res=TypeError: invalid call args i=-249, res=TypeError: invalid call args i=-248, res=TypeError: invalid call args i=-247, res=TypeError: invalid call args i=-246, res=TypeError: invalid call args i=-245, res=TypeError: invalid call args i=-244, res=TypeError: invalid call args i=-243, res=TypeError: invalid call args i=-242, res=TypeError: invalid call args i=-241, res=TypeError: invalid call args i=-240, res=TypeError: invalid call args i=-239, res=TypeError: invalid call args i=-238, res=TypeError: invalid call args i=-237, res=TypeError: invalid call args i=-236, res=TypeError: invalid call args i=-235, res=TypeError: invalid call args i=-234, res=TypeError: invalid call args i=-233, res=TypeError: invalid call args i=-232, res=TypeError: invalid call args i=-231, res=TypeError: invalid call args i=-230, res=TypeError: invalid call args i=-229, res=TypeError: invalid call args i=-228, res=TypeError: invalid call args i=-227, res=TypeError: invalid call args i=-226, res=TypeError: invalid call args i=-225, res=TypeError: invalid call args i=-224, res=TypeError: invalid call args i=-223, res=TypeError: invalid call args i=-222, res=TypeError: invalid call args i=-221, res=TypeError: invalid call args i=-220, res=TypeError: invalid call args i=-219, res=TypeError: invalid call args i=-218, res=TypeError: invalid call args i=-217, res=TypeError: invalid call args i=-216, res=TypeError: invalid call args i=-215, res=TypeError: invalid call args i=-214, res=TypeError: invalid call args i=-213, res=TypeError: invalid call args i=-212, res=TypeError: invalid call args i=-211, res=TypeError: invalid call args i=-210, res=TypeError: invalid call args i=-209, res=TypeError: invalid call args i=-208, res=TypeError: invalid call args i=-207, res=TypeError: invalid call args i=-206, res=TypeError: invalid call args i=-205, res=TypeError: invalid call args i=-204, res=TypeError: invalid call args i=-203, res=TypeError: invalid call args i=-202, res=TypeError: invalid call args i=-201, res=TypeError: invalid call args i=-200, res=TypeError: invalid call args i=-199, res=TypeError: invalid call args i=-198, res=TypeError: invalid call args i=-197, res=TypeError: invalid call args i=-196, res=TypeError: invalid call args i=-195, res=TypeError: invalid call args i=-194, res=TypeError: invalid call args i=-193, res=TypeError: invalid call args i=-192, res=TypeError: invalid call args i=-191, res=TypeError: invalid call args i=-190, res=TypeError: invalid call args i=-189, res=TypeError: invalid call args i=-188, res=TypeError: invalid call args i=-187, res=TypeError: invalid call args i=-186, res=TypeError: invalid call args i=-185, res=TypeError: invalid call args i=-184, res=TypeError: invalid call args i=-183, res=TypeError: invalid call args i=-182, res=TypeError: invalid call args i=-181, res=TypeError: invalid call args i=-180, res=TypeError: invalid call args i=-179, res=TypeError: invalid call args i=-178, res=TypeError: invalid call args i=-177, res=TypeError: invalid call args i=-176, res=TypeError: invalid call args i=-175, res=TypeError: invalid call args i=-174, res=TypeError: invalid call args i=-173, res=TypeError: invalid call args i=-172, res=TypeError: invalid call args i=-171, res=TypeError: invalid call args i=-170, res=TypeError: invalid call args i=-169, res=TypeError: invalid call args i=-168, res=TypeError: invalid call args i=-167, res=TypeError: invalid call args i=-166, res=TypeError: invalid call args i=-165, res=TypeError: invalid call args i=-164, res=TypeError: invalid call args i=-163, res=TypeError: invalid call args i=-162, res=TypeError: invalid call args i=-161, res=TypeError: invalid call args i=-160, res=TypeError: invalid call args i=-159, res=TypeError: invalid call args i=-158, res=TypeError: invalid call args i=-157, res=TypeError: invalid call args i=-156, res=TypeError: invalid call args i=-155, res=TypeError: invalid call args i=-154, res=TypeError: invalid call args i=-153, res=TypeError: invalid call args i=-152, res=TypeError: invalid call args i=-151, res=TypeError: invalid call args i=-150, res=TypeError: invalid call args i=-149, res=TypeError: invalid call args i=-148, res=TypeError: invalid call args i=-147, res=TypeError: invalid call args i=-146, res=TypeError: invalid call args i=-145, res=TypeError: invalid call args i=-144, res=TypeError: invalid call args i=-143, res=TypeError: invalid call args i=-142, res=TypeError: invalid call args i=-141, res=TypeError: invalid call args i=-140, res=TypeError: invalid call args i=-139, res=TypeError: invalid call args i=-138, res=TypeError: invalid call args i=-137, res=TypeError: invalid call args i=-136, res=TypeError: invalid call args i=-135, res=TypeError: invalid call args i=-134, res=TypeError: invalid call args i=-133, res=TypeError: invalid call args i=-132, res=TypeError: invalid call args i=-131, res=TypeError: invalid call args i=-130, res=TypeError: invalid call args i=-129, res=TypeError: invalid call args i=-128, res=1 i=-127, res=1 i=-126, res=1 i=-125, res=1 i=-124, res=1 i=-123, res=1 i=-122, res=1 i=-121, res=1 i=-120, res=1 i=-119, res=1 i=-118, res=1 i=-117, res=1 i=-116, res=1 i=-115, res=1 i=-114, res=1 i=-113, res=1 i=-112, res=1 i=-111, res=1 i=-110, res=1 i=-109, res=1 i=-108, res=1 i=-107, res=1 i=-106, res=1 i=-105, res=1 i=-104, res=1 i=-103, res=1 i=-102, res=1 i=-101, res=1 i=-100, res=1 i=-99, res=1 i=-98, res=1 i=-97, res=1 i=-96, res=1 i=-95, res=1 i=-94, res=1 i=-93, res=1 i=-92, res=1 i=-91, res=1 i=-90, res=1 i=-89, res=1 i=-88, res=1 i=-87, res=1 i=-86, res=1 i=-85, res=1 i=-84, res=1 i=-83, res=1 i=-82, res=1 i=-81, res=1 i=-80, res=1 i=-79, res=1 i=-78, res=1 i=-77, res=1 i=-76, res=1 i=-75, res=1 i=-74, res=1 i=-73, res=1 i=-72, res=1 i=-71, res=1 i=-70, res=1 i=-69, res=1 i=-68, res=1 i=-67, res=1 i=-66, res=1 i=-65, res=1 i=-64, res=1 i=-63, res=1 i=-62, res=1 i=-61, res=1 i=-60, res=1 i=-59, res=1 i=-58, res=1 i=-57, res=1 i=-56, res=1 i=-55, res=1 i=-54, res=1 i=-53, res=1 i=-52, res=1 i=-51, res=1 i=-50, res=1 i=-49, res=1 i=-48, res=1 i=-47, res=1 i=-46, res=1 i=-45, res=1 i=-44, res=1 i=-43, res=1 i=-42, res=1 i=-41, res=1 i=-40, res=1 i=-39, res=1 i=-38, res=1 i=-37, res=1 i=-36, res=1 i=-35, res=1 i=-34, res=1 i=-33, res=1 i=-32, res=1 i=-31, res=1 i=-30, res=1 i=-29, res=1 i=-28, res=1 i=-27, res=1 i=-26, res=1 i=-25, res=1 i=-24, res=1 i=-23, res=1 i=-22, res=1 i=-21, res=1 i=-20, res=1 i=-19, res=1 i=-18, res=1 i=-17, res=1 i=-16, res=1 i=-15, res=1 i=-14, res=1 i=-13, res=1 i=-12, res=1 i=-11, res=1 i=-10, res=1 i=-9, res=1 i=-8, res=1 i=-7, res=1 i=-6, res=1 i=-5, res=1 i=-4, res=1 i=-3, res=1 i=-2, res=1 i=-1, res=1 i=0, res=1 i=1, res=1 i=2, res=1 i=3, res=1 i=4, res=1 i=5, res=1 i=6, res=1 i=7, res=1 i=8, res=1 i=9, res=1 i=10, res=1 i=11, res=1 i=12, res=1 i=13, res=1 i=14, res=1 i=15, res=1 i=16, res=1 i=17, res=1 i=18, res=1 i=19, res=1 i=20, res=1 i=21, res=1 i=22, res=1 i=23, res=1 i=24, res=1 i=25, res=1 i=26, res=1 i=27, res=1 i=28, res=1 i=29, res=1 i=30, res=1 i=31, res=1 i=32, res=1 i=33, res=1 i=34, res=1 i=35, res=1 i=36, res=1 i=37, res=1 i=38, res=1 i=39, res=1 i=40, res=1 i=41, res=1 i=42, res=1 i=43, res=1 i=44, res=1 i=45, res=1 i=46, res=1 i=47, res=1 i=48, res=1 i=49, res=1 i=50, res=1 i=51, res=1 i=52, res=1 i=53, res=1 i=54, res=1 i=55, res=1 i=56, res=1 i=57, res=1 i=58, res=1 i=59, res=1 i=60, res=1 i=61, res=1 i=62, res=1 i=63, res=1 i=64, res=1 i=65, res=1 i=66, res=1 i=67, res=1 i=68, res=1 i=69, res=1 i=70, res=1 i=71, res=1 i=72, res=1 i=73, res=1 i=74, res=1 i=75, res=1 i=76, res=1 i=77, res=1 i=78, res=1 i=79, res=1 i=80, res=1 i=81, res=1 i=82, res=1 i=83, res=1 i=84, res=1 i=85, res=1 i=86, res=1 i=87, res=1 i=88, res=1 i=89, res=1 i=90, res=1 i=91, res=1 i=92, res=1 i=93, res=1 i=94, res=1 i=95, res=1 i=96, res=1 i=97, res=1 i=98, res=1 i=99, res=1 i=100, res=1 i=101, res=1 i=102, res=1 i=103, res=1 i=104, res=1 i=105, res=1 i=106, res=1 i=107, res=1 i=108, res=1 i=109, res=1 i=110, res=1 i=111, res=1 i=112, res=1 i=113, res=1 i=114, res=1 i=115, res=1 i=116, res=1 i=117, res=1 i=118, res=1 i=119, res=1 i=120, res=1 i=121, res=1 i=122, res=1 i=123, res=1 i=124, res=1 i=125, res=1 i=126, res=1 i=127, res=1 i=128, res=TypeError: invalid call args i=129, res=TypeError: invalid call args i=130, res=TypeError: invalid call args i=131, res=TypeError: invalid call args i=132, res=TypeError: invalid call args i=133, res=TypeError: invalid call args i=134, res=TypeError: invalid call args i=135, res=TypeError: invalid call args i=136, res=TypeError: invalid call args i=137, res=TypeError: invalid call args i=138, res=TypeError: invalid call args i=139, res=TypeError: invalid call args i=140, res=TypeError: invalid call args i=141, res=TypeError: invalid call args i=142, res=TypeError: invalid call args i=143, res=TypeError: invalid call args i=144, res=TypeError: invalid call args i=145, res=TypeError: invalid call args i=146, res=TypeError: invalid call args i=147, res=TypeError: invalid call args i=148, res=TypeError: invalid call args i=149, res=TypeError: invalid call args i=150, res=TypeError: invalid call args i=151, res=TypeError: invalid call args i=152, res=TypeError: invalid call args i=153, res=TypeError: invalid call args i=154, res=TypeError: invalid call args i=155, res=TypeError: invalid call args i=156, res=TypeError: invalid call args i=157, res=TypeError: invalid call args i=158, res=TypeError: invalid call args i=159, res=TypeError: invalid call args i=160, res=TypeError: invalid call args i=161, res=TypeError: invalid call args i=162, res=TypeError: invalid call args i=163, res=TypeError: invalid call args i=164, res=TypeError: invalid call args i=165, res=TypeError: invalid call args i=166, res=TypeError: invalid call args i=167, res=TypeError: invalid call args i=168, res=TypeError: invalid call args i=169, res=TypeError: invalid call args i=170, res=TypeError: invalid call args i=171, res=TypeError: invalid call args i=172, res=TypeError: invalid call args i=173, res=TypeError: invalid call args i=174, res=TypeError: invalid call args i=175, res=TypeError: invalid call args i=176, res=TypeError: invalid call args i=177, res=TypeError: invalid call args i=178, res=TypeError: invalid call args i=179, res=TypeError: invalid call args i=180, res=TypeError: invalid call args i=181, res=TypeError: invalid call args i=182, res=TypeError: invalid call args i=183, res=TypeError: invalid call args i=184, res=TypeError: invalid call args i=185, res=TypeError: invalid call args i=186, res=TypeError: invalid call args i=187, res=TypeError: invalid call args i=188, res=TypeError: invalid call args i=189, res=TypeError: invalid call args i=190, res=TypeError: invalid call args i=191, res=TypeError: invalid call args i=192, res=TypeError: invalid call args i=193, res=TypeError: invalid call args i=194, res=TypeError: invalid call args i=195, res=TypeError: invalid call args i=196, res=TypeError: invalid call args i=197, res=TypeError: invalid call args i=198, res=TypeError: invalid call args i=199, res=TypeError: invalid call args i=200, res=TypeError: invalid call args i=201, res=TypeError: invalid call args i=202, res=TypeError: invalid call args i=203, res=TypeError: invalid call args i=204, res=TypeError: invalid call args i=205, res=TypeError: invalid call args i=206, res=TypeError: invalid call args i=207, res=TypeError: invalid call args i=208, res=TypeError: invalid call args i=209, res=TypeError: invalid call args i=210, res=TypeError: invalid call args i=211, res=TypeError: invalid call args i=212, res=TypeError: invalid call args i=213, res=TypeError: invalid call args i=214, res=TypeError: invalid call args i=215, res=TypeError: invalid call args i=216, res=TypeError: invalid call args i=217, res=TypeError: invalid call args i=218, res=TypeError: invalid call args i=219, res=TypeError: invalid call args i=220, res=TypeError: invalid call args i=221, res=TypeError: invalid call args i=222, res=TypeError: invalid call args i=223, res=TypeError: invalid call args i=224, res=TypeError: invalid call args i=225, res=TypeError: invalid call args i=226, res=TypeError: invalid call args i=227, res=TypeError: invalid call args i=228, res=TypeError: invalid call args i=229, res=TypeError: invalid call args i=230, res=TypeError: invalid call args i=231, res=TypeError: invalid call args i=232, res=TypeError: invalid call args i=233, res=TypeError: invalid call args i=234, res=TypeError: invalid call args i=235, res=TypeError: invalid call args i=236, res=TypeError: invalid call args i=237, res=TypeError: invalid call args i=238, res=TypeError: invalid call args i=239, res=TypeError: invalid call args i=240, res=TypeError: invalid call args i=241, res=TypeError: invalid call args i=242, res=TypeError: invalid call args i=243, res=TypeError: invalid call args i=244, res=TypeError: invalid call args i=245, res=TypeError: invalid call args i=246, res=TypeError: invalid call args i=247, res=TypeError: invalid call args i=248, res=TypeError: invalid call args i=249, res=TypeError: invalid call args i=250, res=TypeError: invalid call args i=251, res=TypeError: invalid call args i=252, res=TypeError: invalid call args i=253, res=TypeError: invalid call args i=254, res=TypeError: invalid call args i=255, res=TypeError: invalid call args i=256, res=TypeError: invalid call args ==> rc=0, result='undefined' ===*/ static duk_ret_t test_magic_raw(duk_context *ctx, void *udata) { int i = duk_require_int(ctx, -1); duk_idx_t ret; (void) udata; ret = duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, i /*magic*/); duk_push_int(ctx, (duk_int_t) ret); return 1; } static duk_ret_t test_magic(duk_context *ctx, void *udata) { int i; (void) udata; for (i = -256; i <= 256; i++) { duk_push_int(ctx, i); duk_safe_call(ctx, test_magic_raw, NULL, 1, 1); printf("i=%ld, res=%s\n", (long) i, duk_safe_to_string(ctx, -1)); duk_pop(ctx); } return 0; } /*=== *** test_length_values (duk_safe_call) i=-16, res=TypeError: invalid call args i=-15, res=TypeError: invalid call args i=-14, res=TypeError: invalid call args i=-13, res=TypeError: invalid call args i=-12, res=TypeError: invalid call args i=-11, res=TypeError: invalid call args i=-10, res=TypeError: invalid call args i=-9, res=TypeError: invalid call args i=-8, res=TypeError: invalid call args i=-7, res=TypeError: invalid call args i=-6, res=TypeError: invalid call args i=-5, res=TypeError: invalid call args i=-4, res=TypeError: invalid call args i=-3, res=TypeError: invalid call args i=-2, res=TypeError: invalid call args i=-1, res=TypeError: invalid call args i=0, res=1 i=1, res=1 i=2, res=1 i=3, res=1 i=4, res=1 i=5, res=1 i=6, res=1 i=7, res=1 i=8, res=1 i=9, res=1 i=10, res=1 i=11, res=1 i=12, res=1 i=13, res=1 i=14, res=1 i=15, res=1 i=16, res=TypeError: invalid call args ==> rc=0, result='undefined' ===*/ static duk_ret_t test_length_raw(duk_context *ctx, void *udata) { int i = duk_require_int(ctx, -1); duk_idx_t ret; (void) udata; ret = duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, i /*length*/, 0x42 /*magic*/); duk_push_int(ctx, (duk_int_t) ret); return 1; } static duk_ret_t test_length_values(duk_context *ctx, void *udata) { int i; (void) udata; for (i = -16; i <= 16; i++) { duk_push_int(ctx, i); duk_safe_call(ctx, test_length_raw, NULL, 1, 1); printf("i=%ld, res=%s\n", (long) i, duk_safe_to_string(ctx, -1)); duk_pop(ctx); } return 0; } /*=== *** test_nargs_values (duk_safe_call) i=-16, nargs=-16, res=TypeError: invalid call args i=-15, nargs=-15, res=TypeError: invalid call args i=-14, nargs=-14, res=TypeError: invalid call args i=-13, nargs=-13, res=TypeError: invalid call args i=-12, nargs=-12, res=TypeError: invalid call args i=-11, nargs=-11, res=TypeError: invalid call args i=-10, nargs=-10, res=TypeError: invalid call args i=-9, nargs=-9, res=TypeError: invalid call args i=-8, nargs=-8, res=TypeError: invalid call args i=-7, nargs=-7, res=TypeError: invalid call args i=-6, nargs=-6, res=TypeError: invalid call args i=-5, nargs=-5, res=TypeError: invalid call args i=-4, nargs=-4, res=TypeError: invalid call args i=-3, nargs=-3, res=TypeError: invalid call args i=-2, nargs=-2, res=TypeError: invalid call args i=-1, nargs=-1 (varargs), res=1 i=0, nargs=0, res=1 i=1, nargs=1, res=1 i=2, nargs=2, res=1 i=3, nargs=3, res=1 i=4, nargs=4, res=1 i=5, nargs=5, res=1 i=6, nargs=6, res=1 i=7, nargs=7, res=1 i=8, nargs=8, res=1 i=9, nargs=9, res=1 i=10, nargs=10, res=1 i=11, nargs=11, res=1 i=12, nargs=12, res=1 i=13, nargs=13, res=1 i=14, nargs=14, res=1 i=15, nargs=15, res=TypeError: invalid call args i=16, nargs=16, res=TypeError: invalid call args i=17, nargs=-1 (varargs), res=1 i=18, nargs=18, res=TypeError: invalid call args ==> rc=0, result='undefined' ===*/ static duk_ret_t test_nargs_raw(duk_context *ctx, void *udata) { int i = duk_require_int(ctx, -1); duk_idx_t ret; (void) udata; ret = duk_push_c_lightfunc(ctx, my_addtwo_lfunc, i /*nargs*/, 2 /*length*/, 0x42 /*magic*/); duk_push_int(ctx, (duk_int_t) ret); return 1; } static duk_ret_t test_nargs_values(duk_context *ctx, void *udata) { int i; int nargs; int is_vararg; (void) udata; for (i = -16; i <= 18; i++) { if (i == 17) { duk_push_int(ctx, DUK_VARARGS); } else { duk_push_int(ctx, i); } nargs = duk_get_int(ctx, -1); is_vararg = (nargs == DUK_VARARGS); duk_safe_call(ctx, test_nargs_raw, NULL, 1, 1); printf("i=%ld, nargs=%ld%s, res=%s\n", (long) i, (long) nargs, (is_vararg ? " (varargs)" : ""), duk_safe_to_string(ctx, -1)); duk_pop(ctx); } return 0; } /*=== *** test_enum (duk_safe_call) enum defaults top: 1 enum nonenumerable key: length key: name key: constructor key: toString key: apply key: call key: bind key: __proto__ key: toLocaleString key: valueOf key: hasOwnProperty key: isPrototypeOf key: propertyIsEnumerable top: 1 enum own top: 1 enum own non-enumerable key: length key: name top: 1 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_enum(duk_context *ctx, void *udata) { (void) udata; (void) duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, 0x42 /*magic*/); printf("enum defaults\n"); duk_enum(ctx, -1, 0); while (duk_next(ctx, -1, 0 /*get_value*/)) { printf("key: %s\n", duk_to_string(ctx, -1)); duk_pop(ctx); } duk_pop(ctx); printf("top: %ld\n", (long) duk_get_top(ctx)); printf("enum nonenumerable\n"); duk_enum(ctx, -1, DUK_ENUM_INCLUDE_NONENUMERABLE); while (duk_next(ctx, -1, 0 /*get_value*/)) { printf("key: %s\n", duk_to_string(ctx, -1)); duk_pop(ctx); } duk_pop(ctx); printf("top: %ld\n", (long) duk_get_top(ctx)); printf("enum own\n"); duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY); while (duk_next(ctx, -1, 0 /*get_value*/)) { printf("key: %s\n", duk_to_string(ctx, -1)); duk_pop(ctx); } duk_pop(ctx); printf("top: %ld\n", (long) duk_get_top(ctx)); printf("enum own non-enumerable\n"); duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY | DUK_ENUM_INCLUDE_NONENUMERABLE); while (duk_next(ctx, -1, 0 /*get_value*/)) { printf("key: %s\n", duk_to_string(ctx, -1)); duk_pop(ctx); } duk_pop(ctx); printf("top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_get_length (duk_safe_call) lightFunc len: 3 ecmaFunc.len: 3 final top: 2 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_get_length(duk_context *ctx, void *udata) { duk_size_t len; (void) udata; /* * Lightfunc length is its virtual 'length' property, same as for * ordinary functions. */ (void) duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, 0x42 /*magic*/); len = duk_get_length(ctx, -1); printf("lightFunc len: %ld\n", (long) len); duk_eval_string(ctx, "(function (a,b,c) {})"); len = duk_get_length(ctx, -1); printf("ecmaFunc.len: %ld\n", (long) len); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_to_object (duk_safe_call) tag before: 9 tag after: 6 addtwo entry top: 2 addtwo 'length' property: 3 addtwo duk_get_length: 3 addtwo magic: 66 current magic: 66 addtwo final top: 3 result: 357 final top: 1 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_to_object(duk_context *ctx, void *udata) { (void) udata; (void) duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, 0x42 /*magic*/); printf("tag before: %ld\n", (long) duk_get_type(ctx, -1)); duk_to_object(ctx, -1); printf("tag after: %ld\n", (long) duk_get_type(ctx, -1)); /* The coerced function works as before */ duk_push_int(ctx, 123); duk_push_int(ctx, 234); duk_push_int(ctx, 345); duk_call(ctx, 3); printf("result: %s\n", duk_safe_to_string(ctx, -1)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_to_buffer (duk_safe_call) function light_PTR_4232() {"light"} final top: 1 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_to_buffer(duk_context *ctx, void *udata) { duk_size_t sz; unsigned char *p; (void) udata; (void) duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, 0x42 /*magic*/); /* * Lightfunc-to-buffer coercion currently produces a string: the * lightfunc gets coerced to a string like a normal function would. * The buffer is then filled with the bytes from this coercion. * * The output must be sanitized because it is platform specific. */ p = (unsigned char *) duk_to_buffer(ctx, -1, &sz); if (!p) { printf("ptr is NULL\n"); } else { /* Don't print length because it depends on pointer length * and thus architecture. */ #if 0 printf("%ld: ", (long) sz); #endif /* Sanitize with Ecmascript because it's easier... */ duk_eval_string(ctx, "(function (x) { return String(x)" ".replace(/\\/\\*/g, '(*').replace(/\\*\\//g, '*)')" ".replace(/light_[0-9a-fA-F]+_/g, 'light_PTR_'); })"); duk_dup(ctx, -2); duk_call(ctx, 1); printf("%s\n", duk_safe_to_string(ctx, -1)); duk_pop(ctx); /* pop temp */ } printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_to_pointer (duk_safe_call) ptr is NULL: 1 final top: 1 ==> rc=0, result='undefined' ===*/ static duk_ret_t test_to_pointer(duk_context *ctx, void *udata) { void *p; (void) udata; (void) duk_push_c_lightfunc(ctx, my_addtwo_lfunc, 2 /*nargs*/, 3 /*length*/, 0x42 /*magic*/); /* * Lightfunc-to-pointer coercion currently produces a NULL: there is * no portable way to cast a function pointer to a data pointer, as * there may be segmentation etc involved. This could be improved to * work on specific platforms. */ p = duk_to_pointer(ctx, -1); printf("ptr is NULL: %d\n", (int) (p == NULL ? 1 : 0)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_is_primitive (duk_safe_call) is_primitive: 1 final top: 1 ==> rc=0, result='undefined' ===*/ /* Because lightfuncs have their own type tag in the C API, they're considered * a primitive type like plain buffers and pointers. This is also sensible * because duk_is_object() is 0 for lightfuncs. */ static duk_ret_t test_is_primitive(duk_context *ctx, void *udata) { (void) udata; duk_push_c_lightfunc(ctx, my_dummy_func, 0, 0, 0); printf("is_primitive: %ld\n", (long) duk_is_primitive(ctx, -1)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_is_object (duk_safe_call) is_object: 0 final top: 1 ==> rc=0, result='undefined' ===*/ /* Lightfuncs are not objects (they're primitive). */ static duk_ret_t test_is_object(duk_context *ctx, void *udata) { (void) udata; duk_push_c_lightfunc(ctx, my_dummy_func, 0, 0, 0); printf("is_object: %ld\n", (long) duk_is_object(ctx, -1)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== *** test_is_object_coercible (duk_safe_call) is_object_coercible: 1 final top: 1 ==> rc=0, result='undefined' ===*/ /* Lightfuncs are object coercible. */ static duk_ret_t test_is_object_coercible(duk_context *ctx, void *udata) { (void) udata; duk_push_c_lightfunc(ctx, my_dummy_func, 0, 0, 0); printf("is_object_coercible: %ld\n", (long) duk_is_object_coercible(ctx, -1)); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } /*=== still here ===*/ void test(duk_context *ctx) { /* nargs / length limits, C api test, check what happens if you exceed */ /* Example of using lightfunc as a constructor, separate testcase, doc ref */ TEST_SAFE_CALL(test_is_lightfunc); TEST_SAFE_CALL(test_simple_push); TEST_SAFE_CALL(test_magic); TEST_SAFE_CALL(test_length_values); TEST_SAFE_CALL(test_nargs_values); TEST_SAFE_CALL(test_enum); TEST_SAFE_CALL(test_get_length); TEST_SAFE_CALL(test_to_object); TEST_SAFE_CALL(test_to_buffer); TEST_SAFE_CALL(test_to_pointer); TEST_SAFE_CALL(test_is_primitive); TEST_SAFE_CALL(test_is_object); TEST_SAFE_CALL(test_is_object_coercible); printf("still here\n"); fflush(stdout); }
25.777064
94
0.696943
[ "object" ]
f015f8d958f6f1f552bca476bb10bdad3b75759b
751
h
C
src/gobject-intro/myapp-teacher.h
j1elo/curso-desarrollador-kurento
02ee43c7ddb0f9c8e9f4ea19af5a903a1720895e
[ "MIT" ]
4
2019-07-16T08:37:03.000Z
2019-07-25T10:31:04.000Z
src/gobject-intro/myapp-teacher.h
j1elo/curso-desarrollador-kurento
02ee43c7ddb0f9c8e9f4ea19af5a903a1720895e
[ "MIT" ]
null
null
null
src/gobject-intro/myapp-teacher.h
j1elo/curso-desarrollador-kurento
02ee43c7ddb0f9c8e9f4ea19af5a903a1720895e
[ "MIT" ]
null
null
null
#ifndef MYAPP_TEACHER_H #define MYAPP_TEACHER_H #include "myapp-person.h" #include <glib-object.h> G_BEGIN_DECLS // ---------------------------------------------------------------------------- /* Class public declaration * ======================== */ // GType macro convention: <PREFIX>_TYPE_<CLASS> #define MYAPP_TYPE_TEACHER myapp_teacher_get_type() G_DECLARE_DERIVABLE_TYPE(MyappTeacher, myapp_teacher, MYAPP, TEACHER, MyappPerson) struct _MyappTeacherClass { MyappPersonClass parent_class; }; // ---------------------------------------------------------------------------- /* Class methods * ============= */ // ---------------------------------------------------------------------------- G_END_DECLS #endif // MYAPP_TEACHER_H
21.457143
82
0.484687
[ "object" ]
f01689f4a879f59ad250a9200a4e66b0493426d8
65,113
c
C
tool/yubico-piv-tool.c
Yubico/yubico-piv-tool-dpkg
27c6318e8e704ac0b618f8d6e33a298d79a1132b
[ "BSD-2-Clause" ]
12
2015-10-16T06:57:21.000Z
2021-11-16T21:22:43.000Z
tool/yubico-piv-tool.c
Yubico/yubico-piv-tool-dpkg
27c6318e8e704ac0b618f8d6e33a298d79a1132b
[ "BSD-2-Clause" ]
7
2015-03-30T21:28:45.000Z
2016-09-02T07:13:28.000Z
tool/yubico-piv-tool.c
Yubico/yubico-piv-tool-dpkg
27c6318e8e704ac0b618f8d6e33a298d79a1132b
[ "BSD-2-Clause" ]
12
2015-03-30T20:59:32.000Z
2021-11-16T21:22:34.000Z
/* * Copyright (c) 2014-2016 Yubico AB * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "ykpiv.h" #ifdef _WIN32 #include <windows.h> #endif #include <openssl/des.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/rand.h> #include "cmdline.h" #include "util.h" /* FASC-N containing S9999F9999F999999F0F1F0000000000300001E encoded in * 4-bit BCD with 1 bit parity. run through the tools/fasc.pl script to get * bytes. */ /* this CHUID has an expiry of 2030-01-01, maybe that should be variable.. */ unsigned const char chuid_tmpl[] = { 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, 0x83, 0x68, 0x58, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0x38, 0x42, 0x10, 0xc3, 0xf5, 0x34, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x08, 0x32, 0x30, 0x33, 0x30, 0x30, 0x31, 0x30, 0x31, 0x3e, 0x00, 0xfe, 0x00, }; #define CHUID_GUID_OFFS 29 unsigned const char ccc_tmpl[] = { 0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x21, 0xf2, 0x01, 0x21, 0xf3, 0x00, 0xf4, 0x01, 0x00, 0xf5, 0x01, 0x10, 0xf6, 0x00, 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd, 0x00, 0xfe, 0x00 }; #define CCC_ID_OFFS 9 #define CHUID 0 #define CCC 1 #define MAX_OID_LEN 19 #define KEY_LEN 24 static void print_version(ykpiv_state *state, const char *output_file_name) { char version[7]; FILE *output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return; } if(ykpiv_get_version(state, version, sizeof(version)) == YKPIV_OK) { fprintf(output_file, "Application version %s found.\n", version); } else { fprintf(stderr, "Failed to retrieve application version.\n"); } if(output_file != stdout) { fclose(output_file); } } static bool sign_data(ykpiv_state *state, const unsigned char *in, size_t len, unsigned char *out, size_t *out_len, unsigned char algorithm, int key) { unsigned char signinput[1024]; if(YKPIV_IS_RSA(algorithm)) { size_t padlen = algorithm == YKPIV_ALGO_RSA1024 ? 128 : 256; if(RSA_padding_add_PKCS1_type_1(signinput, padlen, in, len) == 0) { fprintf(stderr, "Failed adding padding.\n"); return false; } in = signinput; len = padlen; } if(ykpiv_sign_data(state, in, len, out, out_len, algorithm, key) == YKPIV_OK) { return true; } return false; } static bool generate_key(ykpiv_state *state, const char *slot, enum enum_algorithm algorithm, const char *output_file_name, enum enum_key_format key_format, enum enum_pin_policy pin_policy, enum enum_touch_policy touch_policy) { unsigned char in_data[11]; unsigned char *in_ptr = in_data; unsigned char data[1024]; unsigned char templ[] = {0, YKPIV_INS_GENERATE_ASYMMETRIC, 0, 0}; unsigned long recv_len = sizeof(data); int sw; int key = 0; FILE *output_file = NULL; bool ret = false; EVP_PKEY *public_key = NULL; RSA *rsa = NULL; BIGNUM *bignum_n = NULL; BIGNUM *bignum_e = NULL; EC_KEY *eckey = NULL; EC_POINT *point = NULL; sscanf(slot, "%2x", &key); templ[3] = key; output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } *in_ptr++ = 0xac; *in_ptr++ = 3; *in_ptr++ = YKPIV_ALGO_TAG; *in_ptr++ = 1; *in_ptr++ = get_piv_algorithm(algorithm); if(in_data[4] == 0) { fprintf(stderr, "Unexpected algorithm.\n"); goto generate_out; } if(pin_policy != pin_policy__NULL) { in_data[1] += 3; *in_ptr++ = YKPIV_PINPOLICY_TAG; *in_ptr++ = 1; *in_ptr++ = get_pin_policy(pin_policy); } if(touch_policy != touch_policy__NULL) { in_data[1] += 3; *in_ptr++ = YKPIV_TOUCHPOLICY_TAG; *in_ptr++ = 1; *in_ptr++ = get_touch_policy(touch_policy); } if(ykpiv_transfer_data(state, templ, in_data, in_ptr - in_data, data, &recv_len, &sw) != YKPIV_OK) { fprintf(stderr, "Failed to communicate.\n"); goto generate_out; } else if(sw != SW_SUCCESS) { fprintf(stderr, "Failed to generate new key ("); if(sw == SW_ERR_INCORRECT_SLOT) { fprintf(stderr, "slot not supported?)\n"); } else if(sw == SW_ERR_INCORRECT_PARAM) { if(pin_policy != pin_policy__NULL) { fprintf(stderr, "pin policy not supported?)\n"); } else if(touch_policy != touch_policy__NULL) { fprintf(stderr, "touch policy not supported?)\n"); } else { fprintf(stderr, "algorithm not supported?)\n"); } } else { fprintf(stderr, "error %x)\n", sw); } goto generate_out; } if(key_format == key_format_arg_PEM) { public_key = EVP_PKEY_new(); if(algorithm == algorithm_arg_RSA1024 || algorithm == algorithm_arg_RSA2048) { unsigned char *data_ptr = data + 5; int len = 0; rsa = RSA_new(); if(*data_ptr != 0x81) { fprintf(stderr, "Failed to parse public key structure.\n"); goto generate_out; } data_ptr++; data_ptr += get_length(data_ptr, &len); bignum_n = BN_bin2bn(data_ptr, len, NULL); if(bignum_n == NULL) { fprintf(stderr, "Failed to parse public key modulus.\n"); goto generate_out; } data_ptr += len; if(*data_ptr != 0x82) { fprintf(stderr, "Failed to parse public key structure (2).\n"); goto generate_out; } data_ptr++; data_ptr += get_length(data_ptr, &len); bignum_e = BN_bin2bn(data_ptr, len, NULL); if(bignum_e == NULL) { fprintf(stderr, "Failed to parse public key exponent.\n"); goto generate_out; } rsa->n = bignum_n; rsa->e = bignum_e; EVP_PKEY_set1_RSA(public_key, rsa); } else if(algorithm == algorithm_arg_ECCP256 || algorithm == algorithm_arg_ECCP384) { EC_GROUP *group; unsigned char *data_ptr = data + 3; int nid; size_t len; if(algorithm == algorithm_arg_ECCP256) { nid = NID_X9_62_prime256v1; len = 65; } else { nid = NID_secp384r1; len = 97; } eckey = EC_KEY_new(); group = EC_GROUP_new_by_curve_name(nid); EC_GROUP_set_asn1_flag(group, nid); EC_KEY_set_group(eckey, group); point = EC_POINT_new(group); if(*data_ptr++ != 0x86) { fprintf(stderr, "Failed to parse public key structure.\n"); goto generate_out; } if(*data_ptr++ != len) { /* the curve point should always be 65 bytes */ fprintf(stderr, "Unexpected length.\n"); goto generate_out; } if(!EC_POINT_oct2point(group, point, data_ptr, len, NULL)) { fprintf(stderr, "Failed to load public point.\n"); goto generate_out; } if(!EC_KEY_set_public_key(eckey, point)) { fprintf(stderr, "Failed to set the public key.\n"); goto generate_out; } EVP_PKEY_set1_EC_KEY(public_key, eckey); } else { fprintf(stderr, "Wrong algorithm.\n"); goto generate_out; } PEM_write_PUBKEY(output_file, public_key); ret = true; } else { fprintf(stderr, "Only PEM is supported as public_key output.\n"); goto generate_out; } generate_out: if(output_file != stdout) { fclose(output_file); } if(point) { EC_POINT_free(point); } if(eckey) { EC_KEY_free(eckey); } if(rsa) { RSA_free(rsa); } if(public_key) { EVP_PKEY_free(public_key); } return ret; } static bool reset(ykpiv_state *state) { unsigned char templ[] = {0, YKPIV_INS_RESET, 0, 0}; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); int sw; /* note: the reset function is only available when both pins are blocked. */ if(ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw) != YKPIV_OK) { return false; } else if(sw == SW_SUCCESS) { return true; } return false; } static bool set_pin_retries(ykpiv_state *state, int pin_retries, int puk_retries, int verbose) { unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, pin_retries, puk_retries}; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); int sw; if(pin_retries > 0xff || puk_retries > 0xff || pin_retries < 1 || puk_retries < 1) { fprintf(stderr, "pin and puk retries must be between 1 and 255.\n"); return false; } if(verbose) { fprintf(stderr, "Setting pin retries to %d and puk retries to %d.\n", pin_retries, puk_retries); } if(ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw) != YKPIV_OK) { return false; } else if(sw == SW_SUCCESS) { return true; } return false; } static bool import_key(ykpiv_state *state, enum enum_key_format key_format, const char *input_file_name, const char *slot, char *password, enum enum_pin_policy pin_policy, enum enum_touch_policy touch_policy) { int key = 0; FILE *input_file = NULL; EVP_PKEY *private_key = NULL; PKCS12 *p12 = NULL; X509 *cert = NULL; bool ret = false; ykpiv_rc rc = YKPIV_GENERIC_ERROR; sscanf(slot, "%2x", &key); input_file = open_file(input_file_name, INPUT); if(!input_file) { return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the private key...\n"); } if(key_format == key_format_arg_PEM) { private_key = PEM_read_PrivateKey(input_file, NULL, NULL, password); if(!private_key) { fprintf(stderr, "Failed loading private key for import.\n"); goto import_out; } } else if(key_format == key_format_arg_PKCS12) { p12 = d2i_PKCS12_fp(input_file, NULL); if(!p12) { fprintf(stderr, "Failed to load PKCS12 from file.\n"); goto import_out; } if(PKCS12_parse(p12, password, &private_key, &cert, NULL) == 0) { fprintf(stderr, "Failed to parse PKCS12 structure. (wrong password?)\n"); goto import_out; } } else { /* TODO: more formats go here */ fprintf(stderr, "Unknown key format.\n"); goto import_out; } { unsigned char algorithm = get_algorithm(private_key); unsigned char pp = YKPIV_PINPOLICY_DEFAULT; unsigned char tp = YKPIV_TOUCHPOLICY_DEFAULT; if(algorithm == 0) { goto import_out; } if(pin_policy != pin_policy__NULL) { pp = get_pin_policy(pin_policy); } if(touch_policy != touch_policy__NULL) { tp = get_touch_policy(touch_policy); } if(YKPIV_IS_RSA(algorithm)) { RSA *rsa_private_key = EVP_PKEY_get1_RSA(private_key); unsigned char e[4]; unsigned char p[128]; unsigned char q[128]; unsigned char dmp1[128]; unsigned char dmq1[128]; unsigned char iqmp[128]; int element_len = 128; if(algorithm == YKPIV_ALGO_RSA1024) { element_len = 64; } if((set_component(e, rsa_private_key->e, 3) == false) || !(e[0] == 0x01 && e[1] == 0x00 && e[2] == 0x01)) { fprintf(stderr, "Invalid public exponent for import (only 0x10001 supported)\n"); goto import_out; } if(set_component(p, rsa_private_key->p, element_len) == false) { fprintf(stderr, "Failed setting p component.\n"); goto import_out; } if(set_component(q, rsa_private_key->q, element_len) == false) { fprintf(stderr, "Failed setting q component.\n"); goto import_out; } if(set_component(dmp1, rsa_private_key->dmp1, element_len) == false) { fprintf(stderr, "Failed setting dmp1 component.\n"); goto import_out; } if(set_component(dmq1, rsa_private_key->dmq1, element_len) == false) { fprintf(stderr, "Failed setting dmq1 component.\n"); goto import_out; } if(set_component(iqmp, rsa_private_key->iqmp, element_len) == false) { fprintf(stderr, "Failed setting iqmp component.\n"); goto import_out; } rc = ykpiv_import_private_key(state, key, algorithm, p, element_len, q, element_len, dmp1, element_len, dmq1, element_len, iqmp, element_len, NULL, 0, pp, tp); } else if(YKPIV_IS_EC(algorithm)) { EC_KEY *ec = EVP_PKEY_get1_EC_KEY(private_key); const BIGNUM *s = EC_KEY_get0_private_key(ec); unsigned char s_ptr[48]; int element_len = 32; if(algorithm == YKPIV_ALGO_ECCP384) { element_len = 48; } if(set_component(s_ptr, s, element_len) == false) { fprintf(stderr, "Failed setting ec private key.\n"); goto import_out; } rc = ykpiv_import_private_key(state, key, algorithm, NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, s_ptr, element_len, pp, tp); } ret = true; if(rc != YKPIV_OK) { ret = false; } } import_out: if(private_key) { EVP_PKEY_free(private_key); } if(p12) { PKCS12_free(p12); } if(cert) { X509_free(cert); } if(input_file != stdin) { fclose(input_file); } return ret; } static bool import_cert(ykpiv_state *state, enum enum_key_format cert_format, const char *input_file_name, enum enum_slot slot, char *password) { bool ret = false; FILE *input_file = NULL; X509 *cert = NULL; PKCS12 *p12 = NULL; EVP_PKEY *private_key = NULL; int compress = 0; int cert_len = -1; input_file = open_file(input_file_name, INPUT); if(!input_file) { return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the certificate...\n"); } if(cert_format == key_format_arg_PEM) { cert = PEM_read_X509(input_file, NULL, NULL, password); if(!cert) { fprintf(stderr, "Failed loading certificate for import.\n"); goto import_cert_out; } } else if(cert_format == key_format_arg_DER) { cert = d2i_X509_fp(input_file, NULL); if(!cert) { fprintf(stderr, "Failed loading certificate for import.\n"); goto import_cert_out; } } else if(cert_format == key_format_arg_PKCS12) { p12 = d2i_PKCS12_fp(input_file, NULL); if(!p12) { fprintf(stderr, "Failed to load PKCS12 from file.\n"); goto import_cert_out; } if(!PKCS12_parse(p12, password, &private_key, &cert, NULL)) { fprintf(stderr, "Failed to parse PKCS12 structure.\n"); goto import_cert_out; } } else if (cert_format == key_format_arg_GZIP) { struct stat st; if(fstat(fileno(input_file), &st) == -1) { fprintf(stderr, "Failed checking input GZIP file.\n"); goto import_cert_out; } cert_len = st.st_size; compress = 0x01; } else { /* TODO: more formats go here */ fprintf(stderr, "Unknown key format.\n"); goto import_cert_out; } if(cert_len == -1) { cert_len = i2d_X509(cert, NULL); } { unsigned char certdata[3072]; unsigned char *certptr = certdata; int object = get_object_id(slot); ykpiv_rc res; if(4 + cert_len + 5 > sizeof(certdata)) { /* 4 is prefix size, 5 is postfix size */ fprintf(stderr, "Certificate is too large to fit in buffer.\n"); goto import_cert_out; } *certptr++ = 0x70; certptr += set_length(certptr, cert_len); if (compress) { if (fread(certptr, 1, (size_t)cert_len, input_file) != (size_t)cert_len) { fprintf(stderr, "Failed to read compressed certificate\n"); goto import_cert_out; } certptr += cert_len; } else { /* i2d_X509 increments certptr here.. */ i2d_X509(cert, &certptr); } *certptr++ = 0x71; *certptr++ = 1; *certptr++ = compress; /* certinfo (gzip etc) */ *certptr++ = 0xfe; /* LRC */ *certptr++ = 0; if((res = ykpiv_save_object(state, object, certdata, (size_t)(certptr - certdata))) != YKPIV_OK) { fprintf(stderr, "Failed commands with device: %s\n", ykpiv_strerror(res)); } else { ret = true; } } import_cert_out: if(cert) { X509_free(cert); } if(input_file != stdin) { fclose(input_file); } if(p12) { PKCS12_free(p12); } if(private_key) { EVP_PKEY_free(private_key); } return ret; } static bool set_dataobject(ykpiv_state *state, int verbose, int type) { unsigned char obj[1024]; ykpiv_rc res; size_t offs, rand_len, len; const unsigned char *tmpl; int id; if(type == CHUID) { offs = CHUID_GUID_OFFS; len = sizeof(chuid_tmpl); rand_len = 0x10; tmpl = chuid_tmpl; id = YKPIV_OBJ_CHUID; } else { offs = CCC_ID_OFFS; rand_len = 0xe; len = sizeof(ccc_tmpl); tmpl = ccc_tmpl; id = YKPIV_OBJ_CAPABILITY; } memcpy(obj, tmpl, len); if(RAND_pseudo_bytes(obj + offs, rand_len) == -1) { fprintf(stderr, "error: no randomness.\n"); return false; } if(verbose) { fprintf(stderr, "Setting the %s to: ", type == CHUID ? "CHUID" : "CCC"); dump_data(obj, len, stderr, true, format_arg_hex); } if((res = ykpiv_save_object(state, id, obj, len)) != YKPIV_OK) { fprintf(stderr, "Failed communicating with device: %s\n", ykpiv_strerror(res)); return false; } return true; } static bool request_certificate(ykpiv_state *state, enum enum_key_format key_format, const char *input_file_name, const char *slot, char *subject, enum enum_hash hash, const char *output_file_name) { X509_REQ *req = NULL; X509_NAME *name = NULL; FILE *input_file = NULL; FILE *output_file = NULL; EVP_PKEY *public_key = NULL; const EVP_MD *md; bool ret = false; unsigned char digest[EVP_MAX_MD_SIZE + MAX_OID_LEN]; unsigned int digest_len; unsigned int md_len; unsigned char algorithm; int key = 0; unsigned char *signinput; size_t len = 0; size_t oid_len; const unsigned char *oid; int nid; sscanf(slot, "%2x", &key); input_file = open_file(input_file_name, INPUT); output_file = open_file(output_file_name, OUTPUT); if(!input_file || !output_file) { goto request_out; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the public key...\n"); } if(key_format == key_format_arg_PEM) { public_key = PEM_read_PUBKEY(input_file, NULL, NULL, NULL); if(!public_key) { fprintf(stderr, "Failed loading public key for request.\n"); goto request_out; } } else { fprintf(stderr, "Only PEM supported for public key input.\n"); goto request_out; } algorithm = get_algorithm(public_key); if(algorithm == 0) { goto request_out; } md = get_hash(hash, &oid, &oid_len); if(md == NULL) { goto request_out; } md_len = (unsigned int)EVP_MD_size(md); digest_len = sizeof(digest) - md_len; req = X509_REQ_new(); if(!req) { fprintf(stderr, "Failed to allocate request structure.\n"); goto request_out; } if(!X509_REQ_set_pubkey(req, public_key)) { fprintf(stderr, "Failed setting the request public key.\n"); goto request_out; } X509_REQ_set_version(req, 0); name = parse_name(subject); if(!name) { fprintf(stderr, "Failed encoding subject as name.\n"); goto request_out; } if(!X509_REQ_set_subject_name(req, name)) { fprintf(stderr, "Failed setting the request subject.\n"); goto request_out; } memcpy(digest, oid, oid_len); /* XXX: this should probably use X509_REQ_digest() but that's buggy */ if(!ASN1_item_digest(ASN1_ITEM_rptr(X509_REQ_INFO), md, req->req_info, digest + oid_len, &digest_len)) { fprintf(stderr, "Failed doing digest of request.\n"); goto request_out; } nid = get_hashnid(hash, algorithm); if(nid == 0) { fprintf(stderr, "Unsupported algorithm %x or hash %x\n", algorithm, hash); goto request_out; } if(YKPIV_IS_RSA(algorithm)) { signinput = digest; len = oid_len + digest_len; } else { signinput = digest + oid_len; len = digest_len; } req->sig_alg->algorithm = OBJ_nid2obj(nid); { unsigned char signature[1024]; size_t sig_len = sizeof(signature); if(!sign_data(state, signinput, len, signature, &sig_len, algorithm, key)) { fprintf(stderr, "Failed signing request.\n"); goto request_out; } M_ASN1_BIT_STRING_set(req->signature, signature, sig_len); /* mark that all bits should be used. */ req->signature->flags = ASN1_STRING_FLAG_BITS_LEFT; } if(key_format == key_format_arg_PEM) { PEM_write_X509_REQ(output_file, req); ret = true; } else { fprintf(stderr, "Only PEM support available for certificate requests.\n"); } request_out: if(input_file && input_file != stdin) { fclose(input_file); } if(output_file && output_file != stdout) { fclose(output_file); } if(public_key) { EVP_PKEY_free(public_key); } if(req) { X509_REQ_free(req); } if(name) { X509_NAME_free(name); } return ret; } static bool selfsign_certificate(ykpiv_state *state, enum enum_key_format key_format, const char *input_file_name, const char *slot, char *subject, enum enum_hash hash, const int *serial, int validDays, const char *output_file_name) { FILE *input_file = NULL; FILE *output_file = NULL; bool ret = false; EVP_PKEY *public_key = NULL; X509 *x509 = NULL; X509_NAME *name = NULL; const EVP_MD *md; unsigned char digest[EVP_MAX_MD_SIZE + MAX_OID_LEN]; unsigned int digest_len; unsigned char algorithm; int key = 0; unsigned char *signinput; size_t len = 0; size_t oid_len; const unsigned char *oid; int nid; unsigned int md_len; ASN1_INTEGER *sno = ASN1_INTEGER_new(); BIGNUM *ser = NULL; sscanf(slot, "%2x", &key); input_file = open_file(input_file_name, INPUT); output_file = open_file(output_file_name, OUTPUT); if(!input_file || !output_file) { goto selfsign_out; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the public key...\n"); } if(key_format == key_format_arg_PEM) { public_key = PEM_read_PUBKEY(input_file, NULL, NULL, NULL); if(!public_key) { fprintf(stderr, "Failed loading public key for certificate.\n"); goto selfsign_out; } } else { fprintf(stderr, "Only PEM supported for public key input.\n"); goto selfsign_out; } algorithm = get_algorithm(public_key); if(algorithm == 0) { goto selfsign_out; } md = get_hash(hash, &oid, &oid_len); if(md == NULL) { goto selfsign_out; } md_len = (unsigned int)EVP_MD_size(md); digest_len = sizeof(digest) - md_len; x509 = X509_new(); if(!x509) { fprintf(stderr, "Failed to allocate certificate structure.\n"); goto selfsign_out; } if(!X509_set_version(x509, 2)) { fprintf(stderr, "Failed to set certificate version.\n"); goto selfsign_out; } if(!X509_set_pubkey(x509, public_key)) { fprintf(stderr, "Failed to set the certificate public key.\n"); goto selfsign_out; } if(serial) { ASN1_INTEGER_set(sno, *serial); } else { ser = BN_new(); if(!ser) { fprintf(stderr, "Failed to allocate BIGNUM.\n"); goto selfsign_out; } if(!BN_pseudo_rand(ser, 64, 0, 0)) { fprintf(stderr, "Failed to generate randomness.\n"); goto selfsign_out; } if(!BN_to_ASN1_INTEGER(ser, sno)) { fprintf(stderr, "Failed to set random serial.\n"); goto selfsign_out; } } if(!X509_set_serialNumber(x509, sno)) { fprintf(stderr, "Failed to set certificate serial.\n"); goto selfsign_out; } if(!X509_gmtime_adj(X509_get_notBefore(x509), 0)) { fprintf(stderr, "Failed to set certificate notBefore.\n"); goto selfsign_out; } if(!X509_gmtime_adj(X509_get_notAfter(x509), 60L * 60L * 24L * validDays)) { fprintf(stderr, "Failed to set certificate notAfter.\n"); goto selfsign_out; } name = parse_name(subject); if(!name) { fprintf(stderr, "Failed encoding subject as name.\n"); goto selfsign_out; } if(!X509_set_subject_name(x509, name)) { fprintf(stderr, "Failed setting certificate subject.\n"); goto selfsign_out; } if(!X509_set_issuer_name(x509, name)) { fprintf(stderr, "Failed setting certificate issuer.\n"); goto selfsign_out; } nid = get_hashnid(hash, algorithm); if(nid == 0) { goto selfsign_out; } if(YKPIV_IS_RSA(algorithm)) { signinput = digest; len = oid_len + md_len; } else { signinput = digest + oid_len; len = md_len; } x509->sig_alg->algorithm = OBJ_nid2obj(nid); x509->cert_info->signature->algorithm = x509->sig_alg->algorithm; memcpy(digest, oid, oid_len); /* XXX: this should probably use X509_digest() but that looks buggy */ if(!ASN1_item_digest(ASN1_ITEM_rptr(X509_CINF), md, x509->cert_info, digest + oid_len, &digest_len)) { fprintf(stderr, "Failed doing digest of certificate.\n"); goto selfsign_out; } { unsigned char signature[1024]; size_t sig_len = sizeof(signature); if(!sign_data(state, signinput, len, signature, &sig_len, algorithm, key)) { fprintf(stderr, "Failed signing certificate.\n"); goto selfsign_out; } M_ASN1_BIT_STRING_set(x509->signature, signature, sig_len); /* setting flags to ASN1_STRING_FLAG_BITS_LEFT here marks that no bits * should be subtracted from the bit string, thus making sure that the * certificate can be validated. */ x509->signature->flags = ASN1_STRING_FLAG_BITS_LEFT; } if(key_format == key_format_arg_PEM) { PEM_write_X509(output_file, x509); ret = true; } else { fprintf(stderr, "Only PEM support available for certificate requests.\n"); } selfsign_out: if(input_file && input_file != stdin) { fclose(input_file); } if(output_file && output_file != stdout) { fclose(output_file); } if(x509) { X509_free(x509); } if(public_key) { EVP_PKEY_free(public_key); } if(name) { X509_NAME_free(name); } if(ser) { BN_free(ser); } if(sno) { ASN1_INTEGER_free(sno); } return ret; } static bool verify_pin(ykpiv_state *state, const char *pin) { int tries = -1; ykpiv_rc res; int len; char pinbuf[9] = {0}; if(!pin) { if (!read_pw("PIN", pinbuf, sizeof(pinbuf), false)) { return false; } pin = pinbuf; } len = strlen(pin); if(len > 8) { fprintf(stderr, "Maximum 8 digits of PIN supported.\n"); } res = ykpiv_verify(state, pin, &tries); if(res == YKPIV_OK) { return true; } else if(res == YKPIV_WRONG_PIN) { if(tries > 0) { fprintf(stderr, "Pin verification failed, %d tries left before pin is blocked.\n", tries); } else { fprintf(stderr, "Pin code blocked, use unblock-pin action to unblock.\n"); } } else { fprintf(stderr, "Pin code verification failed: '%s'\n", ykpiv_strerror(res)); } return false; } /* this function is called for all three of change-pin, change-puk and unblock pin * since they're very similar in what data they use. */ static bool change_pin(ykpiv_state *state, enum enum_action action, const char *pin, const char *new_pin) { char pinbuf[9] = {0}; char new_pinbuf[9] = {0}; const char *name = action == action_arg_changeMINUS_pin ? "pin" : "puk"; const char *new_name = action == action_arg_changeMINUS_puk ? "new puk" : "new pin"; int (*op)(ykpiv_state *state, const char * puk, size_t puk_len, const char * new_pin, size_t new_pin_len, int *tries) = ykpiv_change_pin; size_t pin_len; size_t new_len; int tries; ykpiv_rc res; if(!pin) { if (!read_pw(name, pinbuf, sizeof(pinbuf), false)) { return false; } pin = pinbuf; } if(!new_pin) { if (!read_pw(new_name, new_pinbuf, sizeof(new_pinbuf), true)) { return false; } new_pin = new_pinbuf; } pin_len = strlen(pin); new_len = strlen(new_pin); if(pin_len > 8 || new_len > 8) { fprintf(stderr, "Maximum 8 digits of PIN supported.\n"); return false; } if(new_len < 6) { fprintf(stderr, "Minimum 6 digits of PIN supported.\n"); return false; } if(action == action_arg_unblockMINUS_pin) { op = ykpiv_unblock_pin; } else if(action == action_arg_changeMINUS_puk) { op = ykpiv_change_puk; } res = op(state, pin, pin_len, new_pin, new_len, &tries); switch (res) { case YKPIV_OK: return true; case YKPIV_WRONG_PIN: fprintf(stderr, "Failed verifying %s code, now %d tries left before blocked.\n", name, tries); return false; case YKPIV_PIN_LOCKED: if(action == action_arg_changeMINUS_pin) { fprintf(stderr, "The pin code is blocked, use the unblock-pin action to unblock it.\n"); } else { fprintf(stderr, "The puk code is blocked, you will have to reinitialize the application.\n"); } return false; default: fprintf(stderr, "Failed changing/unblocking code, error: %s\n", ykpiv_strerror(res)); return false; } } static bool delete_certificate(ykpiv_state *state, enum enum_slot slot) { int object = get_object_id(slot); if(ykpiv_save_object(state, object, NULL, 0) != YKPIV_OK) { fprintf(stderr, "Failed deleting object.\n"); return false; } else { fprintf(stderr, "Certificate deleted.\n"); return true; } } static bool read_certificate(ykpiv_state *state, enum enum_slot slot, enum enum_key_format key_format, const char *output_file_name) { FILE *output_file; int object = get_object_id(slot); unsigned char data[3072]; const unsigned char *ptr = data; unsigned long len = sizeof(data); int cert_len; bool ret = false; X509 *x509 = NULL; if(key_format != key_format_arg_PEM && key_format != key_format_arg_DER && key_format != key_format_arg_SSH) { fprintf(stderr, "Only PEM, DER and SSH format are supported for read-certificate.\n"); return false; } output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } if(ykpiv_fetch_object(state, object, data, &len) != YKPIV_OK) { fprintf(stderr, "Failed fetching certificate.\n"); goto read_cert_out; } if(*ptr++ == 0x70) { ptr += get_length(ptr, &cert_len); if(key_format == key_format_arg_PEM || key_format == key_format_arg_SSH) { x509 = X509_new(); if(!x509) { fprintf(stderr, "Failed allocating x509 structure.\n"); goto read_cert_out; } x509 = d2i_X509(NULL, &ptr, cert_len); if(!x509) { fprintf(stderr, "Failed parsing x509 information.\n"); goto read_cert_out; } if (key_format == key_format_arg_PEM) { PEM_write_X509(output_file, x509); ret = true; } else { if (!SSH_write_X509(output_file, x509)) { fprintf(stderr, "Unable to extract public key or not an RSA key.\n"); goto read_cert_out; } ret = true; } } else { /* key_format_arg_DER */ /* XXX: This will just dump the raw data in tag 0x70.. */ fwrite(ptr, (size_t)cert_len, 1, output_file); ret = true; } } else { fprintf(stderr, "Failed parsing data.\n"); } read_cert_out: if(output_file != stdout) { fclose(output_file); } if(x509) { X509_free(x509); } return ret; } static bool sign_file(ykpiv_state *state, const char *input, const char *output, const char *slot, enum enum_algorithm algorithm, enum enum_hash hash, int verbosity) { FILE *input_file = NULL; FILE *output_file = NULL; int key; unsigned int hash_len; unsigned char hashed[EVP_MAX_MD_SIZE]; bool ret = false; int algo; const EVP_MD *md; sscanf(slot, "%2x", &key); input_file = open_file(input, INPUT); if(!input_file) { return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the input...\n"); } output_file = open_file(output, OUTPUT); if(!output_file) { if(input_file && input_file != stdin) { fclose(input_file); } return false; } algo = get_piv_algorithm(algorithm); if(algo == 0) { goto out; } { EVP_MD_CTX *mdctx; md = get_hash(hash, NULL, NULL); if(md == NULL) { goto out; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); while(!feof(input_file)) { char buf[1024]; size_t len = fread(buf, 1, 1024, input_file); EVP_DigestUpdate(mdctx, buf, len); } EVP_DigestFinal_ex(mdctx, hashed, &hash_len); if(verbosity) { fprintf(stderr, "file hashed as: "); dump_data(hashed, hash_len, stderr, true, format_arg_hex); } EVP_MD_CTX_destroy(mdctx); } if(YKPIV_IS_RSA(algo)) { prepare_rsa_signature(hashed, hash_len, hashed, &hash_len, EVP_MD_type(md)); } { unsigned char buf[1024]; size_t len = sizeof(buf); if(!sign_data(state, hashed, hash_len, buf, &len, algo, key)) { fprintf(stderr, "failed signing file\n"); goto out; } if(verbosity) { fprintf(stderr, "file signed as: "); dump_data(buf, len, stderr, true, format_arg_hex); } fwrite(buf, 1, len, output_file); ret = true; } out: if(input_file && input_file != stdin) { fclose(input_file); } if(output_file && output_file != stdout) { fclose(output_file); } return ret; } static void print_cert_info(ykpiv_state *state, enum enum_slot slot, const EVP_MD *md, FILE *output) { int object = get_object_id(slot); int slot_name; unsigned char data[3072]; const unsigned char *ptr = data; unsigned long len = sizeof(data); int cert_len; X509 *x509 = NULL; X509_NAME *subj; BIO *bio = NULL; if(ykpiv_fetch_object(state, object, data, &len) != YKPIV_OK) { return; } if (slot == slot_arg_9a) slot_name = 0x9a; else if (slot >= slot_arg_9c && slot <= slot_arg_9e) slot_name = 0x9b + slot; else slot_name = 0x82 + (slot - slot_arg_82); fprintf(output, "Slot %x:\t", slot_name); if(*ptr++ == 0x70) { unsigned int md_len = sizeof(data); ASN1_TIME *not_before, *not_after; ptr += get_length(ptr, &cert_len); x509 = X509_new(); if(!x509) { fprintf(output, "Allocation failure.\n"); return; } x509 = d2i_X509(NULL, &ptr, cert_len); if(!x509) { fprintf(output, "Unknown data present.\n"); goto cert_out; } { EVP_PKEY *key = X509_get_pubkey(x509); if(!key) { fprintf(output, "Parse error.\n"); goto cert_out; } fprintf(output, "\n\tAlgorithm:\t"); switch(get_algorithm(key)) { case YKPIV_ALGO_RSA1024: fprintf(output, "RSA1024\n"); break; case YKPIV_ALGO_RSA2048: fprintf(output, "RSA2048\n"); break; case YKPIV_ALGO_ECCP256: fprintf(output, "ECCP256\n"); break; case YKPIV_ALGO_ECCP384: fprintf(output, "ECCP384\n"); break; default: fprintf(output, "Unknown\n"); } } subj = X509_get_subject_name(x509); if(!subj) { fprintf(output, "Parse error.\n"); goto cert_out; } fprintf(output, "\tSubject DN:\t"); X509_NAME_print_ex_fp(output, subj, 0, XN_FLAG_COMPAT); fprintf(output, "\n"); subj = X509_get_issuer_name(x509); if(!subj) { fprintf(output, "Parse error.\n"); goto cert_out; } fprintf(output, "\tIssuer DN:\t"); X509_NAME_print_ex_fp(output, subj, 0, XN_FLAG_COMPAT); fprintf(output, "\n"); X509_digest(x509, md, data, &md_len); fprintf(output, "\tFingerprint:\t"); dump_data(data, md_len, output, false, format_arg_hex); bio = BIO_new_fp(output, BIO_NOCLOSE | BIO_FP_TEXT); not_before = X509_get_notBefore(x509); if(not_before) { fprintf(output, "\tNot Before:\t"); ASN1_TIME_print(bio, not_before); fprintf(output, "\n"); } not_after = X509_get_notAfter(x509); if(not_after) { fprintf(output, "\tNot After:\t"); ASN1_TIME_print(bio, not_after); fprintf(output, "\n"); } } else { fprintf(output, "Parse error.\n"); return; } cert_out: if(x509) { X509_free(x509); } if(bio) { BIO_free(bio); } } static bool status(ykpiv_state *state, enum enum_hash hash, enum enum_slot slot, const char *output_file_name) { const EVP_MD *md; unsigned char buf[3072]; long unsigned len = sizeof(buf); int i; FILE *output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } md = get_hash(hash, NULL, NULL); if(md == NULL) { return false; } fprintf(output_file, "CHUID:\t"); if(ykpiv_fetch_object(state, YKPIV_OBJ_CHUID, buf, &len) != YKPIV_OK) { fprintf(output_file, "No data available\n"); } else { dump_data(buf, len, output_file, false, format_arg_hex); } len = sizeof(buf); fprintf(output_file, "CCC:\t"); if(ykpiv_fetch_object(state, YKPIV_OBJ_CAPABILITY, buf, &len) != YKPIV_OK) { fprintf(output_file, "No data available\n"); } else { dump_data(buf, len, output_file, false, format_arg_hex); } if (slot == slot__NULL) for (i = 0; i < 24; i++) { print_cert_info(state, i, md, output_file); } else print_cert_info(state, slot, md, output_file); { int tries; ykpiv_verify(state, NULL, &tries); fprintf(output_file, "PIN tries left:\t%d\n", tries); } if(output_file != stdout) { fclose(output_file); } return true; } static bool test_signature(ykpiv_state *state, enum enum_slot slot, enum enum_hash hash, const char *input_file_name, enum enum_key_format cert_format, int verbose) { const EVP_MD *md; bool ret = false; unsigned char data[1024]; unsigned int data_len; X509 *x509 = NULL; EVP_PKEY *pubkey; FILE *input_file = open_file(input_file_name, INPUT); if(!input_file) { fprintf(stderr, "Failed opening input file %s.\n", input_file_name); return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the certificate to verify against...\n"); } if(cert_format == key_format_arg_PEM) { x509 = PEM_read_X509(input_file, NULL, NULL, NULL); } else if(cert_format == key_format_arg_DER) { x509 = d2i_X509_fp(input_file, NULL); } else { fprintf(stderr, "Only PEM or DER format is supported for test-signature.\n"); goto test_out; } if(!x509) { fprintf(stderr, "Failed loading certificate for test-signature.\n"); goto test_out; } md = get_hash(hash, NULL, NULL); if(md == NULL) { return false; } { unsigned char rand[128]; EVP_MD_CTX *mdctx; if(RAND_pseudo_bytes(rand, 128) == -1) { fprintf(stderr, "error: no randomness.\n"); return false; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, rand, 128); EVP_DigestFinal_ex(mdctx, data, &data_len); if(verbose) { fprintf(stderr, "Test data hashes as: "); dump_data(data, data_len, stderr, true, format_arg_hex); } } { unsigned char signature[1024]; unsigned char encoded[1024]; unsigned char *ptr = data; unsigned int enc_len; size_t sig_len = sizeof(signature); int key = 0; unsigned char algorithm; pubkey = X509_get_pubkey(x509); if(!pubkey) { fprintf(stderr, "Parse error.\n"); goto test_out; } algorithm = get_algorithm(pubkey); if(algorithm == 0) { goto test_out; } sscanf(cmdline_parser_slot_values[slot], "%2x", &key); if(YKPIV_IS_RSA(algorithm)) { prepare_rsa_signature(data, data_len, encoded, &enc_len, EVP_MD_type(md)); ptr = encoded; } else { enc_len = data_len; } if(!sign_data(state, ptr, enc_len, signature, &sig_len, algorithm, key)) { fprintf(stderr, "Failed signing test data.\n"); goto test_out; } switch(algorithm) { case YKPIV_ALGO_RSA1024: case YKPIV_ALGO_RSA2048: { RSA *rsa = EVP_PKEY_get1_RSA(pubkey); if(!rsa) { fprintf(stderr, "Failed getting RSA pubkey.\n"); goto test_out; } if(RSA_verify(EVP_MD_type(md), data, data_len, signature, sig_len, rsa) == 1) { fprintf(stderr, "Successful RSA verification.\n"); ret = true; goto test_out; } else { fprintf(stderr, "Failed RSA verification.\n"); goto test_out; } } break; case YKPIV_ALGO_ECCP256: case YKPIV_ALGO_ECCP384: { EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pubkey); if(ECDSA_verify(0, data, (int)data_len, signature, (int)sig_len, ec) == 1) { fprintf(stderr, "Successful ECDSA verification.\n"); ret = true; goto test_out; } else { fprintf(stderr, "Failed ECDSA verification.\n"); goto test_out; } } break; default: fprintf(stderr, "Unknown algorithm.\n"); goto test_out; } } test_out: if(x509) { X509_free(x509); } if(input_file != stdin) { fclose(input_file); } return ret; } static bool test_decipher(ykpiv_state *state, enum enum_slot slot, const char *input_file_name, enum enum_key_format cert_format, int verbose) { bool ret = false; X509 *x509 = NULL; EVP_PKEY *pubkey; EC_KEY *tmpkey = NULL; FILE *input_file = open_file(input_file_name, INPUT); if(!input_file) { fprintf(stderr, "Failed opening input file %s.\n", input_file_name); return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the certificate to encrypt for...\n"); } if(cert_format == key_format_arg_PEM) { x509 = PEM_read_X509(input_file, NULL, NULL, NULL); } else if(cert_format == key_format_arg_DER) { x509 = d2i_X509_fp(input_file, NULL); } else { fprintf(stderr, "Only PEM or DER format is supported for test-decipher.\n"); goto decipher_out; } if(!x509) { fprintf(stderr, "Failed loading certificate for test-decipher.\n"); goto decipher_out; } { int key = 0; unsigned char algorithm; pubkey = X509_get_pubkey(x509); if(!pubkey) { fprintf(stderr, "Parse error.\n"); goto decipher_out; } algorithm = get_algorithm(pubkey); if(algorithm == 0) { goto decipher_out; } sscanf(cmdline_parser_slot_values[slot], "%2x", &key); if(YKPIV_IS_RSA(algorithm)) { unsigned char secret[32]; unsigned char secret2[32]; unsigned char data[256]; int len; size_t len2 = sizeof(data); RSA *rsa = EVP_PKEY_get1_RSA(pubkey); if(RAND_pseudo_bytes(secret, sizeof(secret)) == -1) { fprintf(stderr, "error: no randomness.\n"); ret = false; goto decipher_out; } len = RSA_public_encrypt(sizeof(secret), secret, data, rsa, RSA_PKCS1_PADDING); if(len < 0) { fprintf(stderr, "Failed performing RSA encryption!\n"); goto decipher_out; } if(ykpiv_decipher_data(state, data, (size_t)len, data, &len2, algorithm, key) != YKPIV_OK) { fprintf(stderr, "RSA decrypt failed!\n"); goto decipher_out; } /* for some reason we have to give the padding check function data + 1 */ len = RSA_padding_check_PKCS1_type_2(secret2, sizeof(secret2), data + 1, len2 - 1, RSA_size(rsa)); if(len == sizeof(secret)) { if(verbose) { fprintf(stderr, "Generated nonce: "); dump_data(secret, sizeof(secret), stderr, true, format_arg_hex); fprintf(stderr, "Decrypted nonce: "); dump_data(secret2, sizeof(secret2), stderr, true, format_arg_hex); } if(memcmp(secret, secret2, sizeof(secret)) == 0) { fprintf(stderr, "Successfully performed RSA decryption!\n"); ret = true; } else { fprintf(stderr, "Failed performing RSA decryption!\n"); } } else { fprintf(stderr, "Failed unwrapping PKCS1 envelope.\n"); } } else if(YKPIV_IS_EC(algorithm)) { unsigned char secret[48]; unsigned char secret2[48]; unsigned char public_key[97]; unsigned char *ptr = public_key; size_t len = sizeof(secret); EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pubkey); int nid; size_t key_len; if(algorithm == YKPIV_ALGO_ECCP256) { nid = NID_X9_62_prime256v1; key_len = 32; } else { nid = NID_secp384r1; key_len = 48; } tmpkey = EC_KEY_new_by_curve_name(nid); EC_KEY_generate_key(tmpkey); ECDH_compute_key(secret, len, EC_KEY_get0_public_key(ec), tmpkey, NULL); i2o_ECPublicKey(tmpkey, &ptr); if(ykpiv_decipher_data(state, public_key, (key_len * 2) + 1, secret2, &len, algorithm, key) != YKPIV_OK) { fprintf(stderr, "Failed ECDH exchange!\n"); goto decipher_out; } if(verbose) { fprintf(stderr, "ECDH host generated: "); dump_data(secret, len, stderr, true, format_arg_hex); fprintf(stderr, "ECDH card generated: "); dump_data(secret2, len, stderr, true, format_arg_hex); } if(memcmp(secret, secret2, key_len) == 0) { fprintf(stderr, "Successfully performed ECDH exchange with card.\n"); ret = true; } else { fprintf(stderr, "ECDH exchange with card failed!\n"); } } } decipher_out: if(tmpkey) { EC_KEY_free(tmpkey); } if(x509) { X509_free(x509); } if(input_file != stdin) { fclose(input_file); } return ret; } static bool list_readers(ykpiv_state *state) { char readers[2048]; char *reader_ptr; size_t len = sizeof(readers); ykpiv_rc rc = ykpiv_list_readers(state, readers, &len); if(rc != YKPIV_OK) { fprintf(stderr, "Failed listing readers.\n"); return false; } for(reader_ptr = readers; *reader_ptr != '\0'; reader_ptr += strlen(reader_ptr) + 1) { printf("%s\n", reader_ptr); } return true; } static bool attest(ykpiv_state *state, const char *slot, enum enum_key_format key_format, const char *output_file_name) { unsigned char data[2048]; unsigned long len = sizeof(data); bool ret = false; X509 *x509 = NULL; unsigned char templ[] = {0, YKPIV_INS_ATTEST, 0, 0}; int key; int sw; FILE *output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } sscanf(slot, "%2x", &key); templ[2] = key; if(key_format != key_format_arg_PEM && key_format != key_format_arg_DER) { fprintf(stderr, "Only PEM and DER format are supported for attest..\n"); return false; } if(ykpiv_transfer_data(state, templ, NULL, 0, data, &len, &sw) != YKPIV_OK) { fprintf(stderr, "Failed to communicate.\n"); goto attest_out; } else if(sw != SW_SUCCESS) { fprintf(stderr, "Failed to attest key.\n"); goto attest_out; } if(data[0] == 0x30) { if(key_format == key_format_arg_PEM) { const unsigned char *ptr = data; int len2 = len; x509 = X509_new(); if(!x509) { fprintf(stderr, "Failed allocating x509 structure.\n"); goto attest_out; } x509 = d2i_X509(NULL, &ptr, len2); if(!x509) { fprintf(stderr, "Failed parsing x509 information.\n"); goto attest_out; } PEM_write_X509(output_file, x509); ret = true; } else { fwrite(data, len, 1, output_file); } ret = true; } attest_out: if(output_file != stdout) { fclose(output_file); } if(x509) { X509_free(x509); } return ret; } static bool write_object(ykpiv_state *state, int id, const char *input_file_name, int verbosity, enum enum_format format) { bool ret = false; FILE *input_file = NULL; unsigned char data[3072]; size_t len = sizeof(data); ykpiv_rc res; input_file = open_file(input_file_name, INPUT); if(!input_file) { return false; } if(isatty(fileno(input_file))) { fprintf(stderr, "Please paste the data...\n"); } len = read_data(data, len, input_file, format); if(len == 0) { fprintf(stderr, "Failed reading data\n"); goto write_out; } if(verbosity) { fprintf(stderr, "Writing %lu bytes of data to object %x.\n", len, id); } if((res = ykpiv_save_object(state, id, data, len)) != YKPIV_OK) { fprintf(stderr, "Failed writing data to device: %s\n", ykpiv_strerror(res)); } else { ret = true; } write_out: if(input_file != stdin) { fclose(input_file); } return ret; } static bool read_object(ykpiv_state *state, int id, const char *output_file_name, enum enum_format format) { FILE *output_file = NULL; unsigned char data[3072]; unsigned long len = sizeof(data); bool ret = false; output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } if(ykpiv_fetch_object(state, id, data, &len) != YKPIV_OK) { fprintf(stderr, "Failed fetching object.\n"); goto read_out; } dump_data(data, len, output_file, false, format); ret = true; read_out: if(output_file != stdout) { fclose(output_file); } return ret; } int main(int argc, char *argv[]) { struct gengetopt_args_info args_info; ykpiv_state *state; int verbosity; enum enum_action action; unsigned int i; int ret = EXIT_SUCCESS; bool authed = false; char pwbuf[128]; char *password; if(cmdline_parser(argc, argv, &args_info) != 0) { return EXIT_FAILURE; } verbosity = args_info.verbose_arg + (int)args_info.verbose_given; password = args_info.password_arg; for(i = 0; i < args_info.action_given; i++) { action = *(args_info.action_arg + i); switch(action) { case action_arg_requestMINUS_certificate: case action_arg_selfsignMINUS_certificate: if(!args_info.subject_arg) { fprintf(stderr, "The '%s' action needs a subject (-S) to operate on.\n", cmdline_parser_action_values[action]); return EXIT_FAILURE; } case action_arg_generate: case action_arg_importMINUS_key: case action_arg_importMINUS_certificate: case action_arg_deleteMINUS_certificate: case action_arg_readMINUS_certificate: case action_arg_testMINUS_signature: case action_arg_testMINUS_decipher: case action_arg_attest: if(args_info.slot_arg == slot__NULL) { fprintf(stderr, "The '%s' action needs a slot (-s) to operate on.\n", cmdline_parser_action_values[action]); return EXIT_FAILURE; } break; case action_arg_pinMINUS_retries: if(!args_info.pin_retries_arg || !args_info.puk_retries_arg) { fprintf(stderr, "The '%s' action needs both --pin-retries and --puk-retries arguments.\n", cmdline_parser_action_values[action]); return EXIT_FAILURE; } break; case action_arg_writeMINUS_object: case action_arg_readMINUS_object: if(!args_info.id_given) { fprintf(stderr, "The '%s' action needs the --id argument.\n", cmdline_parser_action_values[action]); return EXIT_FAILURE; } break; case action_arg_changeMINUS_pin: case action_arg_changeMINUS_puk: case action_arg_unblockMINUS_pin: case action_arg_verifyMINUS_pin: case action_arg_setMINUS_mgmMINUS_key: case action_arg_setMINUS_chuid: case action_arg_setMINUS_ccc: case action_arg_version: case action_arg_reset: case action_arg_status: case action_arg_listMINUS_readers: case action__NULL: default: continue; } } if(ykpiv_init(&state, verbosity) != YKPIV_OK) { fprintf(stderr, "Failed initializing library.\n"); return EXIT_FAILURE; } if(ykpiv_connect(state, args_info.reader_arg) != YKPIV_OK) { fprintf(stderr, "Failed to connect to reader.\n"); return EXIT_FAILURE; } for(i = 0; i < args_info.action_given; i++) { action = *(args_info.action_arg + i); switch(action) { case action_arg_importMINUS_key: case action_arg_importMINUS_certificate: if(args_info.key_format_arg == key_format_arg_PKCS12 && !password) { if(verbosity) { fprintf(stderr, "Asking for password since '%s' needs it.\n", cmdline_parser_action_values[action]); } if(!read_pw("Password", pwbuf, sizeof(pwbuf), false)) { fprintf(stderr, "Failed to get password.\n"); return false; } password = pwbuf; } case action_arg_generate: case action_arg_setMINUS_mgmMINUS_key: case action_arg_pinMINUS_retries: case action_arg_setMINUS_chuid: case action_arg_setMINUS_ccc: case action_arg_deleteMINUS_certificate: case action_arg_writeMINUS_object: if(!authed) { unsigned char key[KEY_LEN]; size_t key_len = sizeof(key); char keybuf[KEY_LEN*2+1]; char *key_ptr = args_info.key_arg; if(verbosity) { fprintf(stderr, "Authenticating since action '%s' needs that.\n", cmdline_parser_action_values[action]); } if(args_info.key_given && args_info.key_orig == NULL) { if(!read_pw("management key", keybuf, sizeof(keybuf), false)) { fprintf(stderr, "Failed to read management key from stdin,\n"); return EXIT_FAILURE; } key_ptr = keybuf; } if(ykpiv_hex_decode(key_ptr, strlen(key_ptr), key, &key_len) != YKPIV_OK) { fprintf(stderr, "Failed decoding key!\n"); return EXIT_FAILURE; } if(ykpiv_authenticate(state, key) != YKPIV_OK) { fprintf(stderr, "Failed authentication with the application.\n"); return EXIT_FAILURE; } if(verbosity) { fprintf(stderr, "Successful application authentication.\n"); } authed = true; } else { if(verbosity) { fprintf(stderr, "Skipping authentication for '%s' since it's already done.\n", cmdline_parser_action_values[action]); } } break; case action_arg_version: case action_arg_reset: case action_arg_requestMINUS_certificate: case action_arg_verifyMINUS_pin: case action_arg_changeMINUS_pin: case action_arg_changeMINUS_puk: case action_arg_unblockMINUS_pin: case action_arg_selfsignMINUS_certificate: case action_arg_readMINUS_certificate: case action_arg_status: case action_arg_testMINUS_signature: case action_arg_testMINUS_decipher: case action_arg_listMINUS_readers: case action_arg_attest: case action_arg_readMINUS_object: case action__NULL: default: if(verbosity) { fprintf(stderr, "Action '%s' does not need authentication.\n", cmdline_parser_action_values[action]); } } } /* openssl setup.. */ OpenSSL_add_all_algorithms(); for(i = 0; i < args_info.action_given; i++) { char new_keybuf[KEY_LEN*2+1] = {0}; char *new_mgm_key = args_info.new_key_arg; action = *(args_info.action_arg + i); if(verbosity) { fprintf(stderr, "Now processing for action '%s'.\n", cmdline_parser_action_values[action]); } switch(action) { case action_arg_version: print_version(state, args_info.output_arg); break; case action_arg_generate: if(generate_key(state, args_info.slot_orig, args_info.algorithm_arg, args_info.output_arg, args_info.key_format_arg, args_info.pin_policy_arg, args_info.touch_policy_arg) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully generated a new private key.\n"); } break; case action_arg_setMINUS_mgmMINUS_key: if(!new_mgm_key) { if(!read_pw("new management key", new_keybuf, sizeof(new_keybuf), true)) { fprintf(stderr, "Failed to read management key from stdin,\n"); ret = EXIT_FAILURE; break; } new_mgm_key = new_keybuf; } if(strlen(new_mgm_key) == (KEY_LEN * 2)){ unsigned char new_key[KEY_LEN]; size_t new_key_len = sizeof(new_key); if(ykpiv_hex_decode(new_mgm_key, strlen(new_mgm_key), new_key, &new_key_len) != YKPIV_OK) { fprintf(stderr, "Failed decoding new key!\n"); ret = EXIT_FAILURE; } else if(ykpiv_set_mgmkey2(state, new_key, args_info.touch_policy_arg == touch_policy_arg_always ? 1 : 0) != YKPIV_OK) { fprintf(stderr, "Failed setting the new key!"); if(args_info.touch_policy_arg != touch_policy__NULL) { fprintf(stderr, " Maybe touch policy is not supported on this key?"); } fprintf(stderr, "\n"); ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully set new management key.\n"); } } else { fprintf(stderr, "The new management key has to be exactly %d character.\n", KEY_LEN * 2); ret = EXIT_FAILURE; } break; case action_arg_reset: if(reset(state) == false) { fprintf(stderr, "Reset failed, are pincodes blocked?\n"); ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully reset the application.\n"); } break; case action_arg_pinMINUS_retries: if(set_pin_retries(state, args_info.pin_retries_arg, args_info.puk_retries_arg, verbosity) == false) { fprintf(stderr, "Failed changing pin retries.\n"); ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully changed pin retries to %d and puk retries to %d, both codes have been reset to default now.\n", args_info.pin_retries_arg, args_info.puk_retries_arg); } break; case action_arg_importMINUS_key: if(import_key(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_orig, password, args_info.pin_policy_arg, args_info.touch_policy_arg) == false) { fprintf(stderr, "Unable to import private key\n"); ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully imported a new private key.\n"); } break; case action_arg_importMINUS_certificate: if(import_cert(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_arg, password) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully imported a new certificate.\n"); } break; case action_arg_setMINUS_ccc: case action_arg_setMINUS_chuid: if(set_dataobject(state, verbosity, action == action_arg_setMINUS_chuid ? CHUID : CCC) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully set new %s.\n", action == action_arg_setMINUS_chuid ? "CHUID" : "CCC"); } break; case action_arg_requestMINUS_certificate: if(request_certificate(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_orig, args_info.subject_arg, args_info.hash_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully generated a certificate request.\n"); } break; case action_arg_verifyMINUS_pin: if(verify_pin(state, args_info.pin_arg)) { fprintf(stderr, "Successfully verified PIN.\n"); } else { ret = EXIT_FAILURE; } break; case action_arg_changeMINUS_pin: case action_arg_changeMINUS_puk: case action_arg_unblockMINUS_pin: if(change_pin(state, action, args_info.pin_arg, args_info.new_pin_arg)) { if(action == action_arg_unblockMINUS_pin) { fprintf(stderr, "Successfully unblocked the pin code.\n"); } else { fprintf(stderr, "Successfully changed the %s code.\n", action == action_arg_changeMINUS_pin ? "pin" : "puk"); } } else { ret = EXIT_FAILURE; } break; case action_arg_selfsignMINUS_certificate: if(selfsign_certificate(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_orig, args_info.subject_arg, args_info.hash_arg, args_info.serial_given ? &args_info.serial_arg : NULL, args_info.valid_days_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully generated a new self signed certificate.\n"); } break; case action_arg_deleteMINUS_certificate: if(delete_certificate(state, args_info.slot_arg) == false) { ret = EXIT_FAILURE; } break; case action_arg_readMINUS_certificate: if(read_certificate(state, args_info.slot_arg, args_info.key_format_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } break; case action_arg_status: if(status(state, args_info.hash_arg, args_info.slot_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } break; case action_arg_testMINUS_signature: if(test_signature(state, args_info.slot_arg, args_info.hash_arg, args_info.input_arg, args_info.key_format_arg, verbosity) == false) { ret = EXIT_FAILURE; } break; case action_arg_testMINUS_decipher: if(test_decipher(state, args_info.slot_arg, args_info.input_arg, args_info.key_format_arg, verbosity) == false) { ret = EXIT_FAILURE; } break; case action_arg_listMINUS_readers: if(list_readers(state) == false) { ret = EXIT_FAILURE; } break; case action_arg_writeMINUS_object: if(write_object(state, args_info.id_arg, args_info.input_arg, verbosity, args_info.format_arg) == false) { ret = EXIT_FAILURE; } break; case action_arg_readMINUS_object: if(read_object(state, args_info.id_arg, args_info.output_arg, args_info.format_arg) == false) { ret = EXIT_FAILURE; } break; case action_arg_attest: if(attest(state, args_info.slot_orig, args_info.key_format_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } break; case action__NULL: default: fprintf(stderr, "Wrong action. %d.\n", action); ret = EXIT_FAILURE; } if(ret == EXIT_FAILURE) { break; } } if(ret == EXIT_SUCCESS && args_info.sign_flag) { if(args_info.slot_arg == slot__NULL) { fprintf(stderr, "The sign action needs a slot (-s) to operate on.\n"); ret = EXIT_FAILURE; } else if(sign_file(state, args_info.input_arg, args_info.output_arg, args_info.slot_orig, args_info.algorithm_arg, args_info.hash_arg, verbosity)) { fprintf(stderr, "Signature successful!\n"); } else { fprintf(stderr, "Failed signing!\n"); ret = EXIT_FAILURE; } } ykpiv_done(state); EVP_cleanup(); return ret; }
29.596818
135
0.630842
[ "object" ]
f01ceb77fce2f49ee693cf4308a6efe1e74c9558
1,659
h
C
src/dotconfig.h
merelabs/mere-config-lite
9f64538eba0f4e9b50f540f59a7be99b6653d252
[ "BSD-2-Clause" ]
null
null
null
src/dotconfig.h
merelabs/mere-config-lite
9f64538eba0f4e9b50f540f59a7be99b6653d252
[ "BSD-2-Clause" ]
null
null
null
src/dotconfig.h
merelabs/mere-config-lite
9f64538eba0f4e9b50f540f59a7be99b6653d252
[ "BSD-2-Clause" ]
null
null
null
#ifndef MERE_CONFIG_DOTCONFIG_H #define MERE_CONFIG_DOTCONFIG_H #include "groupconfig.h" #include "spec/dotted.h" namespace Mere { namespace Config { class MERE_CONFIG_LIB_SPEC DotConfig : public PropertyConfig { public: explicit DotConfig(const std::string &path); // config std::string get(const std::string &fqkp, bool *set = nullptr) const override; void set(const std::string &fqkp, const std::string &value) override; std::string read(const std::string &fqkp, bool *set = nullptr) const override; // // property config std::vector<std::string> getKeys() const override; std::string getValue(const std::string &key, bool *set = nullptr) const override; Property* getProperty(const std::string &key) const override; std::vector<Property *> getProperties() const override; void setProperty(Property *property) override; void setValue(const std::string &key, const std::string &value) override; std::vector<Property *> readProperties() const override; Property* readProperty(const std::string &key) const override; // // group config std::vector<std::string> getKeys(const std::string &name, int *set = nullptr) const; std::vector<std::string> getAllKeys(const std::string &name, int *set = nullptr) const; std::vector<Property *> getProperties(const std::string &name, int *set = nullptr) const; std::vector<Property *> getAllProperties(const std::string &name, int *set = nullptr) const; private: void load(); signals: private: std::vector<Mere::Config::Property *> m_properties; Mere::Config::Spec::Dotted m_config; }; } } #endif // MERE_CONFIG_DOTCONFIG_H
31.903846
96
0.711272
[ "vector" ]
f02c90ef7620c7977add153cc9ffc6a9392dccf2
2,923
h
C
FEBioFluid/FEFluidFSI.h
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
59
2020-06-15T12:38:49.000Z
2022-03-29T19:14:47.000Z
FEBioFluid/FEFluidFSI.h
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
36
2020-06-14T21:10:01.000Z
2022-03-12T12:03:14.000Z
FEBioFluid/FEFluidFSI.h
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
26
2020-06-25T15:02:13.000Z
2022-03-10T09:14:03.000Z
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ #pragma once #include <FEBioMech/FEElasticMaterial.h> #include "FEFluid.h" //----------------------------------------------------------------------------- //! FSI material point class. // class FEBIOFLUID_API FEFSIMaterialPoint : public FEMaterialPoint { public: //! constructor FEFSIMaterialPoint(FEMaterialPoint* pt); //! create a shallow copy FEMaterialPoint* Copy(); //! data serialization void Serialize(DumpStream& ar); //! Data initialization void Init(); public: // FSI material data vec3d m_w; //!< fluid flux relative to solid vec3d m_aw; //!< material time derivative of m_wt double m_Jdot; //!< time derivative of solid volume ratio mat3ds m_ss; //!< solid stress }; //----------------------------------------------------------------------------- //! Base class for FluidFSI materials. class FEBIOFLUID_API FEFluidFSI : public FEMaterial { public: FEFluidFSI(FEModel* pfem); // returns a pointer to a new material point object FEMaterialPoint* CreateMaterialPointData() override; // Get the elastic component (overridden from FEMaterial) FEElasticMaterial* GetElasticMaterial() { return m_pSolid; } //! performs initialization bool Init() override; public: FEFluid* Fluid() { return m_pFluid; } FEElasticMaterial* Solid() { return m_pSolid; } protected: // material properties FEElasticMaterial* m_pSolid; //!< pointer to elastic solid material FEFluid* m_pFluid; //!< pointer to fluid material DECLARE_FECORE_CLASS(); };
33.988372
82
0.68286
[ "object", "solid" ]
6cd3d85ead0bc8265c533684f06ddd4ed0996c48
3,923
h
C
libs/wgtcc/evaluator.h
dfranx/ShaderDebugger
c6f0e9390a3e3cca9b0fec538a920cde4fec8cfd
[ "MIT" ]
355
2019-09-27T15:29:05.000Z
2022-02-08T23:34:46.000Z
libs/wgtcc/evaluator.h
Vicfred/ShaderDebugger
cfdea282056d5c2aa0b4626d852afe031426f44c
[ "MIT" ]
5
2019-11-08T23:49:48.000Z
2020-07-13T20:22:19.000Z
libs/wgtcc/evaluator.h
Vicfred/ShaderDebugger
cfdea282056d5c2aa0b4626d852afe031426f44c
[ "MIT" ]
18
2020-01-26T22:40:19.000Z
2022-03-29T05:33:22.000Z
#ifndef _WGTCC_EVALUATOR_H_ #define _WGTCC_EVALUATOR_H_ #include "ast.h" #include "error.h" #include "visitor.h" namespace pp { class Expr; template<typename T> class Evaluator : public Visitor { public: Evaluator() {} virtual ~Evaluator() {} virtual void VisitBinaryOp(BinaryOp* binary); virtual void VisitUnaryOp(UnaryOp* unary); virtual void VisitConditionalOp(ConditionalOp* cond); virtual void VisitFuncCall(FuncCall* funcCall) { Error(funcCall, "expect constant expression"); } virtual void VisitEnumerator(Enumerator* enumer) { val_ = static_cast<T>(enumer->Val()); } virtual void VisitIdentifier(Identifier* ident) { Error(ident, "expect constant expression"); } virtual void VisitObject(Object* obj) { Error(obj, "expect constant expression"); } virtual void VisitConstant(Constant* cons) { if (cons->Type()->IsFloat()) { val_ = static_cast<T>(cons->FVal()); } else if (cons->Type()->IsInteger()) { val_ = static_cast<T>(cons->IVal()); } else { assert(false); } } virtual void VisitTempVar(TempVar* tempVar) { assert(false); } // We may should assert here virtual void VisitDeclaration(Declaration* init) {} virtual void VisitIfStmt(IfStmt* ifStmt) {} virtual void VisitJumpStmt(JumpStmt* jumpStmt) {} virtual void VisitReturnStmt(ReturnStmt* returnStmt) {} virtual void VisitLabelStmt(LabelStmt* labelStmt) {} virtual void VisitEmptyStmt(EmptyStmt* emptyStmt) {} virtual void VisitCompoundStmt(CompoundStmt* compStmt) {} virtual void VisitFuncDef(FuncDef* funcDef) {} virtual void VisitTranslationUnit(TranslationUnit* unit) {} T Eval(Expr* expr) { expr->Accept(this); return val_; } private: T val_; }; struct Addr { std::string label_; int offset_; }; template<> class Evaluator<Addr> : public Visitor { public: Evaluator<Addr>() {} virtual ~Evaluator<Addr>() {} virtual void VisitBinaryOp(BinaryOp* binary); virtual void VisitUnaryOp(UnaryOp* unary); virtual void VisitConditionalOp(ConditionalOp* cond); virtual void VisitFuncCall(FuncCall* funcCall) { Error(funcCall, "expect constant expression"); } virtual void VisitEnumerator(Enumerator* enumer) { addr_.offset_ = enumer->Val(); } virtual void VisitIdentifier(Identifier* ident) { addr_.label_ = ident->Name(); addr_.offset_ = 0; } virtual void VisitObject(Object* obj) { if (!obj->IsStatic()) { Error(obj, "expect static object"); } addr_.label_ = obj->Repr(); addr_.offset_ = 0; } virtual void VisitConstant(Constant* cons); virtual void VisitTempVar(TempVar* tempVar) { assert(false); } // We may should assert here virtual void VisitDeclaration(Declaration* init) {} virtual void VisitIfStmt(IfStmt* ifStmt) {} virtual void VisitJumpStmt(JumpStmt* jumpStmt) {} virtual void VisitReturnStmt(ReturnStmt* returnStmt) {} virtual void VisitLabelStmt(LabelStmt* labelStmt) {} virtual void VisitEmptyStmt(EmptyStmt* emptyStmt) {} virtual void VisitCompoundStmt(CompoundStmt* compStmt) {} virtual void VisitFuncDef(FuncDef* funcDef) {} virtual void VisitTranslationUnit(TranslationUnit* unit) {} Addr Eval(Expr* expr) { expr->Accept(this); return addr_; } private: Addr addr_; }; } #endif
31.384
70
0.591894
[ "object" ]
6cdc4a94084e945616e1eb6f65c06bb728ecc53c
12,323
c
C
hexagon/ops/src/op_implode_batch.c
supersat/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
37
2018-07-09T09:52:13.000Z
2022-01-24T23:15:54.000Z
hexagon/ops/src/op_implode_batch.c
supersat/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
13
2018-08-03T02:29:04.000Z
2020-06-05T22:09:32.000Z
hexagon/ops/src/op_implode_batch.c
waau/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
11
2018-07-13T02:34:05.000Z
2021-07-22T09:29:12.000Z
/* * Copyright (c) 2017-2019, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) 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 Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. 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. * */ #include <nn_graph.h> #include <string.h> #include <quantize.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #define INPUT_IDX 0 #define INPUT_MIN_IDX 1 #define INPUT_MAX_IDX 2 #define PAD_IDX 3 #define TILE_IDX 4 #define OUTPUT_DATA_IDX 0 #define OUTPUT_MIN_IDX 1 #define OUTPUT_MAX_IDX 2 #define OUTPUT_SHAPE_IDX 3 static int implode_batch_ref_execute(struct nn_node *self, struct nn_graph *nn){ const struct tensor *input_tensor = self->inputs[INPUT_IDX]; const struct tensor *min_tensor = self->inputs[INPUT_MIN_IDX]; const struct tensor *max_tensor = self->inputs[INPUT_MAX_IDX]; const struct tensor *pad_tensor = self->inputs[PAD_IDX]; const struct tensor *tile_tensor = self->inputs[TILE_IDX]; struct tensor *output_tensor = self->outputs[OUTPUT_DATA_IDX]; struct tensor *shape_tensor = self->outputs[OUTPUT_SHAPE_IDX]; uint8_t* in_data = input_tensor->data; uint8_t* out_data = output_tensor->data; tensor_copy(self->outputs[OUTPUT_MIN_IDX],min_tensor); tensor_copy(self->outputs[OUTPUT_MAX_IDX],max_tensor); float min_f = tensor_get_float(min_tensor,0); float max_f = tensor_get_float(max_tensor,0); float pad_f = tensor_get_float(pad_tensor,0); if (min_f > pad_f || max_f < pad_f){ return errlog(nn, "pad value %f does not fall in range of input (%f to %f)",pad_f,min_f,max_f); } uint8_t pad_value = quantize_uint8(pad_f,min_f,max_f); int32_t in_height = input_tensor->shape.height; int32_t pad_height = pad_tensor->shape.height; int32_t tile_height = tile_tensor->shape.height; int32_t big_height = in_height + pad_height; int32_t out_height = tile_height*(big_height)-pad_height; int32_t in_width = input_tensor->shape.width; int32_t pad_width = pad_tensor->shape.width; int32_t tile_width = tile_tensor->shape.width; int32_t big_width = in_width + pad_width; int32_t out_width = tile_width*big_width-pad_width; int32_t depth = input_tensor->shape.depth; int32_t total_batches = input_tensor->shape.batches; int32_t in_size = in_height * in_width * depth; int32_t out_size = out_height * out_width * depth; if(output_tensor->max_size < out_size){ return errlog(nn,"out too small %d < %d",output_tensor->max_size,out_size); } output_tensor->data_size = out_size; memset(out_data,pad_value,out_size); int32_t in_row_bytes = in_width * depth * sizeof (uint8_t); int32_t out_row_bytes = out_width * depth * sizeof (uint8_t); int32_t data_pad_per_width_bytes = big_width * depth * sizeof (uint8_t); // int32_t data_pad_per_width_bytes = tile_height * big_height; tensor_set_shape(output_tensor,1,out_height,out_width,depth); tensor_set_shape(shape_tensor,1,1,1,4); float shape[] = {total_batches,in_height,in_width,depth}; if(shape_tensor->max_size < sizeof(shape)){ return errlog(nn,"shape out too small %d < %d",shape_tensor->max_size,sizeof(shape)); } shape_tensor->data_size = sizeof(shape); for (int i = 0; i < 4;i++){ tensor_set_float(shape_tensor,i,shape[i]); } int32_t batch_height_index,batch_width_index, current_num_batches; int32_t out_batched_row, out_batched_col,out_cur_batch_byte_index,in_cur_batch_byte_index; int32_t out_row_index,in_row_index,in_byte_index,out_byte_index; for (batch_height_index=0; batch_height_index<tile_height; batch_height_index++){ out_batched_row = big_height * batch_height_index; for (batch_width_index=0; batch_width_index<tile_width; batch_width_index++){ current_num_batches = batch_height_index * tile_width + batch_width_index; if (current_num_batches >total_batches){ break; } out_batched_col = big_width * batch_width_index; out_cur_batch_byte_index = data_pad_per_width_bytes*batch_width_index; in_cur_batch_byte_index = current_num_batches * in_size; for (in_row_index = 0; in_row_index <in_height; in_row_index++){ out_row_index = out_batched_row + in_row_index; in_byte_index = in_cur_batch_byte_index+ in_row_index * in_row_bytes; out_byte_index = out_cur_batch_byte_index + out_row_index * out_row_bytes; memcpy(out_data+out_byte_index,in_data+in_byte_index,in_row_bytes); } } } return 0; } struct implode_worker{ struct nn_node *self; uint8_t* in_data; uint8_t* out_data; int32_t in_height; int32_t pad_height; int32_t tile_height; int32_t out_height; int32_t in_width; int32_t pad_width; int32_t tile_width; int32_t out_width; int32_t depth; int32_t total_batches; uint8_t pad_value; }; static void implode_batch_hvx(struct nn_graph *nn, void *vinfo){ struct implode_worker *inf=(struct implode_worker*)vinfo; uint8_t* in_data=inf->in_data; uint8_t* out_data=inf->out_data; int32_t in_height=inf->in_height; int32_t pad_height=inf->pad_height; int32_t tile_height=inf->tile_height; int32_t out_height=inf->out_height; int32_t in_width=inf->in_width; int32_t pad_width=inf->pad_width; int32_t tile_width=inf->tile_width; int32_t out_width=inf->out_width; int32_t depth=inf->depth; int32_t total_batches=inf->total_batches; uint8_t pad_value=inf->pad_value; int32_t in_size=in_height*in_width*depth; int32_t out_size=out_height*out_width*depth; vmemset_asm(out_data,pad_value,out_size); int32_t in_row_bytes = in_width * depth * sizeof (uint8_t); int32_t out_row_bytes = out_width * depth * sizeof (uint8_t); int32_t data_pad_per_width_bytes = (in_width+pad_width) * depth * sizeof (uint8_t); int32_t batch_height_index,batch_width_index, current_num_batches; int32_t out_batched_row, out_batched_col,out_cur_batch_byte_index,in_cur_batch_byte_index; int32_t out_row_index,in_row_index,in_byte_index,out_byte_index; for (batch_height_index=0; batch_height_index<tile_height; batch_height_index++){ out_batched_row = (in_height+pad_height) * batch_height_index; for (batch_width_index=0; batch_width_index<tile_width; batch_width_index++){ current_num_batches = batch_height_index * tile_width + batch_width_index; if (current_num_batches >total_batches){ break; } out_batched_col = (in_width+pad_width) * batch_width_index; out_cur_batch_byte_index = data_pad_per_width_bytes*batch_width_index; in_cur_batch_byte_index = current_num_batches * in_size; for (in_row_index = 0; in_row_index <in_height; in_row_index++){ out_row_index = out_batched_row + in_row_index; in_byte_index = in_cur_batch_byte_index+ in_row_index * in_row_bytes; out_byte_index = out_cur_batch_byte_index + out_row_index * out_row_bytes; vmemcpy_asm(out_data+out_byte_index,in_data+in_byte_index,in_row_bytes); } } } nn_sem_post(inf->self->opaque); } static int implode_batch_hvx_execute(struct nn_node *self, struct nn_graph *nn){ const struct tensor *input_tensor = self->inputs[INPUT_IDX]; const struct tensor *min_tensor = self->inputs[INPUT_MIN_IDX]; const struct tensor *max_tensor = self->inputs[INPUT_MAX_IDX]; const struct tensor *pad_tensor = self->inputs[PAD_IDX]; const struct tensor *tile_tensor = self->inputs[TILE_IDX]; struct tensor *output_tensor = self->outputs[OUTPUT_DATA_IDX]; struct tensor *shape_tensor = self->outputs[OUTPUT_SHAPE_IDX]; uint8_t* in_data = input_tensor->data; uint8_t* out_data = output_tensor->data; tensor_copy(self->outputs[OUTPUT_MIN_IDX],min_tensor); tensor_copy(self->outputs[OUTPUT_MAX_IDX],max_tensor); float min_f = tensor_get_float(min_tensor,0); float max_f = tensor_get_float(max_tensor,0); float pad_f = tensor_get_float(pad_tensor,0); if (min_f > pad_f || max_f < pad_f){ return errlog(nn, "pad value %f does not fall in range of input (%f to %f)",pad_f,min_f,max_f); } uint8_t pad_value = quantize_uint8(pad_f,min_f,max_f); int32_t in_height = input_tensor->shape.height; int32_t pad_height = pad_tensor->shape.height; int32_t tile_height = tile_tensor->shape.height; int32_t out_height = tile_height*(in_height + pad_height)-pad_height; int32_t in_width = input_tensor->shape.width; int32_t pad_width = pad_tensor->shape.width; int32_t tile_width = tile_tensor->shape.width; int32_t out_width = tile_width*(in_width + pad_width)-pad_width; int32_t depth = input_tensor->shape.depth; int32_t total_batches = input_tensor->shape.batches; int32_t out_size = out_height * out_width * depth; if(output_tensor->max_size < out_size){ return errlog(nn,"out too small %d < %d",output_tensor->max_size,out_size); } output_tensor->data_size = out_size; tensor_set_shape(output_tensor,1,out_height,out_width,depth); tensor_set_shape(shape_tensor,1,1,1,4); float shape[] = {total_batches,in_height,in_width,depth}; if(shape_tensor->max_size < sizeof(shape)){ return errlog(nn,"shape out too small %d < %d",shape_tensor->max_size,sizeof(shape)); } shape_tensor->data_size = sizeof(shape); memcpy(shape_tensor->data,shape,sizeof(shape)); struct implode_worker td={ .self=self, .in_data=in_data, .out_data=out_data, .in_height=in_height, .pad_height=pad_height, .tile_height=tile_height, .out_height=out_height, .in_width=in_width, .pad_width=pad_width, .tile_width=tile_width, .out_width=out_width, .depth=depth, .total_batches=total_batches, .pad_value=pad_value }; nn_sem_t sem; nn_sem_init(&sem,0); self->opaque = &sem; nn_os_work_for_vector(nn, implode_batch_hvx, &td); nn_sem_wait(&sem); self->opaque = NULL; return 0; } struct nn_node_ops nn_ops_for_Implode_8_ref = { .execute = implode_batch_ref_execute, .check = NULL, .ctor = node_alloc_common, .dtor = node_free_common, .n_inputs = NN_IOCOUNT(5), .n_outputs = NN_IOCOUNT(4), }; struct nn_node_ops nn_ops_for_Implode_8 = { .execute = implode_batch_hvx_execute, .check = NULL, .ctor = node_alloc_common, .dtor = node_free_common, .n_inputs = NN_IOCOUNT(5), .n_outputs = NN_IOCOUNT(4), };
40.669967
103
0.716465
[ "shape" ]
6cde9a45c7959fe38422859671079832f857eeda
5,781
h
C
include/tsar/Support/IRUtils.h
Valeriya-avt/tsar
ccd3bcaed653f3bb592ba179d5c2d4ce2c5cc725
[ "Apache-2.0" ]
14
2019-11-04T15:03:40.000Z
2021-09-07T17:29:40.000Z
include/tsar/Support/IRUtils.h
Valeriya-avt/tsar
ccd3bcaed653f3bb592ba179d5c2d4ce2c5cc725
[ "Apache-2.0" ]
11
2019-11-29T21:18:12.000Z
2021-12-22T21:36:40.000Z
include/tsar/Support/IRUtils.h
Valeriya-avt/tsar
ccd3bcaed653f3bb592ba179d5c2d4ce2c5cc725
[ "Apache-2.0" ]
17
2019-10-15T13:56:35.000Z
2021-10-20T17:21:14.000Z
//===----- IRUtils.h ---- Utils for exploring LLVM IR -----------*- C++ -*-===// // // Traits Static Analyzer (SAPFOR) // // Copyright 2018 DVM System Group // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// // // This file defines helpful functions to access IR-level information. // //===----------------------------------------------------------------------===// #ifndef TSAR_SUPPORT_IR_UTILS_H #define TSAR_SUPPORT_IR_UTILS_H #include <llvm/Analysis/LoopInfo.h> #include <llvm/IR/Type.h> #include <llvm/ADT/SmallVector.h> namespace tsar { /// Returns argument with a specified number or nullptr. llvm::Argument * getArgument(llvm::Function &F, std::size_t ArgNo); /// Returns number of dimensions in a specified type or 0 if it is not an array. inline unsigned dimensionsNum(const llvm::Type *Ty) { unsigned Dims = 0; for (; Ty->isArrayTy(); Ty = Ty->getArrayElementType(), ++Dims); return Dims; } /// Returns number of dimensions and elements in a specified type and type of /// innermost array element. If `Ty` is not an array type this function returns /// 0,1, Ty. inline std::tuple<unsigned, uint64_t, llvm::Type *> arraySize(llvm::Type *Ty) { assert(Ty && "Type must not be null!"); unsigned Dims = 0; uint64_t NumElements = 1; for (; Ty->isArrayTy(); Ty = Ty->getArrayElementType(), ++Dims) NumElements *= llvm::cast<llvm::ArrayType>(Ty)->getArrayNumElements(); return std::make_tuple(Dims, NumElements, Ty); } /// Return true if a specified type is a pointer type or contains sub-types /// which are pointer types. inline bool hasUnderlyingPointer(llvm::Type *Ty) { assert(Ty && "Type must not be null!"); if (Ty->isPointerTy()) return true; if (Ty->isArrayTy()) return hasUnderlyingPointer(Ty->getArrayElementType()); if (Ty->isVectorTy()) return hasUnderlyingPointer(Ty->getScalarType()); if (Ty->isStructTy()) for (unsigned I = 0, EI = Ty->getStructNumElements(); I < EI; ++I) return hasUnderlyingPointer(Ty->getStructElementType(I)); return false; } /// Return true if a specified value points to the memory which is only /// available inside a specific loop. bool pointsToLocalMemory(const llvm::Value &V, const llvm::Loop &L); namespace detail { /// Applies a specified function object to each loop in a loop tree. template<class Function> void for_each_loop(llvm::LoopInfo::reverse_iterator ReverseI, llvm::LoopInfo::reverse_iterator ReverseEI, Function F) { for (; ReverseI != ReverseEI; ++ReverseI) { F(*ReverseI); for_each_loop((*ReverseI)->rbegin(), (*ReverseI)->rend(), F); } } } /// Applies a specified function object to each loop in a loop tree. template<class Function> Function for_each_loop(const llvm::LoopInfo &LI, Function F) { detail::for_each_loop(LI.rbegin(), LI.rend(), F); return std::move(F); } /// Check if predicate is `true` for at least one instruction which uses /// result of a specified instruction. /// /// This function tries to find instruction which covers each user of a /// specified instruction (a user may be a constant expression for example). /// If corresponding instruction is not found then a user is passed to a /// functor. template<class FunctionT> bool any_of_user_insts(llvm::Instruction &I, FunctionT F) { for (auto *U : I.users()) { if (auto *UI = llvm::dyn_cast<llvm::Instruction>(U)) { if (F(UI)) return true; } else if (auto *CE = llvm::dyn_cast<llvm::ConstantExpr>(U)) { llvm::SmallVector<llvm::ConstantExpr *, 4> WorkList{CE}; do { auto *Expr = WorkList.pop_back_val(); for (auto *ExprU : Expr->users()) { if (auto ExprUseInst = llvm::dyn_cast<llvm::Instruction>(ExprU)) { if (F(UI)) return true; } else if (auto Expr = llvm::dyn_cast<llvm::ConstantExpr>(ExprU)) { WorkList.push_back(Expr); } else if (F(Expr)) { return true; } } } while (!WorkList.empty()); } else if (F(UI)) { return true; } } return false; } /// Apply a specified function to each instruction which uses result of a /// specified instruction. /// /// This function tries to find instruction which covers each user of a /// specified instruction (a user may be a constant expression for example). /// If corresponding instruction is not found then a user is passed to a /// functor. template<class FunctionT> void for_each_user_insts(llvm::Instruction &I, FunctionT F) { for (auto *U : I.users()) { if (auto *UI = llvm::dyn_cast<llvm::Instruction>(U)) { F(UI); } else if (auto *CE = llvm::dyn_cast<llvm::ConstantExpr>(U)) { llvm::SmallVector<llvm::ConstantExpr *, 4> WorkList{ CE }; do { auto *Expr = WorkList.pop_back_val(); for (auto *ExprU : Expr->users()) { if (auto ExprUseInst = llvm::dyn_cast<llvm::Instruction>(ExprU)) F(UI); else if (auto ExprUseExpr = llvm::dyn_cast<llvm::ConstantExpr>(ExprU)) WorkList.push_back(ExprUseExpr); else F(Expr); } } while (!WorkList.empty()); } else F(UI); } } } #endif//TSAR_SUPPORT_IR_UTILS_H
35.466258
80
0.646774
[ "object" ]
6cdfc653c29733e70d0663aff50997e53e695fb4
44,993
c
C
FreeBSD/sys/netipsec/ipsec.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
91
2018-11-24T05:33:58.000Z
2022-03-16T05:58:05.000Z
FreeBSD/sys/netipsec/ipsec.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/sys/netipsec/ipsec.c
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
18
2018-11-24T10:35:29.000Z
2021-04-22T07:22:10.000Z
/* $FreeBSD$ */ /* $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */ /*- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ /* * IPsec controller part. */ #include "opt_inet.h" #include "opt_inet6.h" #include "opt_ipsec.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <sys/domain.h> #include <sys/priv.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/errno.h> #include <sys/hhook.h> #include <sys/time.h> #include <sys/kernel.h> #include <sys/syslog.h> #include <sys/sysctl.h> #include <sys/proc.h> #include <net/if.h> #include <net/if_enc.h> #include <net/if_var.h> #include <net/vnet.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_var.h> #include <netinet/in_var.h> #include <netinet/udp.h> #include <netinet/udp_var.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <netinet/ip6.h> #ifdef INET6 #include <netinet6/ip6_var.h> #endif #include <netinet/in_pcb.h> #ifdef INET6 #include <netinet/icmp6.h> #endif #include <sys/types.h> #include <netipsec/ipsec.h> #ifdef INET6 #include <netipsec/ipsec6.h> #endif #include <netipsec/ah_var.h> #include <netipsec/esp_var.h> #include <netipsec/ipcomp.h> /*XXX*/ #include <netipsec/ipcomp_var.h> #include <netipsec/key.h> #include <netipsec/keydb.h> #include <netipsec/key_debug.h> #include <netipsec/xform.h> #include <machine/in_cksum.h> #include <opencrypto/cryptodev.h> #ifdef IPSEC_DEBUG VNET_DEFINE(int, ipsec_debug) = 1; #else VNET_DEFINE(int, ipsec_debug) = 0; #endif /* NB: name changed so netstat doesn't use it. */ VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat); VNET_PCPUSTAT_SYSINIT(ipsec4stat); #ifdef VIMAGE VNET_PCPUSTAT_SYSUNINIT(ipsec4stat); #endif /* VIMAGE */ VNET_DEFINE(int, ip4_ah_offsetmask) = 0; /* maybe IP_DF? */ /* DF bit on encap. 0: clear 1: set 2: copy */ VNET_DEFINE(int, ip4_ipsec_dfbit) = 0; VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE; /* ECN ignore(-1)/forbidden(0)/allowed(1) */ VNET_DEFINE(int, ip4_ipsec_ecn) = 0; VNET_DEFINE(int, ip4_esp_randpad) = -1; static VNET_DEFINE(struct secpolicy, def_policy); #define V_def_policy VNET(def_policy) /* * Crypto support requirements: * * 1 require hardware support * -1 require software support * 0 take anything */ VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE; FEATURE(ipsec, "Internet Protocol Security (IPsec)"); #ifdef IPSEC_NAT_T FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')"); #endif SYSCTL_DECL(_net_inet_ipsec); /* net.inet.ipsec */ SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(def_policy).policy, 0, "IPsec default policy."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0, "Default ESP transport mode level"); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0, "Default ESP tunnel mode level."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0, "AH transfer mode default level."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0, "AH tunnel mode default level."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0, "If set clear type-of-service field when doing AH computation."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK, ah_offsetmask, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_offsetmask), 0, "If not set clear offset field mask when doing AH computation."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0, "Do not fragment bit on encap."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0, "Explicit Congestion Notification handling."); SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0, "Enable IPsec debugging output when set."); SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0, "Crypto driver selection."); SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat, ipsec4stat, "IPsec IPv4 statistics."); #ifdef REGRESSION /* * When set to 1, IPsec will send packets with the same sequence number. * This allows to verify if the other side has proper replay attacks detection. */ VNET_DEFINE(int, ipsec_replay) = 0; SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0, "Emulate replay attack"); /* * When set 1, IPsec will send packets with corrupted HMAC. * This allows to verify if the other side properly detects modified packets. */ VNET_DEFINE(int, ipsec_integrity) = 0; SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0, "Emulate man-in-the-middle attack"); #endif #ifdef INET6 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat); VNET_PCPUSTAT_SYSINIT(ipsec6stat); #ifdef VIMAGE VNET_PCPUSTAT_SYSUNINIT(ipsec6stat); #endif /* VIMAGE */ VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE; VNET_DEFINE(int, ip6_ipsec_ecn) = 0; /* ECN ignore(-1)/forbidden(0)/allowed(1) */ SYSCTL_DECL(_net_inet6_ipsec6); /* net.inet6.ipsec6 */ SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(def_policy).policy, 0, "IPsec default policy."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0, "Default ESP transport mode level."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0, "Default ESP tunnel mode level."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0, "AH transfer mode default level."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0, "AH tunnel mode default level."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0, "Explicit Congestion Notification handling."); SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug, CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0, "Enable IPsec debugging output when set."); SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats, struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics."); #endif /* INET6 */ static int ipsec_in_reject(struct secpolicy *, const struct mbuf *); static int ipsec_setspidx_inpcb(const struct mbuf *, struct inpcb *); static int ipsec_setspidx(const struct mbuf *, struct secpolicyindex *, int); static void ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *, int); static int ipsec4_setspidx_ipaddr(const struct mbuf *, struct secpolicyindex *); #ifdef INET6 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int); static int ipsec6_setspidx_ipaddr(const struct mbuf *, struct secpolicyindex *); #endif static void ipsec_delpcbpolicy(struct inpcbpolicy *); static struct secpolicy *ipsec_deepcopy_policy(struct secpolicy *src); static void vshiftl(unsigned char *, int, int); MALLOC_DEFINE(M_IPSEC_INPCB, "inpcbpolicy", "inpcb-resident ipsec policy"); /* * Return a held reference to the default SP. */ static struct secpolicy * key_allocsp_default(const char* where, int tag) { struct secpolicy *sp; KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP key_allocsp_default from %s:%u\n", where, tag)); sp = &V_def_policy; if (sp->policy != IPSEC_POLICY_DISCARD && sp->policy != IPSEC_POLICY_NONE) { ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n", sp->policy, IPSEC_POLICY_NONE)); sp->policy = IPSEC_POLICY_NONE; } key_addref(sp); KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP key_allocsp_default returns SP:%p (%u)\n", sp, sp->refcnt)); return (sp); } #define KEY_ALLOCSP_DEFAULT() \ key_allocsp_default(__FILE__, __LINE__) /* * For OUTBOUND packet having a socket. Searching SPD for packet, * and return a pointer to SP. * OUT: NULL: no apropreate SP found, the following value is set to error. * 0 : bypass * EACCES : discard packet. * ENOENT : ipsec_acquire() in progress, maybe. * others : error occurred. * others: a pointer to SP * * NOTE: IPv6 mapped adddress concern is implemented here. */ struct secpolicy * ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir) { struct secpolicy *sp; IPSEC_ASSERT(tdbi != NULL, ("null tdbi")); IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND, ("invalid direction %u", dir)); sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir); if (sp == NULL) /*XXX????*/ sp = KEY_ALLOCSP_DEFAULT(); IPSEC_ASSERT(sp != NULL, ("null SP")); return (sp); } /* * For OUTBOUND packet having a socket. Searching SPD for packet, * and return a pointer to SP. * OUT: NULL: no apropreate SP found, the following value is set to error. * 0 : bypass * EACCES : discard packet. * ENOENT : ipsec_acquire() in progress, maybe. * others : error occurred. * others: a pointer to SP * * NOTE: IPv6 mapped adddress concern is implemented here. */ static struct secpolicy * ipsec_getpolicybysock(const struct mbuf *m, u_int dir, struct inpcb *inp, int *error) { struct inpcbpolicy *pcbsp; struct secpolicy *currsp = NULL; /* Policy on socket. */ struct secpolicy *sp; IPSEC_ASSERT(m != NULL, ("null mbuf")); IPSEC_ASSERT(inp != NULL, ("null inpcb")); IPSEC_ASSERT(error != NULL, ("null error")); IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND, ("invalid direction %u", dir)); if (!key_havesp(dir)) { /* No SP found, use system default. */ sp = KEY_ALLOCSP_DEFAULT(); return (sp); } /* Set spidx in pcb. */ *error = ipsec_setspidx_inpcb(m, inp); if (*error) return (NULL); pcbsp = inp->inp_sp; IPSEC_ASSERT(pcbsp != NULL, ("null pcbsp")); switch (dir) { case IPSEC_DIR_INBOUND: currsp = pcbsp->sp_in; break; case IPSEC_DIR_OUTBOUND: currsp = pcbsp->sp_out; break; } IPSEC_ASSERT(currsp != NULL, ("null currsp")); if (pcbsp->priv) { /* When privilieged socket. */ switch (currsp->policy) { case IPSEC_POLICY_BYPASS: case IPSEC_POLICY_IPSEC: key_addref(currsp); sp = currsp; break; case IPSEC_POLICY_ENTRUST: /* Look for a policy in SPD. */ sp = KEY_ALLOCSP(&currsp->spidx, dir); if (sp == NULL) /* No SP found. */ sp = KEY_ALLOCSP_DEFAULT(); break; default: ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n", __func__, currsp->policy)); *error = EINVAL; return (NULL); } } else { /* Unpriv, SPD has policy. */ sp = KEY_ALLOCSP(&currsp->spidx, dir); if (sp == NULL) { /* No SP found. */ switch (currsp->policy) { case IPSEC_POLICY_BYPASS: ipseclog((LOG_ERR, "%s: Illegal policy for " "non-priviliged defined %d\n", __func__, currsp->policy)); *error = EINVAL; return (NULL); case IPSEC_POLICY_ENTRUST: sp = KEY_ALLOCSP_DEFAULT(); break; case IPSEC_POLICY_IPSEC: key_addref(currsp); sp = currsp; break; default: ipseclog((LOG_ERR, "%s: Invalid policy for " "PCB %d\n", __func__, currsp->policy)); *error = EINVAL; return (NULL); } } } IPSEC_ASSERT(sp != NULL, ("null SP (priv %u policy %u", pcbsp->priv, currsp->policy)); KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP %s (priv %u policy %u) allocate SP:%p (refcnt %u)\n", __func__, pcbsp->priv, currsp->policy, sp, sp->refcnt)); return (sp); } /* * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet, * and return a pointer to SP. * OUT: positive: a pointer to the entry for security policy leaf matched. * NULL: no apropreate SP found, the following value is set to error. * 0 : bypass * EACCES : discard packet. * ENOENT : ipsec_acquire() in progress, maybe. * others : error occurred. */ struct secpolicy * ipsec_getpolicybyaddr(const struct mbuf *m, u_int dir, int *error) { struct secpolicyindex spidx; struct secpolicy *sp; IPSEC_ASSERT(m != NULL, ("null mbuf")); IPSEC_ASSERT(error != NULL, ("null error")); IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND, ("invalid direction %u", dir)); sp = NULL; *error = 0; if (key_havesp(dir)) { /* Make an index to look for a policy. */ *error = ipsec_setspidx(m, &spidx, 0); if (*error != 0) { DPRINTF(("%s: setpidx failed, dir %u\n", __func__, dir)); return (NULL); } spidx.dir = dir; sp = KEY_ALLOCSP(&spidx, dir); } if (sp == NULL) /* No SP found, use system default. */ sp = KEY_ALLOCSP_DEFAULT(); IPSEC_ASSERT(sp != NULL, ("null SP")); return (sp); } struct secpolicy * ipsec4_checkpolicy(const struct mbuf *m, u_int dir, int *error, struct inpcb *inp) { struct secpolicy *sp; *error = 0; if (inp == NULL) sp = ipsec_getpolicybyaddr(m, dir, error); else sp = ipsec_getpolicybysock(m, dir, inp, error); if (sp == NULL) { IPSEC_ASSERT(*error != 0, ("getpolicy failed w/o error")); IPSECSTAT_INC(ips_out_inval); return (NULL); } IPSEC_ASSERT(*error == 0, ("sp w/ error set to %u", *error)); switch (sp->policy) { case IPSEC_POLICY_ENTRUST: default: printf("%s: invalid policy %u\n", __func__, sp->policy); /* FALLTHROUGH */ case IPSEC_POLICY_DISCARD: IPSECSTAT_INC(ips_out_polvio); *error = -EINVAL; /* Packet is discarded by caller. */ break; case IPSEC_POLICY_BYPASS: case IPSEC_POLICY_NONE: KEY_FREESP(&sp); sp = NULL; /* NB: force NULL result. */ break; case IPSEC_POLICY_IPSEC: if (sp->req == NULL) /* Acquire a SA. */ *error = key_spdacquire(sp); break; } if (*error != 0) { KEY_FREESP(&sp); sp = NULL; } return (sp); } static int ipsec_setspidx_inpcb(const struct mbuf *m, struct inpcb *inp) { int error; IPSEC_ASSERT(inp != NULL, ("null inp")); IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp")); IPSEC_ASSERT(inp->inp_sp->sp_out != NULL && inp->inp_sp->sp_in != NULL, ("null sp_in || sp_out")); error = ipsec_setspidx(m, &inp->inp_sp->sp_in->spidx, 1); if (error == 0) { inp->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND; inp->inp_sp->sp_out->spidx = inp->inp_sp->sp_in->spidx; inp->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND; } else { bzero(&inp->inp_sp->sp_in->spidx, sizeof (inp->inp_sp->sp_in->spidx)); bzero(&inp->inp_sp->sp_out->spidx, sizeof (inp->inp_sp->sp_in->spidx)); } return (error); } /* * Configure security policy index (src/dst/proto/sport/dport) * by looking at the content of mbuf. * The caller is responsible for error recovery (like clearing up spidx). */ static int ipsec_setspidx(const struct mbuf *m, struct secpolicyindex *spidx, int needport) { struct ip ipbuf; const struct ip *ip = NULL; const struct mbuf *n; u_int v; int len; int error; IPSEC_ASSERT(m != NULL, ("null mbuf")); /* * Validate m->m_pkthdr.len. We see incorrect length if we * mistakenly call this function with inconsistent mbuf chain * (like 4.4BSD tcp/udp processing). XXX Should we panic here? */ len = 0; for (n = m; n; n = n->m_next) len += n->m_len; if (m->m_pkthdr.len != len) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: pkthdr len(%d) mismatch (%d), ignored.\n", __func__, len, m->m_pkthdr.len)); return (EINVAL); } if (m->m_pkthdr.len < sizeof(struct ip)) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: pkthdr len(%d) too small (v4), ignored.\n", __func__, m->m_pkthdr.len)); return (EINVAL); } if (m->m_len >= sizeof(*ip)) ip = mtod(m, const struct ip *); else { m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf); ip = &ipbuf; } v = ip->ip_v; switch (v) { case 4: error = ipsec4_setspidx_ipaddr(m, spidx); if (error) return (error); ipsec4_get_ulp(m, spidx, needport); return (0); #ifdef INET6 case 6: if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: pkthdr len(%d) too small (v6), " "ignored\n", __func__, m->m_pkthdr.len)); return (EINVAL); } error = ipsec6_setspidx_ipaddr(m, spidx); if (error) return (error); ipsec6_get_ulp(m, spidx, needport); return (0); #endif default: KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: " "unknown IP version %u, ignored.\n", __func__, v)); return (EINVAL); } } static void ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx, int needport) { u_int8_t nxt; int off; /* Sanity check. */ IPSEC_ASSERT(m != NULL, ("null mbuf")); IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),("packet too short")); if (m->m_len >= sizeof (struct ip)) { const struct ip *ip = mtod(m, const struct ip *); if (ip->ip_off & htons(IP_MF | IP_OFFMASK)) goto done; off = ip->ip_hl << 2; nxt = ip->ip_p; } else { struct ip ih; m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih); if (ih.ip_off & htons(IP_MF | IP_OFFMASK)) goto done; off = ih.ip_hl << 2; nxt = ih.ip_p; } while (off < m->m_pkthdr.len) { struct ip6_ext ip6e; struct tcphdr th; struct udphdr uh; switch (nxt) { case IPPROTO_TCP: spidx->ul_proto = nxt; if (!needport) goto done_proto; if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) goto done; m_copydata(m, off, sizeof (th), (caddr_t) &th); spidx->src.sin.sin_port = th.th_sport; spidx->dst.sin.sin_port = th.th_dport; return; case IPPROTO_UDP: spidx->ul_proto = nxt; if (!needport) goto done_proto; if (off + sizeof(struct udphdr) > m->m_pkthdr.len) goto done; m_copydata(m, off, sizeof (uh), (caddr_t) &uh); spidx->src.sin.sin_port = uh.uh_sport; spidx->dst.sin.sin_port = uh.uh_dport; return; case IPPROTO_AH: if (off + sizeof(ip6e) > m->m_pkthdr.len) goto done; /* XXX Sigh, this works but is totally bogus. */ m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e); off += (ip6e.ip6e_len + 2) << 2; nxt = ip6e.ip6e_nxt; break; case IPPROTO_ICMP: default: /* XXX Intermediate headers??? */ spidx->ul_proto = nxt; goto done_proto; } } done: spidx->ul_proto = IPSEC_ULPROTO_ANY; done_proto: spidx->src.sin.sin_port = IPSEC_PORT_ANY; spidx->dst.sin.sin_port = IPSEC_PORT_ANY; } /* Assumes that m is sane. */ static int ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx) { static const struct sockaddr_in template = { sizeof (struct sockaddr_in), AF_INET, 0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 } }; spidx->src.sin = template; spidx->dst.sin = template; if (m->m_len < sizeof (struct ip)) { m_copydata(m, offsetof(struct ip, ip_src), sizeof (struct in_addr), (caddr_t) &spidx->src.sin.sin_addr); m_copydata(m, offsetof(struct ip, ip_dst), sizeof (struct in_addr), (caddr_t) &spidx->dst.sin.sin_addr); } else { const struct ip *ip = mtod(m, const struct ip *); spidx->src.sin.sin_addr = ip->ip_src; spidx->dst.sin.sin_addr = ip->ip_dst; } spidx->prefs = sizeof(struct in_addr) << 3; spidx->prefd = sizeof(struct in_addr) << 3; return (0); } #ifdef INET6 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx, int needport) { int off, nxt; struct tcphdr th; struct udphdr uh; struct icmp6_hdr ih; /* Sanity check. */ if (m == NULL) panic("%s: NULL pointer was passed.\n", __func__); KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__); kdebug_mbuf(m)); /* Set default. */ spidx->ul_proto = IPSEC_ULPROTO_ANY; ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY; ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY; nxt = -1; off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt); if (off < 0 || m->m_pkthdr.len < off) return; switch (nxt) { case IPPROTO_TCP: spidx->ul_proto = nxt; if (!needport) break; if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) break; m_copydata(m, off, sizeof(th), (caddr_t)&th); ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport; ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport; break; case IPPROTO_UDP: spidx->ul_proto = nxt; if (!needport) break; if (off + sizeof(struct udphdr) > m->m_pkthdr.len) break; m_copydata(m, off, sizeof(uh), (caddr_t)&uh); ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport; ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport; break; case IPPROTO_ICMPV6: spidx->ul_proto = nxt; if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len) break; m_copydata(m, off, sizeof(ih), (caddr_t)&ih); ((struct sockaddr_in6 *)&spidx->src)->sin6_port = htons((uint16_t)ih.icmp6_type); ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = htons((uint16_t)ih.icmp6_code); break; default: /* XXX Intermediate headers??? */ spidx->ul_proto = nxt; break; } } /* Assumes that m is sane. */ static int ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx) { struct ip6_hdr ip6buf; const struct ip6_hdr *ip6 = NULL; struct sockaddr_in6 *sin6; if (m->m_len >= sizeof(*ip6)) ip6 = mtod(m, const struct ip6_hdr *); else { m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf); ip6 = &ip6buf; } sin6 = (struct sockaddr_in6 *)&spidx->src; bzero(sin6, sizeof(*sin6)); sin6->sin6_family = AF_INET6; sin6->sin6_len = sizeof(struct sockaddr_in6); bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src)); if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) { sin6->sin6_addr.s6_addr16[1] = 0; sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]); } spidx->prefs = sizeof(struct in6_addr) << 3; sin6 = (struct sockaddr_in6 *)&spidx->dst; bzero(sin6, sizeof(*sin6)); sin6->sin6_family = AF_INET6; sin6->sin6_len = sizeof(struct sockaddr_in6); bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst)); if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) { sin6->sin6_addr.s6_addr16[1] = 0; sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]); } spidx->prefd = sizeof(struct in6_addr) << 3; return (0); } #endif int ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type) { int idx; switch (ctx->af) { #ifdef INET case AF_INET: idx = HHOOK_IPSEC_INET; break; #endif #ifdef INET6 case AF_INET6: idx = HHOOK_IPSEC_INET6; break; #endif default: return (EPFNOSUPPORT); } if (type == HHOOK_TYPE_IPSEC_IN) HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL); else HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL); if (*ctx->mp == NULL) return (EACCES); return (0); } static void ipsec_delpcbpolicy(struct inpcbpolicy *p) { free(p, M_IPSEC_INPCB); } /* Initialize policy in PCB. */ int ipsec_init_policy(struct socket *so, struct inpcbpolicy **pcb_sp) { struct inpcbpolicy *new; /* Sanity check. */ if (so == NULL || pcb_sp == NULL) panic("%s: NULL pointer was passed.\n", __func__); new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy), M_IPSEC_INPCB, M_NOWAIT|M_ZERO); if (new == NULL) { ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__)); return (ENOBUFS); } new->priv = IPSEC_IS_PRIVILEGED_SO(so); if ((new->sp_in = KEY_NEWSP()) == NULL) { ipsec_delpcbpolicy(new); return (ENOBUFS); } new->sp_in->policy = IPSEC_POLICY_ENTRUST; if ((new->sp_out = KEY_NEWSP()) == NULL) { KEY_FREESP(&new->sp_in); ipsec_delpcbpolicy(new); return (ENOBUFS); } new->sp_out->policy = IPSEC_POLICY_ENTRUST; *pcb_sp = new; return (0); } /* Copy old IPsec policy into new. */ int ipsec_copy_policy(struct inpcbpolicy *old, struct inpcbpolicy *new) { struct secpolicy *sp; sp = ipsec_deepcopy_policy(old->sp_in); if (sp) { KEY_FREESP(&new->sp_in); new->sp_in = sp; } else return (ENOBUFS); sp = ipsec_deepcopy_policy(old->sp_out); if (sp) { KEY_FREESP(&new->sp_out); new->sp_out = sp; } else return (ENOBUFS); new->priv = old->priv; return (0); } struct ipsecrequest * ipsec_newisr(void) { struct ipsecrequest *p; p = malloc(sizeof(struct ipsecrequest), M_IPSEC_SR, M_NOWAIT|M_ZERO); if (p != NULL) IPSECREQUEST_LOCK_INIT(p); return (p); } void ipsec_delisr(struct ipsecrequest *p) { IPSECREQUEST_LOCK_DESTROY(p); free(p, M_IPSEC_SR); } /* Deep-copy a policy in PCB. */ static struct secpolicy * ipsec_deepcopy_policy(struct secpolicy *src) { struct ipsecrequest *newchain = NULL; struct ipsecrequest *p; struct ipsecrequest **q; struct ipsecrequest *r; struct secpolicy *dst; if (src == NULL) return (NULL); dst = KEY_NEWSP(); if (dst == NULL) return (NULL); /* * Deep-copy IPsec request chain. This is required since struct * ipsecrequest is not reference counted. */ q = &newchain; for (p = src->req; p; p = p->next) { *q = ipsec_newisr(); if (*q == NULL) goto fail; (*q)->saidx.proto = p->saidx.proto; (*q)->saidx.mode = p->saidx.mode; (*q)->level = p->level; (*q)->saidx.reqid = p->saidx.reqid; bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src)); bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst)); (*q)->sp = dst; q = &((*q)->next); } dst->req = newchain; dst->policy = src->policy; /* Do not touch the refcnt fields. */ return (dst); fail: for (p = newchain; p; p = r) { r = p->next; ipsec_delisr(p); p = NULL; } KEY_FREESP(&dst); return (NULL); } /* Set policy and IPsec request if present. */ static int ipsec_set_policy_internal(struct secpolicy **pcb_sp, int optname, caddr_t request, size_t len, struct ucred *cred) { struct sadb_x_policy *xpl; struct secpolicy *newsp = NULL; int error; /* Sanity check. */ if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL) return (EINVAL); if (len < sizeof(*xpl)) return (EINVAL); xpl = (struct sadb_x_policy *)request; KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: passed policy\n", __func__); kdebug_sadb_x_policy((struct sadb_ext *)xpl)); /* Check policy type. */ /* ipsec_set_policy_internal() accepts IPSEC, ENTRUST and BYPASS. */ if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE) return (EINVAL); /* Check privileged socket. */ if (cred != NULL && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) { error = priv_check_cred(cred, PRIV_NETINET_IPSEC, 0); if (error) return (EACCES); } /* Allocating new SP entry. */ if ((newsp = key_msg2sp(xpl, len, &error)) == NULL) return (error); /* Clear old SP and set new SP. */ KEY_FREESP(pcb_sp); *pcb_sp = newsp; KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: new policy\n", __func__); kdebug_secpolicy(newsp)); return (0); } int ipsec_set_policy(struct inpcb *inp, int optname, caddr_t request, size_t len, struct ucred *cred) { struct sadb_x_policy *xpl; struct secpolicy **pcb_sp; /* Sanity check. */ if (inp == NULL || request == NULL) return (EINVAL); if (len < sizeof(*xpl)) return (EINVAL); xpl = (struct sadb_x_policy *)request; /* Select direction. */ switch (xpl->sadb_x_policy_dir) { case IPSEC_DIR_INBOUND: pcb_sp = &inp->inp_sp->sp_in; break; case IPSEC_DIR_OUTBOUND: pcb_sp = &inp->inp_sp->sp_out; break; default: ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__, xpl->sadb_x_policy_dir)); return (EINVAL); } return (ipsec_set_policy_internal(pcb_sp, optname, request, len, cred)); } int ipsec_get_policy(struct inpcb *inp, caddr_t request, size_t len, struct mbuf **mp) { struct sadb_x_policy *xpl; struct secpolicy *pcb_sp; /* Sanity check. */ if (inp == NULL || request == NULL || mp == NULL) return (EINVAL); IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp")); if (len < sizeof(*xpl)) return (EINVAL); xpl = (struct sadb_x_policy *)request; /* Select direction. */ switch (xpl->sadb_x_policy_dir) { case IPSEC_DIR_INBOUND: pcb_sp = inp->inp_sp->sp_in; break; case IPSEC_DIR_OUTBOUND: pcb_sp = inp->inp_sp->sp_out; break; default: ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__, xpl->sadb_x_policy_dir)); return (EINVAL); } /* Sanity check. Should be an IPSEC_ASSERT. */ if (pcb_sp == NULL) return (EINVAL); *mp = key_sp2msg(pcb_sp); if (!*mp) { ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__)); return (ENOBUFS); } (*mp)->m_type = MT_DATA; KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__); kdebug_mbuf(*mp)); return (0); } /* Delete policy in PCB. */ int ipsec_delete_pcbpolicy(struct inpcb *inp) { IPSEC_ASSERT(inp != NULL, ("null inp")); if (inp->inp_sp == NULL) return (0); if (inp->inp_sp->sp_in != NULL) KEY_FREESP(&inp->inp_sp->sp_in); if (inp->inp_sp->sp_out != NULL) KEY_FREESP(&inp->inp_sp->sp_out); ipsec_delpcbpolicy(inp->inp_sp); inp->inp_sp = NULL; return (0); } /* * Return current level. * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned. */ u_int ipsec_get_reqlevel(struct ipsecrequest *isr) { u_int level = 0; u_int esp_trans_deflev, esp_net_deflev; u_int ah_trans_deflev, ah_net_deflev; IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("null argument")); IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family, ("af family mismatch, src %u, dst %u", isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family)); /* XXX Note that we have ipseclog() expanded here - code sync issue. */ #define IPSEC_CHECK_DEFAULT(lev) \ (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE \ && (lev) != IPSEC_LEVEL_UNIQUE) \ ? (V_ipsec_debug \ ? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\ (lev), IPSEC_LEVEL_REQUIRE) \ : 0), \ (lev) = IPSEC_LEVEL_REQUIRE, \ (lev) \ : (lev)) /* Set default level. */ switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) { #ifdef INET case AF_INET: esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev); esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev); ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev); ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev); break; #endif #ifdef INET6 case AF_INET6: esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev); esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev); ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev); ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev); break; #endif /* INET6 */ default: panic("%s: unknown af %u", __func__, isr->sp->spidx.src.sa.sa_family); } #undef IPSEC_CHECK_DEFAULT /* Set level. */ switch (isr->level) { case IPSEC_LEVEL_DEFAULT: switch (isr->saidx.proto) { case IPPROTO_ESP: if (isr->saidx.mode == IPSEC_MODE_TUNNEL) level = esp_net_deflev; else level = esp_trans_deflev; break; case IPPROTO_AH: if (isr->saidx.mode == IPSEC_MODE_TUNNEL) level = ah_net_deflev; else level = ah_trans_deflev; break; case IPPROTO_IPCOMP: /* * We don't really care, as IPcomp document says that * we shouldn't compress small packets. */ level = IPSEC_LEVEL_USE; break; default: panic("%s: Illegal protocol defined %u\n", __func__, isr->saidx.proto); } break; case IPSEC_LEVEL_USE: case IPSEC_LEVEL_REQUIRE: level = isr->level; break; case IPSEC_LEVEL_UNIQUE: level = IPSEC_LEVEL_REQUIRE; break; default: panic("%s: Illegal IPsec level %u\n", __func__, isr->level); } return (level); } /* * Check security policy requirements against the actual * packet contents. Return one if the packet should be * reject as "invalid"; otherwiser return zero to have the * packet treated as "valid". * * OUT: * 0: valid * 1: invalid */ static int ipsec_in_reject(struct secpolicy *sp, const struct mbuf *m) { struct ipsecrequest *isr; int need_auth; KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__); kdebug_secpolicy(sp)); /* Check policy. */ switch (sp->policy) { case IPSEC_POLICY_DISCARD: return (1); case IPSEC_POLICY_BYPASS: case IPSEC_POLICY_NONE: return (0); } IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC, ("invalid policy %u", sp->policy)); /* XXX Should compare policy against IPsec header history. */ need_auth = 0; for (isr = sp->req; isr != NULL; isr = isr->next) { if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE) continue; switch (isr->saidx.proto) { case IPPROTO_ESP: if ((m->m_flags & M_DECRYPTED) == 0) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: ESP m_flags:%x\n", __func__, m->m_flags)); return (1); } if (!need_auth && isr->sav != NULL && isr->sav->tdb_authalgxform != NULL && (m->m_flags & M_AUTHIPDGM) == 0) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: ESP/AH m_flags:%x\n", __func__, m->m_flags)); return (1); } break; case IPPROTO_AH: need_auth = 1; if ((m->m_flags & M_AUTHIPHDR) == 0) { KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: AH m_flags:%x\n", __func__, m->m_flags)); return (1); } break; case IPPROTO_IPCOMP: /* * We don't really care, as IPcomp document * says that we shouldn't compress small * packets. IPComp policy should always be * treated as being in "use" level. */ break; } } return (0); /* Valid. */ } /* * Non zero return value means security policy DISCARD or policy violation. */ static int ipsec46_in_reject(const struct mbuf *m, struct inpcb *inp) { struct secpolicy *sp; int error; int result; if (!key_havesp(IPSEC_DIR_INBOUND)) return 0; IPSEC_ASSERT(m != NULL, ("null mbuf")); /* Get SP for this packet. */ if (inp == NULL) sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, &error); else sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error); if (sp != NULL) { result = ipsec_in_reject(sp, m); KEY_FREESP(&sp); } else { result = 1; /* treat errors as policy violation */ } return (result); } /* * Check AH/ESP integrity. * This function is called from tcp_input(), udp_input(), * and {ah,esp}4_input for tunnel mode. */ int ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp) { int result; result = ipsec46_in_reject(m, inp); if (result) IPSECSTAT_INC(ips_in_polvio); return (result); } #ifdef INET6 /* * Check AH/ESP integrity. * This function is called from tcp6_input(), udp6_input(), * and {ah,esp}6_input for tunnel mode. */ int ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp) { int result; result = ipsec46_in_reject(m, inp); if (result) IPSEC6STAT_INC(ips_in_polvio); return (result); } #endif /* * Compute the byte size to be occupied by IPsec header. * In case it is tunnelled, it includes the size of outer IP header. * NOTE: SP passed is freed in this function. */ static size_t ipsec_hdrsiz_internal(struct secpolicy *sp) { struct ipsecrequest *isr; size_t size; KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__); kdebug_secpolicy(sp)); switch (sp->policy) { case IPSEC_POLICY_DISCARD: case IPSEC_POLICY_BYPASS: case IPSEC_POLICY_NONE: return (0); } IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC, ("invalid policy %u", sp->policy)); size = 0; for (isr = sp->req; isr != NULL; isr = isr->next) { size_t clen = 0; switch (isr->saidx.proto) { case IPPROTO_ESP: clen = esp_hdrsiz(isr->sav); break; case IPPROTO_AH: clen = ah_hdrsiz(isr->sav); break; case IPPROTO_IPCOMP: clen = sizeof(struct ipcomp); break; } if (isr->saidx.mode == IPSEC_MODE_TUNNEL) { switch (isr->saidx.dst.sa.sa_family) { case AF_INET: clen += sizeof(struct ip); break; #ifdef INET6 case AF_INET6: clen += sizeof(struct ip6_hdr); break; #endif default: ipseclog((LOG_ERR, "%s: unknown AF %d in " "IPsec tunnel SA\n", __func__, ((struct sockaddr *)&isr->saidx.dst)->sa_family)); break; } } size += clen; } return (size); } /* * This function is called from ipsec_hdrsiz_tcp(), ip_ipsec_mtu(), * disabled ip6_ipsec_mtu() and ip6_forward(). */ size_t ipsec_hdrsiz(const struct mbuf *m, u_int dir, struct inpcb *inp) { struct secpolicy *sp; int error; size_t size; if (!key_havesp(dir)) return 0; IPSEC_ASSERT(m != NULL, ("null mbuf")); /* Get SP for this packet. */ if (inp == NULL) sp = ipsec_getpolicybyaddr(m, dir, &error); else sp = ipsec_getpolicybysock(m, dir, inp, &error); if (sp != NULL) { size = ipsec_hdrsiz_internal(sp); KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: size:%lu.\n", __func__, (unsigned long)size)); KEY_FREESP(&sp); } else { size = 0; /* XXX Should be panic? * -> No, we are called w/o knowing if * IPsec processing is needed. */ } return (size); } /* * Check the variable replay window. * ipsec_chkreplay() performs replay check before ICV verification. * ipsec_updatereplay() updates replay bitmap. This must be called after * ICV verification (it also performs replay check, which is usually done * beforehand). * 0 (zero) is returned if packet disallowed, 1 if packet permitted. * * Based on RFC 2401. */ int ipsec_chkreplay(u_int32_t seq, struct secasvar *sav) { const struct secreplay *replay; u_int32_t diff; int fr; u_int32_t wsizeb; /* Constant: bits of window size. */ int frlast; /* Constant: last frame. */ IPSEC_ASSERT(sav != NULL, ("Null SA")); IPSEC_ASSERT(sav->replay != NULL, ("Null replay state")); replay = sav->replay; if (replay->wsize == 0) return (1); /* No need to check replay. */ /* Constant. */ frlast = replay->wsize - 1; wsizeb = replay->wsize << 3; /* Sequence number of 0 is invalid. */ if (seq == 0) return (0); /* First time is always okay. */ if (replay->count == 0) return (1); if (seq > replay->lastseq) { /* Larger sequences are okay. */ return (1); } else { /* seq is equal or less than lastseq. */ diff = replay->lastseq - seq; /* Over range to check, i.e. too old or wrapped. */ if (diff >= wsizeb) return (0); fr = frlast - diff / 8; /* This packet already seen? */ if ((replay->bitmap)[fr] & (1 << (diff % 8))) return (0); /* Out of order but good. */ return (1); } } /* * Check replay counter whether to update or not. * OUT: 0: OK * 1: NG */ int ipsec_updatereplay(u_int32_t seq, struct secasvar *sav) { char buf[128]; struct secreplay *replay; u_int32_t diff; int fr; u_int32_t wsizeb; /* Constant: bits of window size. */ int frlast; /* Constant: last frame. */ IPSEC_ASSERT(sav != NULL, ("Null SA")); IPSEC_ASSERT(sav->replay != NULL, ("Null replay state")); replay = sav->replay; if (replay->wsize == 0) goto ok; /* No need to check replay. */ /* Constant. */ frlast = replay->wsize - 1; wsizeb = replay->wsize << 3; /* Sequence number of 0 is invalid. */ if (seq == 0) return (1); /* First time. */ if (replay->count == 0) { replay->lastseq = seq; bzero(replay->bitmap, replay->wsize); (replay->bitmap)[frlast] = 1; goto ok; } if (seq > replay->lastseq) { /* seq is larger than lastseq. */ diff = seq - replay->lastseq; /* New larger sequence number. */ if (diff < wsizeb) { /* In window. */ /* Set bit for this packet. */ vshiftl(replay->bitmap, diff, replay->wsize); (replay->bitmap)[frlast] |= 1; } else { /* This packet has a "way larger". */ bzero(replay->bitmap, replay->wsize); (replay->bitmap)[frlast] = 1; } replay->lastseq = seq; /* Larger is good. */ } else { /* seq is equal or less than lastseq. */ diff = replay->lastseq - seq; /* Over range to check, i.e. too old or wrapped. */ if (diff >= wsizeb) return (1); fr = frlast - diff / 8; /* This packet already seen? */ if ((replay->bitmap)[fr] & (1 << (diff % 8))) return (1); /* Mark as seen. */ (replay->bitmap)[fr] |= (1 << (diff % 8)); /* Out of order but good. */ } ok: if (replay->count == ~0) { /* Set overflow flag. */ replay->overflow++; /* Don't increment, no more packets accepted. */ if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) return (1); ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n", __func__, replay->overflow, ipsec_logsastr(sav, buf, sizeof(buf)))); } replay->count++; return (0); } /* * Shift variable length buffer to left. * IN: bitmap: pointer to the buffer * nbit: the number of to shift. * wsize: buffer size (bytes). */ static void vshiftl(unsigned char *bitmap, int nbit, int wsize) { int s, j, i; unsigned char over; for (j = 0; j < nbit; j += 8) { s = (nbit - j < 8) ? (nbit - j): 8; bitmap[0] <<= s; for (i = 1; i < wsize; i++) { over = (bitmap[i] >> (8 - s)); bitmap[i] <<= s; bitmap[i-1] |= over; } } } /* Return a printable string for the address. */ char* ipsec_address(union sockaddr_union* sa, char *buf, socklen_t size) { switch (sa->sa.sa_family) { #ifdef INET case AF_INET: return (inet_ntop(AF_INET, &sa->sin.sin_addr, buf, size)); #endif /* INET */ #ifdef INET6 case AF_INET6: return (inet_ntop(AF_INET6, &sa->sin6.sin6_addr, buf, size)); #endif /* INET6 */ default: return ("(unknown address family)"); } } char * ipsec_logsastr(struct secasvar *sav, char *buf, size_t size) { char sbuf[INET6_ADDRSTRLEN], dbuf[INET6_ADDRSTRLEN]; IPSEC_ASSERT(sav->sah->saidx.src.sa.sa_family == sav->sah->saidx.dst.sa.sa_family, ("address family mismatch")); snprintf(buf, size, "SA(SPI=%08lx src=%s dst=%s)", (u_long)ntohl(sav->spi), ipsec_address(&sav->sah->saidx.src, sbuf, sizeof(sbuf)), ipsec_address(&sav->sah->saidx.dst, dbuf, sizeof(dbuf))); return (buf); } void ipsec_dumpmbuf(const struct mbuf *m) { const u_char *p; int totlen; int i; totlen = 0; printf("---\n"); while (m) { p = mtod(m, const u_char *); for (i = 0; i < m->m_len; i++) { printf("%02x ", p[i]); totlen++; if (totlen % 16 == 0) printf("\n"); } m = m->m_next; } if (totlen % 16 != 0) printf("\n"); printf("---\n"); } static void def_policy_init(const void *unused __unused) { bzero(&V_def_policy, sizeof(struct secpolicy)); V_def_policy.policy = IPSEC_POLICY_NONE; V_def_policy.refcnt = 1; } VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, def_policy_init, NULL); /* XXX This stuff doesn't belong here... */ static struct xformsw* xforms = NULL; /* * Register a transform; typically at system startup. */ void xform_register(struct xformsw* xsp) { xsp->xf_next = xforms; xforms = xsp; } /* * Initialize transform support in an sav. */ int xform_init(struct secasvar *sav, int xftype) { struct xformsw *xsp; if (sav->tdb_xform != NULL) /* Previously initialized. */ return (0); for (xsp = xforms; xsp; xsp = xsp->xf_next) if (xsp->xf_type == xftype) return ((*xsp->xf_init)(sav, xsp)); return (EINVAL); }
25.680936
81
0.679617
[ "transform" ]
6ce2aeeb764aaf7ae1db72126c3dd5b74b68e59e
8,931
c
C
powertask_builtin.c
olawlor/powertask
83ade322b214f834c2e638f3360f6c5dedb84ef3
[ "Unlicense" ]
1
2021-01-18T14:22:04.000Z
2021-01-18T14:22:04.000Z
powertask_builtin.c
olawlor/powertask
83ade322b214f834c2e638f3360f6c5dedb84ef3
[ "Unlicense" ]
null
null
null
powertask_builtin.c
olawlor/powertask
83ade322b214f834c2e638f3360f6c5dedb84ef3
[ "Unlicense" ]
null
null
null
/** Functions built into the powertask system: implements the interface in powertask.h. CJ Emerson and Orion Lawlor, 2021-01, public domain */ #include <stdio.h> #include <stdlib.h> #include "powertask.h" /// Debug support static int powertask_debug_level=0; void powertask_debug(int debug_level) { powertask_debug_level=debug_level; } #define DEBUGF(level,params) { if (powertask_debug_level>=level) printf params; } void powertask_fatal(const char *why,int ID) { DEBUGF(0,("FATAL powertask ERROR: %s [%04x]\n",why,ID)); exit(1); } /// This is the tree of all registered tasks. static powertask_task_t *registered_tasks=0; /// This is the current entry in the doubly linked list of all runnable tasks. static powertask_task_t *runnable_tasks=0; // Link this new task into the registered-tasks binary tree static void powertask_link_into_tree(powertask_task_t *parent,powertask_task_t *task) { while (1) { if (parent->attribute->ID < task->attribute->ID) { if (parent->lower) parent=parent->lower; else { // we are their new lower leaf parent->lower=task; break; } } else if (parent->attribute->ID > task->attribute->ID) { if (parent->higher) parent=parent->higher; else { // we are their new higher leaf parent->higher=task; break; } } else /* wait, parent ID == attribute ID ?! */ { DEBUGF(0,("powertask_register ID collision: old ID %04x (%s, %p), new ID %04x (%s,%p)\n", (int)parent->attribute->ID, parent->attribute->name, parent->attribute, (int)task->attribute->ID, task->attribute->name, task->attribute)); powertask_fatal("powertask_register ID collision",task->attribute->ID); } } } /// This is the builtin idle task #define powertask_ID_builtin_idle 0xFFFF static powertask_result_t powertask_idle_task(const powertask_telemetry_t *input, powertask_telemetry_t *output) { // microprocessor sleep mode here? DEBUGF(5,("idle\n")); return POWERTASK_RESULT_RETRY; } const static powertask_attribute_t attributes_idle_task={ powertask_ID_builtin_idle, /* our task ID */ "IdleTask", /* human-readable name */ 0, /* minimum battery energy (Joules) */ powertask_idle_task, /* function to run */ 0, /* bytes of telemetry input data required */ 0 /* bytes of telemetry output data produced */ }; static void powertask_setup() { // Register our builtin idle task powertask_register(&attributes_idle_task); powertask_make_runnable(powertask_ID_builtin_idle); // Register any other utility tasks (mem read? log read?) } void powertask_register(const powertask_attribute_t *attribute) { // Allocate a clean blank task struct. // We use calloc because it zeros the memory it allocates. powertask_task_t *task = (powertask_task_t*)calloc(1,sizeof(powertask_task_t)); powertask_task_register(attribute,task); } void powertask_task_register(const powertask_attribute_t *attribute,powertask_task_t *task) { DEBUGF(10,("powertask_register ID %04x (%s), %d battery, %d bytes in, %d bytes out\n", (int)attribute->ID, attribute->name, (int)attribute->minimum_battery, (int)attribute->input_length, (int)attribute->output_length)); // Link in the basics from the task struct: task->attribute = attribute; task->lower=task->higher=0; task->prev=task->next=0; if (registered_tasks==0) { // This is the first registration ever. registered_tasks=task; // root of the search tree // This is our chance to register builtin tasks and such powertask_setup(); } else { powertask_link_into_tree(registered_tasks,task); } } /// Look up the runtime task structure for this task ID. /// Returns 0 if that task ID is not registered. powertask_task_t *powertask_task_lookup(powertask_ID_t ID) { powertask_task_t *parent=registered_tasks; while (1) { if (parent->attribute->ID < ID) { if (parent->lower) parent=parent->lower; else return 0; // hit leaf } else if (parent->attribute->ID > ID) { if (parent->higher) parent=parent->higher; else return 0; // hit leaf } else /* found it! */ { return parent; } } } /// Allocate telemetry object (only called once per task, cached in task struct) powertask_telemetry_t *powertask_allocate_telemetry(powertask_length_t len) { DEBUGF(8,(" allocating %d bytes of telemetry\n",(int)len)); powertask_telemetry_t *tel=(powertask_telemetry_t *)calloc(1, sizeof(powertask_telemetry_header_t)+len); return tel; } /// Make this task runnable--the task is added to the runnable queue. /// If this task requires input, you must fill out the data portion /// of the returned telemetry structure. powertask_telemetry_t *powertask_make_runnable(powertask_ID_t ID) { powertask_task_t *task=powertask_task_lookup(ID); if (task==0) powertask_fatal("Invalid task in powertask_make_runnable",ID); DEBUGF(3,("powertask_make_runnable %04x (%s)\n",(int)ID,task->attribute->name)); // Is it already runnable? if (task->prev!=0) { DEBUGF(2,(" ignoring request to make task %04x runnable, already runnable",(int)ID)); return task->input; //<- could this cause disaster? fatal instead? } // Allocate telemetry slots (will be needed when it runs) if (task->input==0) task->input=powertask_allocate_telemetry(task->attribute->input_length); if (task->output==0) task->output=powertask_allocate_telemetry(task->attribute->output_length); // Link into doubly linked list of runnable tasks if (runnable_tasks==0) { // first time running any task! task->prev=task; task->next=task; runnable_tasks=task; } else { // link into existing list of runnable tasks task->next=runnable_tasks->next; runnable_tasks->next=task; task->prev=runnable_tasks; runnable_tasks=task; // cut into line? } // Rely on caller to fill in telemetry data (is this right?) return task->input; } powertask_energy_t powertask_current_battery=30000; // <- FIXME: need a real battery interface // Remove the current task from the runnable_tasks list, // and point to the previous task. void remove_task(powertask_task_t *task) { DEBUGF(3,(" removing %04x (%s) from the run queue\n", (int)task->attribute->ID,task->attribute->name)); task->prev->next=task->next; task->next->prev=task->prev; if (task==runnable_tasks) runnable_tasks=task->next; } /// Run the next task. Returns 1 if tasks still exist to run. int powertask_run_next(void) { powertask_task_t *task=runnable_tasks; powertask_energy_t need_battery=task->attribute->minimum_battery; DEBUGF(3,("run_next chooses %04x (%s)\n", (int)task->attribute->ID,task->attribute->name)); if (powertask_current_battery >= need_battery) { // we have the energy to run this now powertask_result_t result; DEBUGF(3,(" running function %p\n",task->attribute->function)); result=task->attribute->function(task->input,task->output); DEBUGF(3,(" function returns %04x\n",result)); if (result==POWERTASK_RESULT_RETRY) { // Leave it in the runnable list, it will come around again // Move on to other tasks runnable_tasks=runnable_tasks->next; } else if (result==POWERTASK_RESULT_OK) { // FIXME: store output telemetry somewhere // It's successful, remove it from the runnable list remove_task(task); } else if (result>=POWERTASK_RESULT_FAIL_QUIET && result<POWERTASK_RESULT_FAIL_OUTPUT) { // Failed without output, remove it remove_task(task); } else if (result>=POWERTASK_RESULT_FAIL_OUTPUT && result<POWERTASK_RESULT_LAST) { // FIXME: store output telemetry somewhere // Failed with output, send it and remove it remove_task(task); } else // invalid result code { powertask_fatal("task returned invalid result code",result); } } else { DEBUGF(3,(" not enough battery, need %d have %d\n", (int)need_battery,(int)powertask_current_battery)); // Move on to other tasks runnable_tasks=runnable_tasks->next; } // We have nothing left to run return runnable_tasks!=runnable_tasks->next; }
32.95572
101
0.643265
[ "object" ]
6cf0dff3bd77d5e61f0a838919b7f12f908da3a7
8,735
h
C
PhysicsTools/UtilAlgos/interface/Plotter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
PhysicsTools/UtilAlgos/interface/Plotter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
PhysicsTools/UtilAlgos/interface/Plotter.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#ifndef ConfigurableAnalysis_Plotter_H #define ConfigurableAnalysis_Plotter_H #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "TH1.h" #include "TH1F.h" #include "TH2F.h" #include "TProfile.h" #include "PhysicsTools/UtilAlgos/interface/VariableHelper.h" #include "PhysicsTools/UtilAlgos/interface/CachingVariable.h" #include "PhysicsTools/UtilAlgos/interface/ConfigurableHisto.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "CommonTools/Utils/interface/TFileDirectory.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" class Plotter { public: Plotter(){} Plotter(const edm::ParameterSet& iConfig){} virtual ~Plotter(){} virtual void setDir(std::string dir) =0; virtual void fill(std::string subDir,const edm::Event& iEvent) =0; virtual void complete() =0; }; class VariablePlotter : public Plotter { public: VariablePlotter(const edm::ParameterSet& iConfig) : currentDir_("youDidNotSetDirectoryFirst") { //create the master copy, never filled, just to make copies // make TH1 edm::ParameterSet th1=iConfig.getParameter<edm::ParameterSet>("TH1s"); std::vector<std::string> th1Names; th1.getParameterSetNames(th1Names); for (unsigned int iH=0;iH!=th1Names.size();++iH){ std::string hname = th1Names[iH]; edm::ParameterSet hPset=th1.getParameter<edm::ParameterSet>(hname); if (hPset.exists("name")) hname = hPset.getParameter<std::string>("name"); bool split=hPset.exists("splitter") || hPset.exists("splitters"); if (split) master_[hname]=new SplittingConfigurableHisto(ConfigurableHisto::h1, hname, hPset); else master_[hname]=new ConfigurableHisto(ConfigurableHisto::h1, hname, hPset); } // make profiles edm::ParameterSet tprof=iConfig.getParameter<edm::ParameterSet>("TProfiles"); std::vector<std::string> tprofNames; tprof.getParameterSetNames(tprofNames); for (unsigned int iH=0;iH!=tprofNames.size();++iH){ std::string hname = tprofNames[iH]; edm::ParameterSet hPset=tprof.getParameter<edm::ParameterSet>(hname); bool split=hPset.exists("splitter") || hPset.exists("splitters"); if (hPset.exists("name")) hname = hPset.getParameter<std::string>("name"); if (split) master_[hname]=new SplittingConfigurableHisto(ConfigurableHisto::prof, hname, hPset); else master_[hname]=new ConfigurableHisto(ConfigurableHisto::prof, hname, hPset); } // make TH2 edm::ParameterSet th2=iConfig.getParameter<edm::ParameterSet>("TH2s"); std::vector<std::string> th2Names; th2.getParameterSetNames(th2Names); for (unsigned int iH=0;iH!=th2Names.size();++iH){ std::string hname = th2Names[iH]; edm::ParameterSet hPset=th2.getParameter<edm::ParameterSet>(hname); if (hPset.exists("name")) hname = hPset.getParameter<std::string>("name"); bool split=hPset.exists("splitter") || hPset.exists("splitters"); if (split) master_[hname]=new SplittingConfigurableHisto(ConfigurableHisto::h2, hname, hPset); else master_[hname]=new ConfigurableHisto(ConfigurableHisto::h2, hname, hPset); } } void setDir(std::string dir) override{ //insert a new one Directory & insertedDirectory = directories_[dir]; //create the actual directory in TFile: name is <dir> if (!insertedDirectory.dir){ insertedDirectory.dir=new TFileDirectory(edm::Service<TFileService>()->mkdir(dir)); insertedDirectory.dirName=dir; } //remember which directory name this is currentDir_=dir; } void fill(std::string subDir,const edm::Event& iEvent) override{ //what is the current directory Directory & currentDirectory= directories_[currentDir_]; //what is the current set of sub directories for this SubDirectories & currentSetOfSubDirectories=currentDirectory.subDir; //find the subDirectory requested: SubDirectory * subDirectoryToUse=nullptr; SubDirectories::iterator subDirectoryFindIterator=currentSetOfSubDirectories.find(subDir); //not found? insert a new directory with this name if (subDirectoryFindIterator==currentSetOfSubDirectories.end()){ edm::LogInfo("VariablePlotter")<<" gonna clone histograms for :"<<subDir<<" in "<<currentDir_; SubDirectory & insertedDir = currentSetOfSubDirectories[subDir]; subDirectoryToUse = &insertedDir; if (!insertedDir.dir){ insertedDir.dir=new TFileDirectory(currentDirectory.dir->mkdir(subDir)); insertedDir.dirName=subDir; } //create a copy from the master copy DirectoryHistos::iterator masterHistogramIterator=master_.begin(); DirectoryHistos::iterator masterHistogramIterator_end=master_.end(); for (; masterHistogramIterator!=masterHistogramIterator_end;++masterHistogramIterator) { //clone does not book histogram insertedDir.histos[masterHistogramIterator->first]=masterHistogramIterator->second->clone(); } //book all copies of the histos DirectoryHistos::iterator clonedHistogramIterator=insertedDir.histos.begin(); DirectoryHistos::iterator clonedHistogramIterator_end=insertedDir.histos.end(); for (; clonedHistogramIterator!=clonedHistogramIterator_end;++clonedHistogramIterator) { clonedHistogramIterator->second->book(insertedDir.dir); } } else{ subDirectoryToUse=&subDirectoryFindIterator->second; } //now that you have the subdirectory: fill histograms for this sub directory DirectoryHistos::iterator histogramIterator=subDirectoryToUse->histos.begin(); DirectoryHistos::iterator histogramIterator_end=subDirectoryToUse->histos.end(); for(; histogramIterator!=histogramIterator_end;++histogramIterator) { histogramIterator->second->fill(iEvent); } } ~VariablePlotter() override{ // CANNOT DO THAT because of TFileService holding the histograms /* //loop over all subdirectories and delete all ConfigurableHistograms Directories::iterator dir_It = directories_.begin(); Directories::iterator dir_It_end = directories_.end(); // loop directories for (;dir_It!=dir_It_end;++dir_It){ Directory & currentDirectory=dir_It->second; SubDirectories & currentSetOfSubDirectories=currentDirectory.subDir; SubDirectories::iterator subDir_It = currentSetOfSubDirectories.begin(); SubDirectories::iterator subDir_It_end = currentSetOfSubDirectories.end(); //loop subdirectories for (;subDir_It!=subDir_It_end;++subDir_It){ DirectoryHistos::iterator histogramIterator=subDir_It->second.histos.begin(); DirectoryHistos::iterator histogramIterator_end=subDir_It->second.histos.end(); //loop configurable histograms for(; histogramIterator!=histogramIterator_end;++histogramIterator){ // by doing that you are removing the histogram from the TFileService too. and this will crash // delete histogramIterator->second; } } } */ } void complete() override{ //loop over all subdirectories and call complete() on all ConfigurableHistograms Directories::iterator dir_It = directories_.begin(); Directories::iterator dir_It_end = directories_.end(); // loop directories for (;dir_It!=dir_It_end;++dir_It){ Directory & currentDirectory=dir_It->second; SubDirectories & currentSetOfSubDirectories=currentDirectory.subDir; SubDirectories::iterator subDir_It = currentSetOfSubDirectories.begin(); SubDirectories::iterator subDir_It_end = currentSetOfSubDirectories.end(); //loop subdirectories for (;subDir_It!=subDir_It_end;++subDir_It){ DirectoryHistos::iterator histogramIterator=subDir_It->second.histos.begin(); DirectoryHistos::iterator histogramIterator_end=subDir_It->second.histos.end(); //loop configurable histograms for(; histogramIterator!=histogramIterator_end;++histogramIterator) { histogramIterator->second->complete(); } } } } private: typedef std::map<std::string, ConfigurableHisto *> DirectoryHistos; DirectoryHistos master_; class SubDirectory { public: SubDirectory() : dirName(""),dir(nullptr){} std::string dirName; DirectoryHistos histos; TFileDirectory * dir; }; typedef std::map<std::string, SubDirectory> SubDirectories; class Directory { public: Directory() : dirName(""),dir(nullptr){} std::string dirName; SubDirectories subDir; TFileDirectory * dir; }; typedef std::map<std::string, Directory> Directories; std::string currentDir_; Directories directories_; }; #include "FWCore/PluginManager/interface/PluginFactory.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" typedef edmplugin::PluginFactory< Plotter* (const edm::ParameterSet&) > PlotterFactory; #endif
38.822222
100
0.733829
[ "vector" ]
6cf0e695848405c083b9b54d888219f872eb55b0
1,066
h
C
lib/asan/tests/asan_test_config.h
SaleJumper/android-source-browsing.platform--external--compiler-rt
1f922a5259510f70a12576e7a61eaa0033a02b16
[ "MIT" ]
1
2021-04-29T08:28:54.000Z
2021-04-29T08:28:54.000Z
lib/asan/tests/asan_test_config.h
SaleJumper/android-source-browsing.platform--external--compiler-rt
1f922a5259510f70a12576e7a61eaa0033a02b16
[ "MIT" ]
null
null
null
lib/asan/tests/asan_test_config.h
SaleJumper/android-source-browsing.platform--external--compiler-rt
1f922a5259510f70a12576e7a61eaa0033a02b16
[ "MIT" ]
3
2015-01-09T13:48:30.000Z
2020-04-26T09:50:52.000Z
//===-- asan_test_config.h ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // //===----------------------------------------------------------------------===// #ifndef ASAN_TEST_CONFIG_H #define ASAN_TEST_CONFIG_H #include <vector> #include <string> #include <map> #include "gtest/gtest.h" using std::string; using std::vector; using std::map; #ifndef ASAN_UAR # error "please define ASAN_UAR" #endif #ifndef ASAN_HAS_EXCEPTIONS # error "please define ASAN_HAS_EXCEPTIONS" #endif #ifndef ASAN_HAS_BLACKLIST # error "please define ASAN_HAS_BLACKLIST" #endif #ifndef ASAN_NEEDS_SEGV # error "please define ASAN_NEEDS_SEGV" #endif #ifndef ASAN_LOW_MEMORY #define ASAN_LOW_MEMORY 0 #endif #define ASAN_PCRE_DOTALL "" #endif // ASAN_TEST_CONFIG_H
21.755102
80
0.616323
[ "vector" ]
6cfad1d87d5fc7a0e6aee0bedfd07d6c2d49d33c
22,751
c
C
bgbcc22/ccxl/ccxl_struct.c
cr88192/bgbtech_btsr1arch
dcee6e5c7bbdac33a6891228f2238f6489e3c29a
[ "MIT" ]
15
2019-05-19T15:51:06.000Z
2021-12-01T08:12:17.000Z
bgbcc22/ccxl/ccxl_struct.c
cr88192/bgbtech_btsr1arch
dcee6e5c7bbdac33a6891228f2238f6489e3c29a
[ "MIT" ]
null
null
null
bgbcc22/ccxl/ccxl_struct.c
cr88192/bgbtech_btsr1arch
dcee6e5c7bbdac33a6891228f2238f6489e3c29a
[ "MIT" ]
1
2019-11-21T16:57:31.000Z
2019-11-21T16:57:31.000Z
#include <bgbccc.h> #if 0 BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupStructureForType( BGBCC_TransState *ctx, ccxl_type ty) { BGBCC_CCXL_LiteralInfo *obj; int i; i=BGBCC_CCXL_GetTypeBaseType(ctx, ty); if(i>=256) { obj=ctx->literals[i-256]; return(obj); } return(NULL); } #endif BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupStructureForSig( BGBCC_TransState *ctx, char *sig) { char *s, *t; s=sig; while(*s && (*s=='P')) { s++; } return(BGBCC_CCXL_LookupStructureForSig2(ctx, s)); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupStructureForSig2( BGBCC_TransState *ctx, char *sig) { char tb[256]; BGBCC_CCXL_LiteralInfo *cur; char *s, *t; int i; s=sig; // while(*s && (*s=='P')) // { s++; } if((*s!='X') && (*s!='Y')) { return(NULL); } s++; if((*s>='0') && (*s<='9')) { i=atoi(s); cur=ctx->literals[i]; return(cur); } t=tb; while(*s && (*s!=';')) *t++=*s++; *t++=0; cur=BGBCC_CCXL_LookupStructure(ctx, tb); return(cur); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_GetStructureForSig( BGBCC_TransState *ctx, char *sig) { char *s, *t; s=sig; while(*s && (*s=='P')) { s++; } return(BGBCC_CCXL_GetStructureForSig2(ctx, s)); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_GetStructureForSig2( BGBCC_TransState *ctx, char *sig) { char tb[256]; BGBCC_CCXL_LiteralInfo *cur; char *s, *t; int i; s=sig; if((*s!='X') && (*s!='Y')) { return(NULL); } s++; if((*s>='0') && (*s<='9')) { i=atoi(s); cur=ctx->literals[i]; return(cur); } t=tb; while(*s && (*s!=';')) *t++=*s++; *t++=0; cur=BGBCC_CCXL_LookupStructure(ctx, tb); if(!cur) { cur=BGBCC_CCXL_GetStruct(ctx, tb); } return(cur); } int BGBCC_CCXL_LookupStructureIDForSig( BGBCC_TransState *ctx, char *sig) { BGBCC_CCXL_LiteralInfo *cur; cur=BGBCC_CCXL_LookupStructureForSig(ctx, sig); if(!cur)return(-1); return(cur->litid); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupTypedefForSig( BGBCC_TransState *ctx, char *sig) { char *s, *t; s=sig; while(*s && (*s=='P')) { s++; } return(BGBCC_CCXL_LookupTypedefForSig2(ctx, s)); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupTypedefForSig2( BGBCC_TransState *ctx, char *sig) { char tb[256]; BGBCC_CCXL_LiteralInfo *cur; char *s, *t; int i; s=sig; // while(*s && (*s=='P')) // { s++; } if(*s!='U') { return(NULL); } s++; if((*s>='0') && (*s<='9')) { i=atoi(s); cur=ctx->literals[i]; return(cur); } t=tb; while(*s && (*s!=';')) *t++=*s++; *t++=0; cur=BGBCC_CCXL_LookupTypedef(ctx, tb, NULL); return(cur); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_GetTypedefForSig( BGBCC_TransState *ctx, char *sig) { char *s, *t; s=sig; while(*s && (*s=='P')) { s++; } return(BGBCC_CCXL_GetTypedefForSig2(ctx, s)); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_GetTypedefForSig2( BGBCC_TransState *ctx, char *sig) { char tb[256]; BGBCC_CCXL_LiteralInfo *cur; char *s, *t; int i; s=sig; if(*s!='U') { return(NULL); } s++; if((*s>='0') && (*s<='9')) { i=atoi(s); cur=ctx->literals[i]; return(cur); } t=tb; while(*s && (*s!=';')) *t++=*s++; *t++=0; cur=BGBCC_CCXL_LookupTypedef(ctx, tb, NULL); if(!cur) { cur=BGBCC_CCXL_GetTypedef2(ctx, tb); } return(cur); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_LookupStructureForType( BGBCC_TransState *ctx, ccxl_type type) { BGBCC_CCXL_TypeOverflow ovf; BGBCC_CCXL_LiteralInfo *st; int bt; if((type.val&CCXL_TY_TYTY_MASK)==CCXL_TY_TYTY_BASIC) { bt=type.val&CCXL_TY_BASEMASK; if(bt<256) { // BGBCC_CCXL_TagError(ctx, // CCXL_TERR_STATUS(CCXL_STATUS_ERR_UNHANDLEDTYPE)); return(NULL); } st=ctx->literals[bt-256]; return(st); } if((type.val&CCXL_TY_TYTY_MASK)==CCXL_TY_TYTY_BASIC2) { // BGBCC_DBGBREAK bt=type.val&CCXL_TYB2_BASEMASK; if(bt<256) { // BGBCC_CCXL_TagError(ctx, // CCXL_TERR_STATUS(CCXL_STATUS_ERR_UNHANDLEDTYPE)); return(NULL); } st=ctx->literals[bt-256]; return(st); } if((type.val&CCXL_TY_TYTY_MASK)==CCXL_TY_TYTY_BASIC3) { bt=type.val&CCXL_TYB3_BASEMASK; if(bt<256) { // BGBCC_CCXL_TagError(ctx, // CCXL_TERR_STATUS(CCXL_STATUS_ERR_UNHANDLEDTYPE)); return(NULL); } st=ctx->literals[bt-256]; return(st); } if((type.val&CCXL_TY_TYTY_MASK)==CCXL_TY_TYTY_OVF1) { ovf=*(ctx->tyovf[type.val&CCXL_TYOVF_IDXMASK]); // bt=type.val&CCXL_TYB2_BASEMASK; bt=ovf.base; if(bt<256) { // BGBCC_CCXL_TagError(ctx, // CCXL_TERR_STATUS(CCXL_STATUS_ERR_UNHANDLEDTYPE)); return(NULL); } st=ctx->literals[bt-256]; return(st); } BGBCC_CCXL_TagError(ctx, CCXL_TERR_STATUS(CCXL_STATUS_ERR_UNHANDLEDTYPE)); return(NULL); } int BGBCC_CCXL_LookupStructureIDForType( BGBCC_TransState *ctx, ccxl_type type) { BGBCC_CCXL_LiteralInfo *cur; cur=BGBCC_CCXL_LookupStructureForType(ctx, type); if(!cur)return(-1); return(cur->litid); } int BGBCC_CCXL_LookupStructContainsFieldID( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name) { BGBCC_CCXL_LiteralInfo *st2; int i, j; if(!st) return(-1); if(!st->decl) return(-1); for(i=0; i<st->decl->n_fields; i++) { // if(!st->decl->fields[i]->name) if((!st->decl->fields[i]->name || !strcmp(st->decl->fields[i]->name, "_")) || (st->decl->fields[i]->flagsint&BGBCC_TYFL_DELEGATE)) { st2=BGBCC_CCXL_LookupStructureForType(ctx, st->decl->fields[i]->type); if(!st2) continue; j=BGBCC_CCXL_LookupStructContainsFieldID(ctx, st2, name); if(j>=0)return(i); continue; } if(!strcmp(st->decl->fields[i]->name, name)) return(i); } return(-1); } int BGBCC_CCXL_LookupStructFieldID( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name) { return(BGBCC_CCXL_LookupStructFieldIDSig(ctx, st, name, NULL)); } int BGBCC_CCXL_LookupStructFieldIDSig( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name, char *sig) { int i; if(!st) return(-1); if(!st->decl) return(-1); /* Object Fields */ for(i=0; i<st->decl->n_fields; i++) { if(!st->decl->fields[i]->name) continue; if(!strcmp(st->decl->fields[i]->name, name)) return(CCXL_FID_TAG_FIELD|i); } /* Static Fields */ for(i=0; i<st->decl->n_statics; i++) { if(!st->decl->statics[i]->name) continue; if(!strcmp(st->decl->statics[i]->name, name)) return(CCXL_FID_TAG_STATICS|i); } /* Methods */ for(i=0; i<st->decl->n_regs; i++) { if(!st->decl->regs[i]->name) continue; // if(!strcmp(st->decl->regs[i]->name, name)) if(!bgbcc_strcmp_nosig(st->decl->regs[i]->name, name)) { if(sig && !BGBCC_CCXL_MatchSig(ctx, st->decl->regs[i]->sig, sig)) continue; return(CCXL_FID_TAG_REGS|i); } } return(-1); } BGBCC_CCXL_LiteralInfo *BGBCC_CCXL_GetStructSuperclass( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st) { BGBCC_CCXL_LiteralInfo *st1; if(st->decl->n_args>0) { st1=BGBCC_CCXL_LookupStructureForSig(ctx, st->decl->args[0]->sig); return(st1); } return(NULL); } ccxl_status BGBCC_CCXL_LookupStructFieldType( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name, ccxl_type *rty) { return(BGBCC_CCXL_LookupStructFieldTypeSig(ctx, st, name, NULL, rty)); } ccxl_status BGBCC_CCXL_LookupStructFieldTypeSig( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name, char *sig, ccxl_type *rty) { BGBCC_CCXL_LiteralInfo *st1; ccxl_type bty; int i; if(!st) return(-1); if(!st->decl) return(-1); /* Object Fields */ for(i=0; i<st->decl->n_fields; i++) { if(!st->decl->fields[i]->name) continue; if(!strcmp(st->decl->fields[i]->name, name)) { BGBCC_CCXL_TypeFromSig(ctx, &bty, st->decl->fields[i]->sig); *rty=bty; return(1); } } /* Object Fields */ for(i=0; i<st->decl->n_statics; i++) { if(!st->decl->statics[i]->name) continue; if(!strcmp(st->decl->statics[i]->name, name)) { BGBCC_CCXL_TypeFromSig(ctx, &bty, st->decl->statics[i]->sig); *rty=bty; return(1); } } /* Methods */ for(i=0; i<st->decl->n_regs; i++) { if(!st->decl->regs[i]->name) continue; // if(!strcmp(st->decl->regs[i]->name, name)) if(!bgbcc_strcmp_nosig(st->decl->regs[i]->name, name)) { if(sig && !BGBCC_CCXL_MatchSig(ctx, st->decl->regs[i]->sig, sig)) continue; // BGBCC_CCXL_TypeFromSig(ctx, &bty, // st->decl->fields[i]->sig); bty=st->decl->regs[i]->type; *rty=bty; return(1); } } if(st->decl->n_args>0) { st1=BGBCC_CCXL_LookupStructureForSig(ctx, st->decl->args[0]->sig); i=BGBCC_CCXL_LookupStructFieldTypeSig(ctx, st1, name, sig, &bty); if(i>0) { *rty=bty; return(1); } } // printf("BGBCC_CCXL_LookupStructFieldType: No Field '%s'\n", name); bty=BGBCC_CCXL_TypeWrapBasicType(CCXL_TY_I); *rty=bty; return(0); } ccxl_status BGBCC_CCXL_LookupStructSuperFieldType( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, char *name, int *rsi, int *rfi, ccxl_type *rty) { BGBCC_CCXL_LiteralInfo *sobj; ccxl_type bty, tty; int i0, i1; int i; if(!st) return(-1); if(!st->decl) return(-1); for(i=0; i<st->decl->n_fields; i++) { if(!st->decl->fields[i]->name) continue; if(!strcmp(st->decl->fields[i]->name, name)) { BGBCC_CCXL_TypeFromSig(ctx, &bty, st->decl->fields[i]->sig); *rty=bty; *rsi=0; *rfi=i; return(1); } } if(st->decl->n_args>0) { tty=st->decl->args[0]->type; sobj=BGBCC_CCXL_LookupStructureForType(ctx, tty); i=BGBCC_CCXL_LookupStructSuperFieldType(ctx, sobj, name, &i0, &i1, &bty); if(i>0) { *rty=bty; *rsi=i0+1; *rfi=i1; return(1); } } // printf("BGBCC_CCXL_LookupStructFieldType: No Field '%s'\n", name); bty=BGBCC_CCXL_TypeWrapBasicType(CCXL_TY_I); // *rty=bty; return(0); } ccxl_status BGBCC_CCXL_LookupStructFieldIdType( BGBCC_TransState *ctx, BGBCC_CCXL_LiteralInfo *st, int idx, ccxl_type *rty) { ccxl_type bty; int i; if(!st) return(-1); if(!st->decl) return(-1); if((idx>=0) && (idx<st->decl->n_fields)) { BGBCC_CCXL_TypeFromSig(ctx, &bty, st->decl->fields[idx]->sig); *rty=bty; return(1); } bty=BGBCC_CCXL_TypeWrapBasicType(CCXL_TY_I); return(-1); } int BGBCC_CCXL_GetArraySizeForSig( BGBCC_TransState *ctx, char *sig) { char *s, *t; s=sig; while(*s && (*s=='P')) { s++; } return(BGBCC_CCXL_GetArraySizeForSig2(ctx, s)); } int BGBCC_CCXL_GetArraySizeForSig2( BGBCC_TransState *ctx, char *sig) { return(BGBCC_CCXL_GetArraySizeForSig2R(ctx, &sig)); } int BGBCC_CCXL_GetArraySizeForSig2R( BGBCC_TransState *ctx, char **rsig) { char *s, *t; int i; s=*rsig; if(*s=='A') { s++; i=0; while(*s && (*s>='0') && (*s<='9')) { i=(i*10)+((*s++)-'0'); } if(*s==',') return(-1); if(*s==';') s++; *rsig=s; return(i); } return(-1); } int BGBCC_CCXL_GetArraySizeForSig3R( BGBCC_TransState *ctx, char **rsig) { char *s, *t; int i, j; s=*rsig; if(*s=='A') { s++; i=1; while(*s) { j=0; while(*s && (*s>='0') && (*s<='9')) { j=(j*10)+((*s++)-'0'); } if(*s==',') { i=i*j; s++; continue; } if(*s==';') { i=i*j; s++; break; } i=i*j; break; } *rsig=s; return(i); } return(-1); } ccxl_status BGBCC_CCXL_GetStructSigFixedSize( BGBCC_TransState *ctx, char *sig, int *rsz) { BGBCC_CCXL_LiteralInfo *str; str=BGBCC_CCXL_LookupStructureForSig2(ctx, sig); if(str) { *rsz=str->decl->fxsize; return(0); } *rsz=0; return(-1); } ccxl_status BGBCC_CCXL_GetSigFixedSize( BGBCC_TransState *ctx, char *sig, int *rsz) { int asz[16]; char *s; int sz, na; int i, j, k; switch(*sig) { case 'a': case 'b': case 'c': case 'h': sz=1; break; case 'i': case 'j': sz=4; break; case 'l': case 'm': if(BGBCC_IsEmitRil(ctx)) __debugbreak(); if(ctx->arch_sizeof_long) { sz=ctx->arch_sizeof_long; break; } sz=4; break; case 's': case 't': case 'w': case 'k': sz=2; break; case 'x': case 'y': sz=8; break; case 'f': sz=4; break; case 'd': sz=8; break; // case 'P': // sz=4; break; case 'A': s=sig+1; na=0; i=0; while(*s) { if((*s>='0') && (*s<='9')) { i=i*10+((*s++)-'0'); continue; } if(*s==',') { asz[na++]=i; i=0; s++; continue; } if(*s==';') { asz[na++]=i; i=0; s++; break; } asz[na++]=i; break; } BGBCC_CCXL_GetSigFixedSize(ctx, s, &sz); j=1; for(i=0; i<na; i++) j*=asz[i]; sz=j*sz; break; case 'P': if(BGBCC_IsEmitRil(ctx)) __debugbreak(); if(ctx->arch_sizeof_ptr) { sz=ctx->arch_sizeof_ptr; break; } sz=4; break; case 'X': BGBCC_CCXL_GetStructSigFixedSize(ctx, sig, &sz); break; default: // sz=4; __debugbreak(); break; } *rsz=sz; return(0); } char *BGBCC_CCXL_SigGetReturnSig( BGBCC_TransState *ctx, char *sig) { char *s; int i; s=sig; while(*s=='P')s++; if(*s=='(') { i=0; while(*s) { if(*s=='(') { i++; s++; continue; } if(*s==')') { i--; s++; if(!i)break; continue; } s++; } return(s); } return(sig); } ccxl_status BGBCC_CCXL_GetStructSigMinMaxSize( BGBCC_TransState *ctx, char *sig, int *rsz, int *ral) { BGBCC_CCXL_LiteralInfo *str; str=BGBCC_CCXL_LookupStructureForSig2(ctx, sig); if(str && (str->littype==CCXL_LITID_CLASS)) { rsz[0]=8; rsz[1]=8; ral[0]=8; ral[1]=8; return(0); } if(str && str->decl) { rsz[0]=str->decl->fxmsize; rsz[1]=str->decl->fxnsize; ral[0]=str->decl->fxmalgn; ral[1]=str->decl->fxnalgn; return(0); } rsz[0]=0; rsz[1]=0; ral[0]=1; ral[1]=1; return(-1); } ccxl_status BGBCC_CCXL_GetSigMinMaxSize( BGBCC_TransState *ctx, char *sig, int *rsz, int *ral) { int asz[16]; char *s; int sza[2], ala[2]; int sz, al, na, ret; int i, j, k; ret=0; switch(*sig) { case 'a': case 'b': case 'c': case 'h': sza[0]=1; sza[1]=1; ala[0]=1; ala[1]=1; break; case 'i': case 'j': sza[0]=4; sza[1]=4; ala[0]=4; ala[1]=4; break; case 'l': case 'm': // if(ctx->arch_sizeof_long && !BGBCC_IsEmitRil(ctx)) if(ctx->arch_sizeof_long) { i=ctx->arch_sizeof_long; sza[0]=i; sza[1]=i; ala[0]=i; ala[1]=i; break; } sza[0]=4; sza[1]=8; ala[0]=4; ala[1]=8; break; case 's': case 't': case 'w': case 'k': case 'u': sza[0]=2; sza[1]=2; ala[0]=2; ala[1]=2; break; case 'x': case 'y': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'f': sza[0]=4; sza[1]=4; ala[0]=4; ala[1]=4; break; case 'd': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'n': case 'o': case 'g': sza[0]=16; sza[1]=16; ala[0]=16; ala[1]=16; break; case 'P': // if(ctx->arch_sizeof_ptr && !BGBCC_IsEmitRil(ctx)) if(ctx->arch_sizeof_ptr) { i=ctx->arch_sizeof_ptr; sza[0]=i; sza[1]=i; ala[0]=i; ala[1]=i; break; } sza[0]=4; sza[1]=8; ala[0]=4; ala[1]=8; break; case 'Q': // sza[0]=16; sza[1]=16; sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'A': s=sig+1; na=0; i=0; while(*s) { if((*s>='0') && (*s<='9')) { i=i*10+((*s++)-'0'); continue; } if(*s==',') { asz[na++]=i; i=0; s++; continue; } if(*s==';') { asz[na++]=i; i=0; s++; break; } asz[na++]=i; break; } BGBCC_CCXL_GetSigMinMaxSize(ctx, s, sza, ala); j=1; for(i=0; i<na; i++) j*=asz[i]; sza[0]=j*sza[0]; sza[1]=j*sza[1]; break; case 'X': ret=BGBCC_CCXL_GetStructSigMinMaxSize(ctx, sig, sza, ala); break; case 'v': sza[0]=1; sza[1]=1; ala[0]=1; ala[1]=1; break; case 'r': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'C': switch(sig[1]) { case 's': case 'o': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'a': case 'f': case 'l': case 'm': case 'v': case 'w': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'b': case 'c': case 'd': case 'h': case 'i': case 'j': case 'n': case 'q': sza[0]=16; sza[1]=16; ala[0]=8; ala[1]=8; break; case 'p': sza[0]=16; sza[1]=16; ala[0]=1; ala[1]=1; break; default: BGBCC_DBGBREAK break; } break; case 'D': switch(sig[1]) { case 'i': case 'j': case 'k': case 'l': sza[0]=8; sza[1]=8; ala[0]=8; ala[1]=8; break; case 'h': sza[0]=16; sza[1]=16; ala[0]=8; ala[1]=8; break; case 'z': sz=ctx->arch_sizeof_valist; al=ctx->arch_align_max; // if((sz>0) && !BGBCC_IsEmitRil(ctx)) if(sz>0) { sza[0]=sz; sza[1]=sz; ala[0]=al; ala[1]=al; } break; default: BGBCC_DBGBREAK break; } break; case 'U': sza[0]=0; sza[1]=0; ala[0]=1; ala[1]=1; ret=-1; break; default: sza[0]=0; sza[1]=0; ala[0]=1; ala[1]=1; ret=-1; break; } // if(sza[0]!=sza[1]) // { BGBCC_DBGBREAK } rsz[0]=sza[0]; rsz[1]=sza[1]; ral[0]=ala[0]; ral[1]=ala[1]; return(ret); } ccxl_status BGBCC_CCXL_MarkTypeAccessed( BGBCC_TransState *ctx, ccxl_type type) { BGBCC_CCXL_LiteralInfo *obj; int i, j, k, n; i=BGBCC_CCXL_TypeObjectLiteralIndex(ctx, type); if(i<0)return(0); obj=ctx->literals[i]; if(!obj || !obj->decl) return(0); if(obj->decl->regflags&BGBCC_REGFL_ACCESSED) return(0); obj->decl->regflags|=BGBCC_REGFL_ACCESSED; for(i=0; i<obj->decl->n_args; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->args[i]->type); } for(i=0; i<obj->decl->n_locals; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->locals[i]->type); } for(i=0; i<obj->decl->n_regs; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->regs[i]->type); } for(i=0; i<obj->decl->n_statics; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->statics[i]->type); } n=obj->decl->n_fields; for(i=0; i<n; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->fields[i]->type); } return(1); } ccxl_status BGBCC_CCXL_MarkTypeVarConv( BGBCC_TransState *ctx, ccxl_type type) { BGBCC_CCXL_LiteralInfo *obj; ccxl_type tty; int i, j, k, n; i=BGBCC_CCXL_TypeObjectLiteralIndex(ctx, type); if(i<0)return(0); obj=ctx->literals[i]; if(!obj || !obj->decl) return(0); if(obj->decl->regflags&BGBCC_REGFL_VARCONV) return(0); obj->decl->regflags|=BGBCC_REGFL_VARCONV; #if 0 for(i=0; i<obj->decl->n_args; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->args[i]->type); } for(i=0; i<obj->decl->n_locals; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->locals[i]->type); } n=obj->decl->n_fields; for(i=0; i<n; i++) { BGBCC_CCXL_MarkTypeAccessed(ctx, obj->decl->fields[i]->type); } #endif if(obj->decl->n_args>0) { // obj=BGBCC_CCXL_LookupStructureForSig(ctx, // obj->decl->args[0]->sig); BGBCC_CCXL_TypeFromSig(ctx, &tty, obj->decl->args[0]->sig); BGBCC_CCXL_MarkTypeVarConv(ctx, tty); } return(1); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureStaticMember( BGBCC_TransState *ctx, char *cname, char *fname) { BGBCC_CCXL_LiteralInfo *obj, *obj1; BGBCC_CCXL_RegisterInfo *ri; int i; obj=BGBCC_CCXL_LookupStructure(ctx, cname); if(!obj) return(NULL); #if 0 if( (obj->littype==CCXL_LITID_CLASS) || (obj->littype==CCXL_LITID_ENUMDEF) ) { for(i=0; i<obj->decl->n_statics; i++) { ri=obj->decl->statics[i]; if(!strcmp(ri->name, fname)) return(ri); } if(obj->decl->n_args>0) { ri=BGBCC_CCXL_LookupStructureStaticMember(ctx, obj->decl->args[0]->name, fname); if(ri) return(ri); } } #endif #if 1 while(obj && ((obj->littype==CCXL_LITID_CLASS) || (obj->littype==CCXL_LITID_ENUMDEF)) ) { for(i=0; i<obj->decl->n_statics; i++) { ri=obj->decl->statics[i]; if(!strcmp(ri->name, fname)) return(ri); } if(obj->decl->n_args>0) { obj=BGBCC_CCXL_LookupStructureForSig(ctx, obj->decl->args[0]->sig); }else { obj=NULL; } } #endif return(NULL); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureStaticMemberRns( BGBCC_TransState *ctx, char *cname, char *fname) { char tb1[256]; BGBCC_CCXL_RegisterInfo *ri, *gbl; int i; ri=NULL; for(i=(ctx->n_imp-1); i>=0; i--) { sprintf(tb1, "%s/%s", ctx->imp_ns[i], cname); gbl=BGBCC_CCXL_LookupStructureStaticMember(ctx, tb1, fname); if(gbl) { ri=gbl; break; } } if(!ri) { gbl=BGBCC_CCXL_LookupStructureStaticMember(ctx, cname, fname); if(gbl) { ri=gbl; } } return(ri); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureMember( BGBCC_TransState *ctx, char *cname, char *fname) { BGBCC_CCXL_LiteralInfo *obj; BGBCC_CCXL_RegisterInfo *ri; int i; obj=BGBCC_CCXL_LookupStructure(ctx, cname); if(!obj) return(NULL); #if 0 if( (obj->littype==CCXL_LITID_STRUCT) || (obj->littype==CCXL_LITID_UNION) || (obj->littype==CCXL_LITID_CLASS) ) { for(i=0; i<obj->decl->n_fields; i++) { ri=obj->decl->fields[i]; if(!strcmp(ri->name, fname)) return(ri); } if(obj->decl->n_args>0) { ri=BGBCC_CCXL_LookupStructureMember(ctx, obj->decl->args[0]->name, fname); if(ri) return(ri); } } #endif #if 1 while(obj && ((obj->littype==CCXL_LITID_STRUCT) || (obj->littype==CCXL_LITID_UNION) || (obj->littype==CCXL_LITID_CLASS)) ) { for(i=0; i<obj->decl->n_fields; i++) { ri=obj->decl->fields[i]; if(!strcmp(ri->name, fname)) return(ri); } if(obj->decl->n_args>0) { obj=BGBCC_CCXL_LookupStructureForSig(ctx, obj->decl->args[0]->sig); }else { obj=NULL; } } #endif return(NULL); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureMethod( BGBCC_TransState *ctx, char *cname, char *fname, char *sig) { BGBCC_CCXL_LiteralInfo *obj; BGBCC_CCXL_RegisterInfo *ri; int i; obj=BGBCC_CCXL_LookupStructure(ctx, cname); if(!obj) return(NULL); while(obj && ((obj->littype==CCXL_LITID_STRUCT) || (obj->littype==CCXL_LITID_UNION) || (obj->littype==CCXL_LITID_CLASS)) ) { for(i=0; i<obj->decl->n_regs; i++) { ri=obj->decl->regs[i]; // if(!strcmp(ri->name, fname)) // return(ri); if(!bgbcc_strcmp_nosig(ri->name, fname)) { if(sig && !BGBCC_CCXL_MatchSig(ctx, ri->sig, sig)) continue; return(ri); } } if(obj->decl->n_args>0) { obj=BGBCC_CCXL_LookupStructureForSig(ctx, obj->decl->args[0]->sig); }else { obj=NULL; } } return(NULL); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureMethodRns( BGBCC_TransState *ctx, char *cname, char *fname, char *sig) { char tb1[256]; BGBCC_CCXL_RegisterInfo *ri, *gbl; int i; ri=NULL; for(i=(ctx->n_imp-1); i>=0; i--) { sprintf(tb1, "%s/%s", ctx->imp_ns[i], cname); gbl=BGBCC_CCXL_LookupStructureMethod(ctx, tb1, fname, sig); if(gbl) { ri=gbl; break; } } if(!ri) { gbl=BGBCC_CCXL_LookupStructureMethod(ctx, cname, fname, sig); if(gbl) { ri=gbl; } } return(ri); } BGBCC_CCXL_RegisterInfo *BGBCC_CCXL_LookupStructureVirtualMethod( BGBCC_TransState *ctx, char *cname, char *fname, char *sig) { BGBCC_CCXL_LiteralInfo *obj; BGBCC_CCXL_RegisterInfo *ri; int i; ri=BGBCC_CCXL_LookupStructureMethod(ctx, cname, fname, sig); if(!ri) return(NULL); if(ri->flagsint&BGBCC_TYFL_STATIC) return(NULL); return(ri); }
17.447086
71
0.613204
[ "object" ]
6cfce3ecdc5051bb4b5d3a0fedfc98dfdb5168b5
4,418
h
C
heyp/cluster-agent/fast-controller.h
uluyol/heyp-agents
7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6
[ "MIT" ]
5
2022-01-09T05:55:22.000Z
2022-03-28T00:21:23.000Z
heyp/cluster-agent/fast-controller.h
uluyol/heyp-agents
7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6
[ "MIT" ]
21
2021-08-30T03:22:20.000Z
2022-01-28T03:22:12.000Z
heyp/cluster-agent/fast-controller.h
uluyol/heyp-agents
7e45bb636aa6a108e0e9d81a0e9f6e8c744798c6
[ "MIT" ]
null
null
null
#ifndef HEYP_CLUSTER_AGENT_FAST_CONTROLLER_H_ #define HEYP_CLUSTER_AGENT_FAST_CONTROLLER_H_ #include <atomic> #include "absl/container/btree_map.h" #include "absl/functional/function_ref.h" #include "heyp/alg/downgrade/impl-hashing.h" #include "heyp/alg/sampler.h" #include "heyp/alg/unordered-ids.h" #include "heyp/cluster-agent/controller-iface.h" #include "heyp/cluster-agent/fast-aggregator.h" #include "heyp/cluster-agent/per-agg-allocators/util.h" #include "heyp/flows/map.h" #include "heyp/proto/config.pb.h" #include "heyp/proto/heyp.pb.h" #include "heyp/threads/executor.h" #include "heyp/threads/par-indexed-map.h" namespace heyp { // FastController is a controller that can quickly perform downgrade // using sampling and (mostly or fully) demand-oblivious downgrade selection. // // It is not as full featured as ClusterController.s class FastClusterController : public ClusterController { public: static std::unique_ptr<FastClusterController> Create( const proto::FastClusterControllerConfig& config, const proto::AllocBundle& cluster_wide_allocs); void UpdateInfo(ParID bundler_id, const proto::InfoBundle& info) override { aggregator_.UpdateInfo(info); } void ComputeAndBroadcast() override; class Listener; // on_new_bundle_func should not block. std::unique_ptr<ClusterController::Listener> RegisterListener( uint64_t host_id, const OnNewBundleFunc& on_new_bundle_func) override; ParID GetBundlerID(const proto::FlowMarker& bundler) override { return 0; /* currently unused by FastClusterController */ } class Listener : public ClusterController::Listener { public: ~Listener(); Listener(const Listener&) = delete; Listener& operator=(const Listener&) = delete; private: Listener(); ParID host_par_id_; uint64_t lis_id_; FastClusterController* controller_ = nullptr; friend class FastClusterController; }; private: FastClusterController(const proto::FastClusterControllerConfig& config, ClusterFlowMap<int64_t> agg_flow2id, std::vector<proto::FlowMarker> agg_id2flow, std::vector<int64_t> approval_bps, std::vector<ThresholdSampler> samplers, int num_threads); const ClusterFlowMap<int64_t> agg_flow2id_; const std::vector<proto::FlowMarker> agg_id2flow_; const std::vector<int64_t> approval_bps_; spdlog::logger logger_; Executor exec_; FastAggregator aggregator_; struct PerAggState { double downgrade_frac = 0; double ewma_max_child_usage = -1; std::optional<DowngradeFracController> frac_controller; }; std::vector<PerAggState> agg_states_; std::vector<HashingDowngradeSelector> agg_selectors_; std::atomic<uint64_t> next_lis_id_; struct ChildState { std::vector<bool> agg_is_lopri; absl::flat_hash_map<uint64_t, OnNewBundleFunc> lis_new_bundle_funcs; int64_t gen_seen = 0; bool broadcasted_latest_state = false; bool saw_data_this_run = false; }; ParIndexedMap<uint64_t, ChildState, absl::flat_hash_map<uint64_t, ParID>> child_states_; // base_bundle should have flows_allocs[i].flow populated for all aggregate flows. void BroadcastStateUnconditional(const SendBundleAux& aux, proto::AllocBundle* base_bundle, ChildState& state); void BroadcastStateIfUpdated(const SendBundleAux& aux, proto::AllocBundle* base_bundle, ChildState& state); // A copy of the id map in child_states_ that is maintained so that we don't need to // synchronize between UpdateInfo and ComputeAndBroadcast. // Additionally, we can specialize the respresentations to serve each use the best. // // Only used by ComputeAndBroadcast. absl::btree_map<uint64_t, ParID> host2par_; // A list of new host ID information that will be drained and added to host2par_ when // ComputeAndBroadcast runs. // // Pushed to in RegisterListener and drained in ComputeAndBroadcast. absl::Mutex mu_; std::vector<std::pair<uint64_t, ParID>> new_host_id_pairs_ ABSL_GUARDED_BY(mu_); }; // Time complexity: O(log(id2par) * (ids.ranges + ids.points)) void ForEachSelected(const absl::btree_map<uint64_t, ParID>& id2par, UnorderedIds ids, absl::FunctionRef<void(uint64_t, ParID)> func); } // namespace heyp #endif // HEYP_CLUSTER_AGENT_FAST_CONTROLLER_H_
34.787402
90
0.733816
[ "vector" ]
6cfd5472b8ee06de2cd116e2ed37501a5e18b771
335
h
C
include/Triangle.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
include/Triangle.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
include/Triangle.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
#pragma once #include <Vertex.h> #include <vector> #include <cassert> struct Triangle { Vertex m_v1; Vertex m_v2; Vertex m_v3; Vec3 m_normal; Color m_color; Vertex& operator[](int p_index) { switch (p_index % 3) { case 0: return m_v1; case 1: return m_v2; case 2: return m_v3; default: break; } } };
11.964286
32
0.638806
[ "vector" ]
9f009322be36208e3d67c202f2dfe2938f8d45c5
3,256
c
C
d/avatars/lurue/id_adder.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/avatars/lurue/id_adder.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
null
null
null
d/avatars/lurue/id_adder.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
// Coded by Lujke. These are the devilkin's dancing boots. They are // enchanted to +1, have an ac setting of -1 when worn, but give a bonus // of +1 to dex. #include <std.h> #include <move.h> inherit ARMOUR; string * ids, wearer; void create() { ::create(); set_short("id adder"); set_name("strange item"); set_id(({"id adder","adder",})); set_long("Four sets of red eyes, which Lurue can use alterobj on if she wants it to look fancier"); set_weight(5); set_type("clothing"); set_limbs(({"head"})); set_ac(0); set_value(50); set_wear((:TO,"wearme":)); set_read("You can use this item to add or remove ids from the creature who wears it. Use the" +" commands:\n add id <id>\ndelete id <id>\n list ids\nclear ids\n You can also 'set wearer" +" <wearer>, to change the creature the item is bound to."); ids = ({}); } void init(){ ::init(); if (objectp(ETO)&& interactive(ETO)){ if (!avatarp(ETO)){ remove(); } } add_action("list_ids", "list"); add_action("add_id", "add"); add_action("remove_id", "delete"); add_action("clear_ids", "clear"); add_action("set_wearer", "set"); } int set_wearer(string str){ string who; object what; if (!avatarp(TP) && !TP->query_true_invis()){ return 0; } if (sscanf(str, "wearer %s", who)<1){ return notify_fail("Try 'set wearer <who>'"); } what = present(who, ETP); if (!objectp(what)){ tell_object(TP, who + " is not here"); } wearer = (string)what->query_name(); tell_object(TP, "Wearer changed. " + who + " should now be able to wear the item"); return 1; } string query_wearer(){ return wearer; } int wearme() { if (!objectp(TO)||!objectp(ETO)||!objectp(EETO)){return 0;} if (!ETO->id(wearer)){ tell_object(ETO, "You can't wear those! You don't look like a big greasy ball of slime!"); call_out("wear2", 2, ETO); return 0; } ETO->add_id("slime"); ETO->add_id("creature"); ETO->add_id("beast"); return 1; } wear2(object ob){ if (objectp(ob)){ tell_object(ob, "Well, on reflection maybe you do. But you still can't wear them!"); } } int list_ids(string str){ int i; if (sizeof(ids)<1){ tell_object(TP, "There are no ids set. Start your own by typing 'add id <id>'"); return 1; } tell_object(TP, "The current ids set are:"); for (i=0;i<sizeof(ids);i++){ tell_object(TP, ids[i]); } return 1; } int add_id(string str){ string what; if ( sscanf(str, "id %s", what) <1){ tell_object(TP, "Try 'add id <id>'"); return 1; } if (member_array(what, ids)!= -1){ tell_object(TP, "That id is already on the list"); return 1; } tell_object(TP, "id '" + what + "' added."); ids += ({what}); return 1; } int remove_id(string str){ string what; if ( sscanf(str, "id %s", what) <1){ tell_object(TP, "Try 'delete id <id>'"); return 1; } if (member_array(what, ids)== -1){ tell_object(TP, "That id is not on the list. You don't need to delete it."); return 1; } tell_object(TP, "id '" + what + "' removed."); ids -= ({what}); return 1; } int clear_ids(string str){ if (str != "ids"){ return notify_fail("Try 'clear ids'"); } tell_object(TP, "id list cleared"); ids = ({}); }
23.42446
101
0.604423
[ "object" ]
9f012390f306b4ec1a2f5a20402db191838ac75b
762
h
C
inference_backend/image_inference/async_with_va_api/image_inference_async/thread_pool.h
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
125
2020-09-18T10:50:27.000Z
2022-02-10T06:20:59.000Z
inference_backend/image_inference/async_with_va_api/image_inference_async/thread_pool.h
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
155
2020-09-10T23:32:29.000Z
2022-02-05T07:10:26.000Z
inference_backend/image_inference/async_with_va_api/image_inference_async/thread_pool.h
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
41
2020-09-15T08:49:17.000Z
2022-01-24T10:39:36.000Z
/******************************************************************************* * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #pragma once #include <chrono> #include <condition_variable> #include <functional> #include <future> #include <queue> #include <thread> class ThreadPool { private: std::vector<std::thread> _threads; std::queue<std::function<void()>> _tasks; std::condition_variable _condition_variable; std::mutex _mutex; bool _terminate = false; void _task_runner(); public: explicit ThreadPool(size_t size); ~ThreadPool(); std::future<void> schedule(const std::function<void()> &callable); };
23.090909
80
0.545932
[ "vector" ]
9f0238794a4b96382ff6c3d03db8279cfbdeb595
2,210
h
C
src/conv/step/step-g/STEPEntity.h
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
83
2021-03-10T05:54:52.000Z
2022-03-31T16:33:46.000Z
src/conv/step/step-g/STEPEntity.h
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
13
2021-06-24T17:07:48.000Z
2022-03-31T15:31:33.000Z
src/conv/step/step-g/STEPEntity.h
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
54
2021-03-10T07:57:06.000Z
2022-03-28T23:20:37.000Z
/* S T E P E N T I T Y . H * BRL-CAD * * Copyright (c) 2009-2021 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This 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 file; see the file named COPYING for more * information. */ #ifndef CONV_STEP_STEP_G_STEPENTITY_H #define CONV_STEP_STEP_G_STEPENTITY_H #include "common.h" /* system headers */ #include <iostream> #include "STEPWrapper.h" class ON_Brep; class STEPEntity; // A generic pseudo-constructor function type. Descendants of STEPEntity have // a private static member of this type (GetInstance) which returns a pointer // to a new instance of the subtype cast to a STEPEntity*. typedef STEPEntity *(EntityInstanceFunc)(STEPWrapper *sw, int id); #define POINT_CLOSENESS_TOLERANCE 1e-6 #define TAB(j) \ { \ for ( int tab_index=0; tab_index< j; tab_index++) \ std::cout << " "; \ } class STEPEntity { protected: int id; int ON_id; STEPWrapper *step; static STEPEntity *CreateEntity( STEPWrapper *sw, SDAI_Application_instance *sse, EntityInstanceFunc Instance, const char *classname); public: STEPEntity(); virtual ~STEPEntity(); int GetId() { return id; } void SetId(int nid) { id = nid; } int GetONId() { return ON_id; } void SetONId(int on_id) { ON_id = on_id; } int STEPid(); STEPWrapper *Step(); virtual bool Load(STEPWrapper *UNUSED(sw), SDAI_Application_instance *UNUSED(sse)) { return false; }; }; #endif /* CONV_STEP_STEP_G_STEPENTITY_H */ /* * Local Variables: * tab-width: 8 * mode: C * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
23.763441
88
0.695928
[ "cad" ]
9f147211f893dac16bc6dfa2c01f7d2ff8ade0fe
463
h
C
offline_compiler/decoder/helper.h
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
offline_compiler/decoder/helper.h
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
offline_compiler/decoder/helper.h
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include <string> #include <vector> #include <exception> void addSlash(std::string &path); std::vector<char> readBinaryFile(const std::string &fileName); void readFileToVectorOfStrings(std::vector<std::string> &lines, const std::string &fileName, bool replaceTabs = false); size_t findPos(const std::vector<std::string> &lines, const std::string &whatToFind);
23.15
119
0.732181
[ "vector" ]
9f18bea0ed459b4a250904d82f4a4ead51debbf7
1,033
h
C
content/public/browser/hid_chooser.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/public/browser/hid_chooser.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
content/public/browser/hid_chooser.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 CONTENT_PUBLIC_BROWSER_HID_CHOOSER_H_ #define CONTENT_PUBLIC_BROWSER_HID_CHOOSER_H_ #include <vector> #include "base/callback_forward.h" #include "content/common/content_export.h" #include "services/device/public/mojom/hid.mojom-forward.h" namespace content { // Token representing an open HID device chooser prompt. Destroying this // object should cancel the prompt. class CONTENT_EXPORT HidChooser { public: // Callback type used to report the user action. An empty vector is passed if // no device was selected. using Callback = base::OnceCallback<void(std::vector<device::mojom::HidDeviceInfoPtr>)>; HidChooser() = default; HidChooser(const HidChooser&) = delete; HidChooser& operator=(const HidChooser&) = delete; virtual ~HidChooser() = default; }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_HID_CHOOSER_H_
28.694444
79
0.763795
[ "object", "vector" ]
9f269af7b3de104d0d35f738ac648db15c0ae6f5
555
h
C
idlesse/Classes/MusicNews/Views/ZPEquipmentOrStrategyCell.h
fakepinge/idlesse
9d021f0995f9c508db65f5c7c0fc42ee55dea6a7
[ "MIT" ]
2
2018-05-21T02:02:03.000Z
2018-10-18T09:14:32.000Z
idlesse/Classes/MusicNews/Views/ZPEquipmentOrStrategyCell.h
fakepinge/idlesse
9d021f0995f9c508db65f5c7c0fc42ee55dea6a7
[ "MIT" ]
null
null
null
idlesse/Classes/MusicNews/Views/ZPEquipmentOrStrategyCell.h
fakepinge/idlesse
9d021f0995f9c508db65f5c7c0fc42ee55dea6a7
[ "MIT" ]
null
null
null
// // ZPEquipmentOrStrategyCell.h // idlesse // // Created by 胡知平 on 16/6/3. // Copyright © 2016年 fakepinge. All rights reserved. // #import <UIKit/UIKit.h> @class ZPMusicNewsModel; @interface ZPEquipmentOrStrategyCell : UITableViewCell /**模型*/ @property (nonatomic, strong) ZPMusicNewsModel *model; @property (weak, nonatomic) IBOutlet UILabel *titleLabel; @property (weak, nonatomic) IBOutlet UILabel *timeLabel; @property (weak, nonatomic) IBOutlet UILabel *readLabel; @property (weak, nonatomic) IBOutlet UIImageView *musicImageView; @end
21.346154
65
0.751351
[ "model" ]
378ba338af639feb7351caeebd7bf91f091d73c2
805
h
C
macosxcocoa/lesson27/Lesson27_OSXCocoa/3Dobject.h
neozhou2009/nehe-opengl
9f073e5b092ad8dbcb21393871a2855fe86a65c6
[ "MIT" ]
177
2017-12-31T04:44:27.000Z
2022-03-23T10:08:03.000Z
macosxcocoa/lesson27/Lesson27_OSXCocoa/3Dobject.h
neozhou2009/nehe-opengl
9f073e5b092ad8dbcb21393871a2855fe86a65c6
[ "MIT" ]
2
2018-06-28T20:28:33.000Z
2018-09-09T17:34:44.000Z
macosxcocoa/lesson27/Lesson27_OSXCocoa/3Dobject.h
neozhou2009/nehe-opengl
9f073e5b092ad8dbcb21393871a2855fe86a65c6
[ "MIT" ]
72
2018-01-07T16:41:29.000Z
2022-03-18T17:57:38.000Z
#if !defined(_3DOBJECT_H_) #define _3DOBJECT_H_ #include <stdio.h> #import <OpenGL/OpenGL.h> #import <OpenGL/gl.h> #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif // vertex in 3d-coordinate system struct sPoint{ float x, y, z; }; // plane equation struct sPlaneEq{ float a, b, c, d; }; // structure describing an object's face struct sPlane{ unsigned int p[3]; sPoint normals[3]; unsigned int neigh[3]; sPlaneEq PlaneEq; bool visible; }; // object structure struct glObject{ GLuint nPlanes, nPoints; sPoint points[100]; sPlane planes[200]; }; int ReadObject(const char *st, glObject *o); void SetConnectivity(glObject *o); void CalcPlane(glObject o, sPlane *plane); void DrawGLObject(glObject o); void CastShadow(glObject *o, float *lp); #endif // _3DOBJECT_H_
16.428571
44
0.721739
[ "object", "3d" ]
378f88f45f30a941016a6ebc0c3eca62e029e2e6
423
h
C
PSI/include/a/PsiReceiver.h
xiaozhao1234/PSI-CA
2476c12e00800c170a30be4ebf7f6075cd1d5cbe
[ "MIT" ]
null
null
null
PSI/include/a/PsiReceiver.h
xiaozhao1234/PSI-CA
2476c12e00800c170a30be4ebf7f6075cd1d5cbe
[ "MIT" ]
null
null
null
PSI/include/a/PsiReceiver.h
xiaozhao1234/PSI-CA
2476c12e00800c170a30be4ebf7f6075cd1d5cbe
[ "MIT" ]
null
null
null
#pragma once #include "Defines.h" #include <vector> namespace PSI { class PsiReceiver { public: PsiReceiver() {} void run(PRNG& prng, Channel& ch, block commonSeed, const u64& senderSize, const u64& receiverSize, const u64& height, const u64& logHeight, const u64& width, std::vector<block>& receiverSet, const u64& hashLengthInBytes, const u64& h1LengthInBytes, const u64& bucket1, const u64& bucket2); }; }
23.5
292
0.725768
[ "vector" ]
37924f1479f3112010bd6fb5e0d6c32033d5a30a
1,151
h
C
CMSIS/DSP/Testing/Include/Benchmarks/BayesF16.h
Yin-Cheng-888/CMSIS_5
43574aa3a2f2b25f5f62513aadb0ffda36c5c55e
[ "Apache-2.0" ]
1
2022-03-30T02:43:52.000Z
2022-03-30T02:43:52.000Z
CMSIS/DSP/Testing/Include/Benchmarks/BayesF16.h
Yin-Cheng-888/CMSIS_5
43574aa3a2f2b25f5f62513aadb0ffda36c5c55e
[ "Apache-2.0" ]
null
null
null
CMSIS/DSP/Testing/Include/Benchmarks/BayesF16.h
Yin-Cheng-888/CMSIS_5
43574aa3a2f2b25f5f62513aadb0ffda36c5c55e
[ "Apache-2.0" ]
1
2021-07-30T06:50:56.000Z
2021-07-30T06:50:56.000Z
#include "Test.h" #include "Pattern.h" #include "dsp/bayes_functions_f16.h" class BayesF16:public Client::Suite { public: BayesF16(Testing::testID_t id); virtual void setUp(Testing::testID_t,std::vector<Testing::param_t>& paramsArgs,Client::PatternMgr *mgr); virtual void tearDown(Testing::testID_t,Client::PatternMgr *mgr); private: #include "BayesF16_decl.h" Client::Pattern<float16_t> input; Client::Pattern<float16_t> params; Client::Pattern<int16_t> dims; Client::LocalPattern<float16_t> outputProbas; Client::LocalPattern<int16_t> outputPredicts; // Reference patterns are not loaded when we are in dump mode Client::RefPattern<int16_t> predicts; int classNb,vecDim; int nb=0; const float16_t *theta; const float16_t *sigma; const float16_t *classPrior; float16_t epsilon; arm_gaussian_naive_bayes_instance_f16 bayes; const float16_t *inp; float16_t *bufp; };
30.289474
116
0.599479
[ "vector" ]
3799bd1d073c8b56998318ea9cc8a97ea4ca0020
3,013
h
C
src/canvas.h
sgrayrw/canvas-drawer
8c5d0102a5b5fee24d367a65e0230a17e7e7be93
[ "MIT" ]
null
null
null
src/canvas.h
sgrayrw/canvas-drawer
8c5d0102a5b5fee24d367a65e0230a17e7e7be93
[ "MIT" ]
null
null
null
src/canvas.h
sgrayrw/canvas-drawer
8c5d0102a5b5fee24d367a65e0230a17e7e7be93
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "ppm_image.h" using namespace std; namespace agl { enum PrimitiveType { UNDEFINED, LINES, TRIANGLES }; struct point { int x; int y; ppm_pixel color; }; class canvas { public: canvas(int w, int h); virtual ~canvas(); // Save to file void save(const std::string &filename); // Draw primitives with a given type (either LINES or TRIANGLES) // For example, the following draws a red line followed by a green line // begin(LINES); // color(255,0,0); // vertex(0,0); // vertex(100,0); // color(0,255,0); // vertex(0, 0); // vertex(0,100); // end(); void begin(PrimitiveType type); void end(); // Specifiy a vertex at raster position (x,y) // x corresponds to the column; y to the row void vertex(int x, int y); // Specify a color. Color components are in range [0,255] void color(unsigned char r, unsigned char g, unsigned char b); // Fill the canvas with the given background color void background(unsigned char r, unsigned char g, unsigned char b); //******************* additional features below ******************* // draw a circle with given center (x, y) and radius void draw_circle(int x, int y, int radius); // draw a rectangel with given center (x, y), width, and height void draw_rectangle(int x, int y, int width, int height); // set the width of shape borders void set_width(int width); // Resemble dotted lines by randomly missing some pixels, and expect // to only draw *ratio* amount of pixels in total void dotted(float ratio); private: ppm_image _canvas; ppm_pixel curr_color = {0, 0, 0}; ppm_pixel curr_background = {0, 0, 0}; PrimitiveType curr_type = UNDEFINED; vector<point> curr_points; int curr_width = 1; float curr_ratio = 1; static ppm_pixel linear_interpolate(const ppm_pixel &c1, const ppm_pixel &c2, float t); void draw_line(const point& start, const point& end); void draw_line_vertical(int ax, int ay, int bx, int by, const ppm_pixel &cx, const ppm_pixel &cy); void draw_line_horizontal(int ax, int ay, int bx, int by, const ppm_pixel &cx, const ppm_pixel &cy); void draw_line_flat(int ax, int ay, int bx, int by, const ppm_pixel& cx, const ppm_pixel& cy); void draw_line_steep(int ax, int ay, int bx, int by, const ppm_pixel& cx, const ppm_pixel& cy); void draw_triangle(const point &a, const point &b, const point &c); static int line_distance(const point &start, const point &end, const point &p); void draw_circle_internal(int x, int y, int radius); void draw_rectangle_internal(int x, int y, int width, int height); }; }
32.75
108
0.601062
[ "shape", "vector" ]
379aff3ba4fe91c88dd42fc13c448a8b7c96724d
819
h
C
include/Crypto/CSPRNG.h
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
include/Crypto/CSPRNG.h
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
include/Crypto/CSPRNG.h
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
#pragma once // Copyright (c) 2018-2019 David Burkett // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #include <Common/ImportExport.h> #include <Common/Secure.h> #include <Crypto/BigInteger.h> #include <vector> #ifdef MW_CRYPTO #define CRYPTO_API EXPORT #else #define CRYPTO_API IMPORT #endif // // A wrapper around a third-party CSPRNG random number generator to generate cryptographically-secure random numbers. // class CRYPTO_API CSPRNG { public: // // Generates a cryptographically-strong pseudo-random 32-byte number. // static CBigInteger<32> GenerateRandom32(); static SecureVector GenerateRandomBytes(const size_t numBytes); static uint64_t GenerateRandom(const uint64_t minimum, const uint64_t maximum); };
25.59375
117
0.781441
[ "vector" ]
37a365a8b50f595aad4e992133e87da926b6d927
3,771
h
C
src/dpdk/drivers/net/mlx4/mlx4_mr.h
Elvor/trex-core
c518275a922ed99612cd82574ed9574809f055ec
[ "Apache-2.0" ]
17
2019-01-30T23:44:08.000Z
2021-08-13T09:39:21.000Z
src/dpdk/drivers/net/mlx4/mlx4_mr.h
Elvor/trex-core
c518275a922ed99612cd82574ed9574809f055ec
[ "Apache-2.0" ]
3
2018-04-25T20:28:49.000Z
2018-07-16T13:45:40.000Z
src/dpdk/drivers/net/mlx4/mlx4_mr.h
Elvor/trex-core
c518275a922ed99612cd82574ed9574809f055ec
[ "Apache-2.0" ]
9
2019-02-04T09:12:33.000Z
2021-11-14T23:06:47.000Z
/* SPDX-License-Identifier: BSD-3-Clause * Copyright 2018 6WIND S.A. * Copyright 2018 Mellanox Technologies, Ltd */ #ifndef RTE_PMD_MLX4_MR_H_ #define RTE_PMD_MLX4_MR_H_ #include <stddef.h> #include <stdint.h> #include <sys/queue.h> /* Verbs headers do not support -pedantic. */ #ifdef PEDANTIC #pragma GCC diagnostic ignored "-Wpedantic" #endif #include <infiniband/verbs.h> #ifdef PEDANTIC #pragma GCC diagnostic error "-Wpedantic" #endif #include <rte_eal_memconfig.h> #include <rte_ethdev.h> #include <rte_rwlock.h> #include <rte_bitmap.h> /* Size of per-queue MR cache array for linear search. */ #define MLX4_MR_CACHE_N 8 /* Size of MR cache table for binary search. */ #define MLX4_MR_BTREE_CACHE_N 256 /* Memory Region object. */ struct mlx4_mr { LIST_ENTRY(mlx4_mr) mr; /**< Pointer to the prev/next entry. */ struct ibv_mr *ibv_mr; /* Verbs Memory Region. */ const struct rte_memseg_list *msl; int ms_base_idx; /* Start index of msl->memseg_arr[]. */ int ms_n; /* Number of memsegs in use. */ uint32_t ms_bmp_n; /* Number of bits in memsegs bit-mask. */ struct rte_bitmap *ms_bmp; /* Bit-mask of memsegs belonged to MR. */ }; /* Cache entry for Memory Region. */ struct mlx4_mr_cache { uintptr_t start; /* Start address of MR. */ uintptr_t end; /* End address of MR. */ uint32_t lkey; /* rte_cpu_to_be_32(ibv_mr->lkey). */ } __rte_packed; /* MR Cache table for Binary search. */ struct mlx4_mr_btree { uint16_t len; /* Number of entries. */ uint16_t size; /* Total number of entries. */ int overflow; /* Mark failure of table expansion. */ struct mlx4_mr_cache (*table)[]; } __rte_packed; /* Per-queue MR control descriptor. */ struct mlx4_mr_ctrl { uint32_t *dev_gen_ptr; /* Generation number of device to poll. */ uint32_t cur_gen; /* Generation number saved to flush caches. */ uint16_t mru; /* Index of last hit entry in top-half cache. */ uint16_t head; /* Index of the oldest entry in top-half cache. */ struct mlx4_mr_cache cache[MLX4_MR_CACHE_N]; /* Cache for top-half. */ struct mlx4_mr_btree cache_bh; /* Cache for bottom-half. */ } __rte_packed; extern struct mlx4_dev_list mlx4_mem_event_cb_list; extern rte_rwlock_t mlx4_mem_event_rwlock; /* First entry must be NULL for comparison. */ #define mlx4_mr_btree_len(bt) ((bt)->len - 1) int mlx4_mr_btree_init(struct mlx4_mr_btree *bt, int n, int socket); void mlx4_mr_btree_free(struct mlx4_mr_btree *bt); void mlx4_mr_btree_dump(struct mlx4_mr_btree *bt); void mlx4_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr, size_t len, void *arg); int mlx4_mr_update_mp(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl, struct rte_mempool *mp); void mlx4_mr_dump_dev(struct rte_eth_dev *dev); void mlx4_mr_release(struct rte_eth_dev *dev); /** * Look up LKey from given lookup table by linear search. Firstly look up the * last-hit entry. If miss, the entire array is searched. If found, update the * last-hit index and return LKey. * * @param lkp_tbl * Pointer to lookup table. * @param[in,out] cached_idx * Pointer to last-hit index. * @param n * Size of lookup table. * @param addr * Search key. * * @return * Searched LKey on success, UINT32_MAX on no match. */ static __rte_always_inline uint32_t mlx4_mr_lookup_cache(struct mlx4_mr_cache *lkp_tbl, uint16_t *cached_idx, uint16_t n, uintptr_t addr) { uint16_t idx; if (likely(addr >= lkp_tbl[*cached_idx].start && addr < lkp_tbl[*cached_idx].end)) return lkp_tbl[*cached_idx].lkey; for (idx = 0; idx < n && lkp_tbl[idx].start != 0; ++idx) { if (addr >= lkp_tbl[idx].start && addr < lkp_tbl[idx].end) { /* Found. */ *cached_idx = idx; return lkp_tbl[idx].lkey; } } return UINT32_MAX; } #endif /* RTE_PMD_MLX4_MR_H_ */
30.658537
78
0.719173
[ "object" ]
37a40c8debf3f5843307e8ba6f4955d491e6f045
5,526
h
C
modules/PoissonRecon/include/Mesh/PoissonRecon/FunctionData.h
ahmadhasan2k8/PoissonRecon
e5a3f4f018a282ee4cea5928e3dbb7a1b2e14614
[ "MIT" ]
7
2017-10-04T22:22:08.000Z
2020-06-30T01:31:47.000Z
modules/PoissonRecon/include/Mesh/PoissonRecon/FunctionData.h
ahmadhasan2k8/PoissonRecon
e5a3f4f018a282ee4cea5928e3dbb7a1b2e14614
[ "MIT" ]
2
2017-10-07T00:14:31.000Z
2019-05-31T17:25:08.000Z
modules/PoissonRecon/include/Mesh/PoissonRecon/FunctionData.h
ahmadhasan2k8/PoissonRecon
e5a3f4f018a282ee4cea5928e3dbb7a1b2e14614
[ "MIT" ]
6
2017-10-06T02:59:26.000Z
2020-08-31T23:05:32.000Z
/* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho 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 Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUNCTION_DATA_INCLUDED #define FUNCTION_DATA_INCLUDED #define BOUNDARY_CONDITIONS 1 #include "Mesh/PoissonRecon/PPolynomial.h" template <int Degree, class Real> class FunctionData { bool useDotRatios; int normalize; #if BOUNDARY_CONDITIONS bool reflectBoundary; #endif // BOUNDARY_CONDITIONS public: const static int DOT_FLAG = 1; const static int D_DOT_FLAG = 2; const static int D2_DOT_FLAG = 4; const static int VALUE_FLAG = 1; const static int D_VALUE_FLAG = 2; int depth, res, res2; Real *dotTable, *dDotTable, *d2DotTable; Real *valueTables, *dValueTables; #if BOUNDARY_CONDITIONS PPolynomial<Degree> baseFunction, leftBaseFunction, rightBaseFunction; PPolynomial<Degree - 1> dBaseFunction, dLeftBaseFunction, dRightBaseFunction; #else // !BOUNDARY_CONDITIONS PPolynomial<Degree> baseFunction; PPolynomial<Degree - 1> dBaseFunction; #endif // BOUNDARY_CONDITIONS PPolynomial<Degree + 1>* baseFunctions; FunctionData(void); ~FunctionData(void); virtual void setDotTables(const int& flags); virtual void clearDotTables(const int& flags); virtual void setValueTables(const int& flags, const double& smooth = 0); virtual void setValueTables(const int& flags, const double& valueSmooth, const double& normalSmooth); virtual void clearValueTables(void); /******************************************************** * Sets the translates and scales of the basis function * up to the prescribed depth * <maxDepth> the maximum depth * <F> the basis function * <normalize> how the functions should be scaled * 0] Value at zero equals 1 * 1] Integral equals 1 * 2] L2-norm equals 1 * <useDotRatios> specifies if dot-products of derivatives * should be pre-divided by function integrals * <reflectBoundary> spcifies if function space should be * forced to be reflectively symmetric across the boundary ********************************************************/ #if BOUNDARY_CONDITIONS void set(const int& maxDepth, const PPolynomial<Degree>& F, const int& normalize, bool useDotRatios = true, bool reflectBoundary = false); #else // !BOUNDARY_CONDITIONS void set(const int& maxDepth, const PPolynomial<Degree>& F, const int& normalize, bool useDotRatios = true); #endif // BOUNDARY_CONDITIONS #if BOUNDARY_CONDITIONS Real dotProduct(const double& center1, const double& width1, const double& center2, const double& width2, int boundary1, int boundary2) const; Real dDotProduct(const double& center1, const double& width1, const double& center2, const double& width2, int boundary1, int boundary2) const; Real d2DotProduct(const double& center1, const double& width1, const double& center2, const double& width2, int boundary1, int boundary2) const; #else // !BOUNDARY_CONDITIONS Real dotProduct(const double& center1, const double& width1, const double& center2, const double& width2) const; Real dDotProduct(const double& center1, const double& width1, const double& center2, const double& width2) const; Real d2DotProduct(const double& center1, const double& width1, const double& center2, const double& width2) const; #endif // BOUNDARY_CONDITIONS static inline int SymmetricIndex(const int& i1, const int& i2); static inline int SymmetricIndex(const int& i1, const int& i2, int& index); }; #include "Mesh/PoissonRecon/FunctionData.inl" #endif // FUNCTION_DATA_INCLUDED
38.915493
80
0.675896
[ "mesh" ]
37a731d2a2bb733086085d2947cac40d41e37bc7
2,853
h
C
Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Comparison_1_gen2998427754MethodDeclarations.h
screwylightbulb/europa
3dcc98369c8066cb2310143329535206751c8846
[ "MIT" ]
11
2016-07-22T19:58:09.000Z
2021-09-21T12:51:40.000Z
Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Comparison_1_gen2998427754MethodDeclarations.h
screwylightbulb/europa
3dcc98369c8066cb2310143329535206751c8846
[ "MIT" ]
1
2018-05-07T14:32:13.000Z
2018-05-08T09:15:30.000Z
iOS/Classes/Native/mscorlib_System_Comparison_1_gen2998427754MethodDeclarations.h
mopsicus/unity-share-plugin-ios-android
3ee99aef36034a1e4d7b156172953f9b4dfa696f
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // System.Comparison`1<UnityEngine.Vector4> struct Comparison_1_t2998427754; // System.Object struct Il2CppObject; // System.IAsyncResult struct IAsyncResult_t2754620036; // System.AsyncCallback struct AsyncCallback_t1369114871; #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Object4170816371.h" #include "mscorlib_System_IntPtr4010401971.h" #include "UnityEngine_UnityEngine_Vector44282066567.h" #include "mscorlib_System_AsyncCallback1369114871.h" // System.Void System.Comparison`1<UnityEngine.Vector4>::.ctor(System.Object,System.IntPtr) extern "C" void Comparison_1__ctor_m3317333335_gshared (Comparison_1_t2998427754 * __this, Il2CppObject * ___object0, IntPtr_t ___method1, const MethodInfo* method); #define Comparison_1__ctor_m3317333335(__this, ___object0, ___method1, method) (( void (*) (Comparison_1_t2998427754 *, Il2CppObject *, IntPtr_t, const MethodInfo*))Comparison_1__ctor_m3317333335_gshared)(__this, ___object0, ___method1, method) // System.Int32 System.Comparison`1<UnityEngine.Vector4>::Invoke(T,T) extern "C" int32_t Comparison_1_Invoke_m3660033737_gshared (Comparison_1_t2998427754 * __this, Vector4_t4282066567 ___x0, Vector4_t4282066567 ___y1, const MethodInfo* method); #define Comparison_1_Invoke_m3660033737(__this, ___x0, ___y1, method) (( int32_t (*) (Comparison_1_t2998427754 *, Vector4_t4282066567 , Vector4_t4282066567 , const MethodInfo*))Comparison_1_Invoke_m3660033737_gshared)(__this, ___x0, ___y1, method) // System.IAsyncResult System.Comparison`1<UnityEngine.Vector4>::BeginInvoke(T,T,System.AsyncCallback,System.Object) extern "C" Il2CppObject * Comparison_1_BeginInvoke_m4085291330_gshared (Comparison_1_t2998427754 * __this, Vector4_t4282066567 ___x0, Vector4_t4282066567 ___y1, AsyncCallback_t1369114871 * ___callback2, Il2CppObject * ___object3, const MethodInfo* method); #define Comparison_1_BeginInvoke_m4085291330(__this, ___x0, ___y1, ___callback2, ___object3, method) (( Il2CppObject * (*) (Comparison_1_t2998427754 *, Vector4_t4282066567 , Vector4_t4282066567 , AsyncCallback_t1369114871 *, Il2CppObject *, const MethodInfo*))Comparison_1_BeginInvoke_m4085291330_gshared)(__this, ___x0, ___y1, ___callback2, ___object3, method) // System.Int32 System.Comparison`1<UnityEngine.Vector4>::EndInvoke(System.IAsyncResult) extern "C" int32_t Comparison_1_EndInvoke_m3697677059_gshared (Comparison_1_t2998427754 * __this, Il2CppObject * ___result0, const MethodInfo* method); #define Comparison_1_EndInvoke_m3697677059(__this, ___result0, method) (( int32_t (*) (Comparison_1_t2998427754 *, Il2CppObject *, const MethodInfo*))Comparison_1_EndInvoke_m3697677059_gshared)(__this, ___result0, method)
67.928571
362
0.823694
[ "object" ]
37b50afd3c637465d3a0ccd7ff01d6ee297adca2
5,588
h
C
src/BabylonCpp/include/babylon/postprocesses/volumetric_light_scattering_post_process.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/BabylonCpp/include/babylon/postprocesses/volumetric_light_scattering_post_process.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
src/BabylonCpp/include/babylon/postprocesses/volumetric_light_scattering_post_process.h
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
null
null
null
#ifndef BABYLON_POSTPROCESSES_VOLUMETRIC_LIGHT_SCATTERING_POST_PROCESS_H #define BABYLON_POSTPROCESSES_VOLUMETRIC_LIGHT_SCATTERING_POST_PROCESS_H #include <babylon/babylon_api.h> #include <babylon/maths/viewport.h> #include <babylon/postprocesses/post_process.h> namespace BABYLON { class AbstractMesh; class Mesh; class RenderTargetTexture; class SubMesh; class VolumetricLightScatteringPostProcess; using AbstractMeshPtr = std::shared_ptr<AbstractMesh>; using MeshPtr = std::shared_ptr<Mesh>; using RenderTargetTexturePtr = std::shared_ptr<RenderTargetTexture>; using SubMeshPtr = std::shared_ptr<SubMesh>; using VolumetricLightScatteringPostProcessPtr = std::shared_ptr<VolumetricLightScatteringPostProcess>; /** * @brief VolumetricLightScatteringPostProcess class. * * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html */ class BABYLON_SHARED_EXPORT VolumetricLightScatteringPostProcess : public PostProcess { public: template <typename... Ts> static VolumetricLightScatteringPostProcessPtr New(Ts&&... args) { auto postProcess = std::shared_ptr<VolumetricLightScatteringPostProcess>( new VolumetricLightScatteringPostProcess(std::forward<Ts>(args)...)); postProcess->add(postProcess); return postProcess; } ~VolumetricLightScatteringPostProcess() override; // = default /** * @brief Returns the string "VolumetricLightScatteringPostProcess". * @returns "VolumetricLightScatteringPostProcess" */ [[nodiscard]] std::string getClassName() const override; /** * @brief Sets the new light position for light scattering effect. * @param position The new custom light position */ void setCustomMeshPosition(const Vector3& position); /** * @brief Returns the light position for light scattering effect. * @return Vector3 The custom light position */ Vector3& getCustomMeshPosition(); /** * @brief Disposes the internal assets and detaches the post-process from the * camera. */ void dispose(Camera* camera) override; /** * @brief Returns the render target texture used by the post-process. * @return the render target texture used by the post-process */ RenderTargetTexturePtr& getPass(); //** Static methods **/ / /** * @brief Creates a default mesh for the Volumeric Light Scattering * post-process. * @param name The mesh name * @param scene The scene where to create the mesh * @return the default mesh */ static MeshPtr CreateDefaultMesh(const std::string& name, Scene* scene); protected: /** * @brief Constructor * @param name The post-process name * @param ratio The size of the post-process and/or internal pass (0.5 means * that your postprocess will have a width = canvas.width 0.5 and a height = * canvas.height 0.5) * @param camera The camera that the post-process will be attached to * @param mesh The mesh used to create the light scattering * @param samples The post-process quality, default 100 * @param samplingModeThe post-process filtering mode * @param engine The babylon engine * @param reusable If the post-process is reusable * @param scene The constructor needs a scene reference to initialize internal * components. If "camera" is null a "scene" must be provided */ VolumetricLightScatteringPostProcess( const std::string& name, float ratio, const CameraPtr& camera, const MeshPtr& mesh, unsigned int samples = 100, const std::optional<unsigned int>& samplingMode = std::nullopt, Engine* engine = nullptr, bool reusable = false, Scene* scene = nullptr); private: bool _isReady(SubMesh* subMesh, bool useInstances); bool _meshExcluded(const AbstractMeshPtr& mesh); void _createPass(Scene* scene, float ratio); void _updateMeshScreenCoordinates(Scene* scene); public: /** * If not undefined, the mesh position is computed from the attached node * position */ Vector3* attachedNode; /** * Custom position of the mesh. Used if "useCustomMeshPosition" is set to * "true" */ Vector3 customMeshPosition; /** * Set if the post-process should use a custom position for the light source * (true) or the internal mesh position (false) */ bool useCustomMeshPosition; /** * If the post-process should inverse the light scattering direction */ bool invert; /** * The internal mesh used by the post-process */ MeshPtr mesh; /** * Set to true to use the diffuseColor instead of the diffuseTexture */ bool useDiffuseColor; /** * Array containing the excluded meshes not rendered in the internal pass */ std::vector<AbstractMeshPtr> excludedMeshes; /** * Controls the overall intensity of the post-process */ float exposure; /** * Dissipates each sample's contribution in range [0, 1] */ float decay; /** * Controls the overall intensity of each sample */ float weight; /** * Controls the density of each sample */ float density; private: EffectPtr _volumetricLightScatteringPass; RenderTargetTexturePtr _volumetricLightScatteringRTT; Viewport _viewPort; Vector2 _screenCoordinates; std::string _cachedDefines; Vector3 _customMeshPosition; }; // end of class VolumetricLightScatteringPostProcess } // end of namespace BABYLON #endif // end of // BABYLON_POSTPROCESSES_VOLUMETRIC_LIGHT_SCATTERING_POST_PROCESS_H
32.678363
96
0.709735
[ "mesh", "render", "vector" ]
37c140f4cb172df48ae7435eceb63fe09170a992
58,921
c
C
DIR819_v1.06/src/opensource/dlna/dlna_intel/ChinaTelecomDLNA/MediaServerAbstraction/MediaServerAbstraction.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
DIR819_v1.06/src/opensource/dlna/dlna_intel/ChinaTelecomDLNA/MediaServerAbstraction/MediaServerAbstraction.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
null
null
null
DIR819_v1.06/src/opensource/dlna/dlna_intel/ChinaTelecomDLNA/MediaServerAbstraction/MediaServerAbstraction.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/* * INTEL CONFIDENTIAL * Copyright (c) 2002 - 2006 Intel Corporation. All rights reserved. * * The source code contained or described herein and all documents * related to the source code ("Material") are owned by Intel * Corporation or its suppliers or licensors. Title to the * Material remains with Intel Corporation or its suppliers and * licensors. The Material contains trade secrets and proprietary * and confidential information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright and * trade secret laws and treaty provisions. No part of the Material * may be used, copied, reproduced, modified, published, uploaded, * posted, transmitted, distributed, or disclosed in any way without * Intel's prior express written permission. * No license under any patent, copyright, trade secret or other * intellectual property right is granted to or conferred upon you * by disclosure or delivery of the Materials, either expressly, by * implication, inducement, estoppel or otherwise. Any license * under such intellectual property rights must be express and * approved by Intel in writing. * * $Workfile: MediaServerAbstraction.c * * * */ #ifdef _POSIX #define stricmp strcasecmp #define strcmpi strcasecmp #define strnicmp strncasecmp #endif #ifdef WIN32 #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #ifndef _WIN32_WCE #include <crtdbg.h> #endif #else #include <stdlib.h> #endif #if defined(WINSOCK2) #include <winsock2.h> #elif defined(WINSOCK1) #include <winsock.h> #endif #include <stdio.h> #include <string.h> #include "ILibAsyncSocket.h" #include "ILibWebServer.h" #include "MediaServer_MicroStack.h" #include "ILibParsers.h" #include "MediaServerAbstraction.h" #include "CdsDidlSerializer.h" #include "CdsErrors.h" #include "CdsStrings.h" #include "FileIoAbstraction.h" #ifdef WIN32 #ifndef UNDER_CE #include "assert.h" #include <crtdbg.h> #endif #endif #ifdef _POSIX #include "assert.h" #include <semaphore.h> #define strnicmp strncasecmp #endif #ifndef _WIN32_WCE #define ASSERT(x) #endif struct MSA_InternalState { /* * Lock for thread-safety. */ sem_t Lock; /* * SystemUpdateID value of the media server. */ unsigned int SystemUpdateID; /* * Linked list of container update IDs to print. */ struct MSA_ContainerUpdate *ContainerUpdateID; /* * Moderation flag for eventing. */ unsigned short ModerationFlag; /* * Supported abilities for sorting browse/search results. * SortCapabilitiesString: concatenation of strings in MSA_CONFIG_SORT_CAPABILITIES */ char *SortCapabilitiesString; /* * Supported abilities for searching results. * SearchCapabilitiesString: concatenation of strings in MSA_CONFIG_SEARCH_CAPABILITIES */ char *SearchCapabilitiesString; /* * Contains the list of IP addresses for the media server. */ int *IpAddrList; int IpAddrListLen; /* * The list of protocolInfo for this device as a source. */ char *SourceProtocolInfo; /* * The list of protocolInfo for this device as a sink. */ char *SinkProtocolInfo; /* * Miscellaneous object that is provided in MSA_CreateMediaServer. */ void *UserObject; /* * Statistic Information. */ struct MSA_Stats *Statistics; }; struct MSA_ContainerUpdate { char *ContainerID; unsigned int UpdateID; struct MSA_ContainerUpdate *Next; }; /* Internal Structure for calling methods through the thread pool. */ #ifdef WIN32 typedef unsigned __int64 METHOD_PARAM; #else typedef void *METHOD_PARAM; #endif typedef struct _contextSwitchCall { MSA MSA_Object; void* UPnPSession; MSA_ActionHandlerContextSwitchId ActionId; int ParameterCount; METHOD_PARAM Parameters[16]; } *ContextSwitchCall; MSA_Error _ExecuteCallbackThroughThreadPool(MSA msa_obj, ContextSwitchCall context_switch); int _AddMethodParameter(ContextSwitchCall context_switch, METHOD_PARAM parameter) { if(context_switch->ParameterCount == 16) { return -1; } context_switch->Parameters[context_switch->ParameterCount++] = parameter; return 0; } ContextSwitchCall _CreateMethod(MSA_ActionHandlerContextSwitchId action_id, MSA msa_obj, void* upnp_session) { ContextSwitchCall result = malloc(sizeof(struct _contextSwitchCall)); memset(result, 0, sizeof(struct _contextSwitchCall)); if(result != NULL) { result->UPnPSession = upnp_session; result->ActionId = action_id; result->MSA_Object = msa_obj; } return result; } /* * This method release the resources occupied * msaObj : The object returned from CreateMediaServer */ void MSA_DestroyMediaServer(void *msa_obj) { MSA msa = (MSA) msa_obj; struct MSA_ContainerUpdate *cu, *nextCu; struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa->InternalState; /* properly deallocate the objects for the container UpdateIDs */ sem_wait(&(state->Lock)); msa->ThreadPool = NULL; if(state->Statistics != NULL) { free(state->Statistics); } cu = state->ContainerUpdateID; while (cu != NULL) { nextCu = cu->Next; free(cu); cu = nextCu; } msa->OnStats = NULL; msa->OnBrowse = NULL; msa->OnSearch = NULL; msa->OnGetSystemUpdateID = NULL; msa->OnGetSearchCapabilities = NULL; msa->OnGetSortCapabilities = NULL; msa->OnGetProtocolInfo = NULL; msa->OnGetCurrentConnectionIDs = NULL; msa->OnGetCurrentConnectionInfo = NULL; #if defined(INCLUDE_FEATURE_UPLOAD) msa->OnCreateObject = NULL; msa->OnDestroyObject = NULL; #endif free(state->SinkProtocolInfo); free(state->SourceProtocolInfo); free(state->SearchCapabilitiesString); free(state->SortCapabilitiesString); free(state->IpAddrList); cu = state->ContainerUpdateID; while (cu != NULL) { nextCu = cu->Next; free(cu); cu = nextCu; } sem_post(&(state->Lock)); sem_destroy(&(state->Lock)); free(state); msa->InternalState = NULL; } void _MSA_Helper_PopulateIpInfo(MSA_State msa_state, void* upnp_session, struct MSA_CdsQuery *cdsQuery) { int size, i, swapValue; struct MSA_InternalState* state = (struct MSA_InternalState*) msa_state; /* * Obtain the IP address and port that received this request */ cdsQuery->RequestedOnAddress = MediaServer_GetLocalInterfaceToHost(upnp_session); cdsQuery->RequestedOnPort = MediaServer_GetLocalPortNumber(upnp_session); /* * Obtain the list of active IP addresses for this machine. * Microstack allows us to assume that the port number * will be the same for all IP addresses. */ sem_wait(&(state->Lock)); cdsQuery->IpAddrListLen = state->IpAddrListLen; size = (int) (sizeof(int) * cdsQuery->IpAddrListLen); cdsQuery->IpAddrList = (int*) malloc(size); memcpy(cdsQuery->IpAddrList, state->IpAddrList, size); sem_post(&(state->Lock)); /* * Reorder the list of active IP addresses so that the * IP address for the interface that received the request * is listed first. */ if (cdsQuery->IpAddrList[0] != cdsQuery->RequestedOnAddress) { swapValue = cdsQuery->IpAddrList[0]; cdsQuery->IpAddrList[0] = cdsQuery->RequestedOnAddress; for (i=1; i < cdsQuery->IpAddrListLen; i++) { if (cdsQuery->IpAddrList[i] == cdsQuery->RequestedOnAddress) { cdsQuery->IpAddrList[i] = swapValue; break; } } } } /* number of bytes needed to represent a 32bit unsigned int as a string with a comma. */ #define MSA_MAX_BYTESIZE_UINT 13 void MSA_Helper_UpdateImmediate_ContainerUpdateID(MSA msa_obj) { int size; struct MSA_ContainerUpdate *cu, *nextCu; char *sv, *var; int writecomma; struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa_obj->InternalState; /* don't bother updating if there's nothing to report */ if (state->ContainerUpdateID == NULL) return; size = 0; /* calculate size needed for state variable value */ cu = state->ContainerUpdateID; while (cu != NULL) { size += (int) (MSA_MAX_BYTESIZE_UINT + strlen(cu->ContainerID)); cu = cu->Next; } size++; /* * Acquire the value of the state variable by writing it to 'var. * * We progressively write 'var' by writing to 'sv'. The format * of the state variable is a comma-delimited list of * containerID/UpdateID pairs... of course, the spec authors * also made the delimiter between ContainerID and UpdateID * into a comma... how silly. */ cu = state->ContainerUpdateID; var = sv = (char*) malloc(size); writecomma = 0; while (cu != NULL) { nextCu = cu->Next; if (writecomma != 0) { sv += sprintf(sv, ","); } sv += sprintf(sv, "%s,%u", cu->ContainerID, cu->UpdateID); writecomma = 1; free(cu->ContainerID); free(cu); cu = nextCu; } /* clear the ContainerUpdateID list as everything as been evented */ state->ContainerUpdateID = NULL; ASSERT(sv <= var+size); #ifdef _DEBUG printf("UPnP ContainerUpdateID Event Fired: %s\r\n", var); #endif MediaServer_SetState_ContentDirectory_ContainerUpdateIDs(msa_obj->DeviceMicroStack, var); free(var); } void MSA_Helper_ModerationSink_ContainerUpdateID(MSA msa_obj) { struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa_obj->InternalState; #ifdef _DEBUG printf("MSA_Helper_ModerationSink_ContainerUpdateID()\r\n"); #endif sem_wait(&(state->Lock)); MSA_Helper_UpdateImmediate_ContainerUpdateID(msa_obj); state->ModerationFlag = 0; sem_post(&(state->Lock)); } /* * Assumes caller has locked msa->Lock. */ void MSA_Helper_UpdateModerated_ContainerUpdateID(MSA msa_obj) { /* don't bother updating if there's nothing to report */ struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa_obj->InternalState; if (state->ContainerUpdateID == NULL) return; if (state->ModerationFlag == 0) { state->ModerationFlag = 1; ILibLifeTime_Add(msa_obj->LifeTimeMonitor,(void*)msa_obj,1,(void*)MSA_Helper_ModerationSink_ContainerUpdateID, NULL); } } /* END SECTION - helper functions */ /************************************************************************************/ /************************************************************************************/ /* START SECTION - Dispatch sinks generated in original main.c */ /* entry point from generated code */ void MediaServer_ContentDirectory_Browse(void* upnptoken,char* ObjectID,char* BrowseFlag,char* Filter,unsigned int StartingIndex,unsigned int RequestedCount,char* SortCriteria) { struct MSA_CdsQuery *browseArgs; int errorCode; const char *errorMsg; enum MSA_Enum_QueryTypes browseChildren = 0; ContextSwitchCall method = NULL; struct MSA_InternalState* state; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_Browse() - ID %s;\r\n", ObjectID); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_Browse++; msa->OnStats(msa, state->Statistics); } #endif /* * Validate arguments. */ errorCode = 0; errorMsg = NULL; if (strcmpi(BrowseFlag, CDS_STRING_BROWSE_DIRECT_CHILDREN) == 0) { browseChildren = MSA_Query_BrowseDirectChildren; } else if (strcmpi(BrowseFlag, CDS_STRING_BROWSE_METADATA) == 0) { browseChildren = MSA_Query_BrowseMetadata; } else { fprintf(stderr, "WARNING: MediaServer_ContentDirectory_Browse(): Possible error with generated microstack. Encountered BrowseFlag='%s'\r\n", BrowseFlag); errorCode = CDS_EC_INVALID_BROWSEFLAG; errorMsg = CDS_EM_INVALID_BROWSEFLAG; } if ((errorCode != 0) || (errorMsg != NULL)) { /* ensure that the error code and message map to something */ if (errorCode == 0) { errorCode = CDS_EC_INTERNAL_ERROR; } if (errorMsg == NULL) { errorMsg = CDS_EM_INTERNAL_ERROR; } MediaServer_Response_Error(upnptoken, errorCode, errorMsg); } else { /* deserialize request */ /* * Input arguments valid at UPnP layer. * Create an MSA_CdsQuery object and execute * the browse callback so that application can return results. */ browseArgs = (struct MSA_CdsQuery*) malloc (sizeof(struct MSA_CdsQuery)); memset(browseArgs, 0, sizeof(struct MSA_CdsQuery)); browseArgs->QueryType = browseChildren; browseArgs->Filter = ILibString_Copy(Filter, -1); browseArgs->ObjectID = ILibString_Copy(ObjectID, -1); /* Be sure to unescape it first. */ ILibInPlaceXmlUnEscape(browseArgs->ObjectID); browseArgs->RequestedCount = RequestedCount; browseArgs->SortCriteria = ILibString_Copy(SortCriteria, -1); browseArgs->StartingIndex = StartingIndex; browseArgs->IpAddrList = NULL; _MSA_Helper_PopulateIpInfo(msa->InternalState, upnptoken, browseArgs); method = _CreateMethod(MSA_CDS_BROWSE, msa, upnptoken); _AddMethodParameter(method, (METHOD_PARAM) browseArgs); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } } void MediaServer_ContentDirectory_Search(void* upnptoken,char* ContainerID,char* SearchCriteria, char* Filter,unsigned int StartingIndex,unsigned int RequestedCount,char* SortCriteria) { struct MSA_CdsQuery *searchArgs; ContextSwitchCall method = NULL; struct MSA_InternalState* state; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_Search();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_Search++; msa->OnStats(msa, state->Statistics); } #endif /* * Validate arguments. */ /* * Input arguments valid at UPnP layer. * Create an MSA_CdsQuery object and execute * the browse callback so that application can return results. */ searchArgs = (struct MSA_CdsQuery*) malloc (sizeof(struct MSA_CdsQuery)); memset(searchArgs, 0, sizeof(struct MSA_CdsQuery)); searchArgs->QueryType = MSA_Query_Search; searchArgs->Filter = ILibString_Copy(Filter, -1); searchArgs->ObjectID = ILibString_Copy(ContainerID, -1); /* Be sure to unescape it first. */ ILibInPlaceXmlUnEscape(searchArgs->ObjectID); searchArgs->SearchCriteria = ILibString_Copy(SearchCriteria, -1); searchArgs->RequestedCount = RequestedCount; searchArgs->SortCriteria = ILibString_Copy(SortCriteria, -1); searchArgs->StartingIndex = StartingIndex; searchArgs->IpAddrList = NULL; _MSA_Helper_PopulateIpInfo(msa->InternalState, upnptoken, searchArgs); method = _CreateMethod(MSA_CDS_SEARCH, msa, upnptoken); _AddMethodParameter(method, (METHOD_PARAM) searchArgs); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ContentDirectory_GetSystemUpdateID(void* upnptoken) { /* * Reports the known SystemUpdateID. * The SystemUpdateID is changed through MSA_IncrementSystemUpdateID(). */ struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_GetSystemUpdateID();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetSystemUpdateID++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CDS_GETSYSTEMUPDATEID, msa, upnptoken); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ContentDirectory_GetSearchCapabilities(void* upnptoken) { /* * Reports the statically defined search capabilities of the MediaServer. * You can customize this value to the abilities of the backend database * by changing MSA_CONFIG_SEARCH_CAPABILITIES_xxx variables. */ struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_GetSearchCapabilities();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetSearchCapabilities++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CDS_GETSEARCHCAPABILITIES, msa, upnptoken); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ContentDirectory_GetSortCapabilities(void* upnptoken) { /* * Reports the statically defined sort capabilities of the MediaServer. * You can customize this value to the abilities of the backend database * by changing MSA_CONFIG_SORT_CAPABILITIES_xxx variables. */ struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_GetSortCapabilities();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetSortCapabilities++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CDS_GETSORTCAPABILITIES, msa, upnptoken); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ConnectionManager_GetProtocolInfo(void* upnptoken) { struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ConnectionManager_GetProtocolInfo();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetProtocolInfo++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CMS_GETPROTOCOLINFO, msa, upnptoken); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ConnectionManager_GetCurrentConnectionIDs(void* upnptoken) { /* * HTTP connections are stateless, from the perspective of UPnP AV. * This is largely because we can't really monitor connection lifetime * of HTTP traffic in the UPnP AV sense, without risking memory leaks. * * TODO: Low priority - Add support for connection-lifetime aware protocols. */ struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ConnectionManager_GetCurrentConnectionIDs();\r\n"); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetCurrentConnectionIDs++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CMS_GETCURRENTCONNECTIONIDS, msa, upnptoken); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } void MediaServer_ConnectionManager_GetCurrentConnectionInfo(void* upnptoken,int ConnectionID) { /* * HTTP connections are stateless, from the perspective of UPnP AV. * This is largely because we can't really monitor connection lifetime * of HTTP traffic in the UPnP AV sense, without risking memory leaks. * * TODO: Low priority - Add support for connection-lifetime aware protocols. */ struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ConnectionManager_GetCurrentConnectionInfo(%u);\r\n",ConnectionID); if (msa->OnStats != NULL && state!=NULL) { state->Statistics->Count_GetCurrentConnectionInfo++; msa->OnStats(msa, state->Statistics); } #endif method = _CreateMethod(MSA_CMS_GETCURRENTCONNECTIONINFO, msa, upnptoken); _AddMethodParameter(method, (METHOD_PARAM) ConnectionID); if(_ExecuteCallbackThroughThreadPool(msa, method) != MSA_ERROR_NONE) { MediaServer_Response_Error(upnptoken, CDS_EC_INTERNAL_ERROR, CDS_EM_INTERNAL_ERROR); } } /* END SECTION - Dispatch sinks generated in original main.c */ /************************************************************************************/ /************************************************************************************/ /* START SECTION - public methods*/ /*****************************************************************************/ /* UPLOAD CAPABILITY */ /*****************************************************************************/ #if defined(INCLUDE_FEATURE_UPLOAD) void _MSA_Helper_PopulateIpInfoEx(MSA_State msa_state, void* upnp_session, struct MSA_CdsCreateObj *create_obj_arg) { int size, i, swapValue; struct MSA_InternalState* state = (struct MSA_InternalState*) msa_state; /* * Obtain the IP address and port that received this request */ create_obj_arg->RequestedOnAddress = MediaServer_GetLocalInterfaceToHost(upnp_session); create_obj_arg->RequestedOnPort = MediaServer_GetLocalPortNumber(upnp_session); /* * Obtain the list of active IP addresses for this machine. * Microstack allows us to assume that the port number * will be the same for all IP addresses. */ sem_wait(&(state->Lock)); create_obj_arg->IpAddrListLen = state->IpAddrListLen; size = (int) (sizeof(int) * create_obj_arg->IpAddrListLen); create_obj_arg->IpAddrList = (int*) malloc(size); memcpy(create_obj_arg->IpAddrList, state->IpAddrList, size); sem_post(&(state->Lock)); /* * Reorder the list of active IP addresses so that the * IP address for the interface that received the request * is listed first. */ if (create_obj_arg->IpAddrList[0] != create_obj_arg->RequestedOnAddress) { swapValue = create_obj_arg->IpAddrList[0]; create_obj_arg->IpAddrList[0] = create_obj_arg->RequestedOnAddress; for (i=1; i < create_obj_arg->IpAddrListLen; i++) { if (create_obj_arg->IpAddrList[i] == create_obj_arg->RequestedOnAddress) { create_obj_arg->IpAddrList[i] = swapValue; break; } } } } void MediaServer_ContentDirectory_CreateObject(void* upnptoken, char* id, char* Elements) { struct MSA_CdsCreateObj *createObjArg; struct ILibXMLNode* nodeList; struct ILibXMLNode* node; struct ILibXMLAttribute *attribs; int resultLen; int parsePeerResult = 0; char *lastResultPos; int isItemFlag = 0; struct CdsObject *newObj; struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_CreateObject() - ID %s;\r\n", id); #endif if((id != NULL)&& (Elements != NULL)) { /* parse the didl Result into a CdsObject, */ newObj = NULL; resultLen = (int) strlen(Elements); lastResultPos = Elements + resultLen; nodeList = ILibParseXML(Elements, 0, resultLen); ILibXML_BuildNamespaceLookupTable(nodeList); parsePeerResult = ILibProcessXMLNodeList(nodeList); if (parsePeerResult != 0 || resultLen == 0) { MediaServer_Response_Error(upnptoken, 712, "Bad Metadata - Cannot parse DIDL-Lite."); ILibDestructXMLNodeList(nodeList); return; } else { node = nodeList; while (node != NULL) { if (node->StartTag != 0) { /*[DONOTREPARSE] null terminate string */ attribs = ILibGetXMLAttributes(node); node->Name[node->NameLength] = '\0'; newObj = NULL; if (strcmp(node->Name, CDS_TAG_CONTAINER) == 0) { newObj = CDS_DeserializeDidlToObjectEx(node, attribs, 0, Elements, lastResultPos, 1); if(newObj == NULL) { /* free attribute mappings */ ILibDestructXMLAttributeList(attribs); break; } } else if (strcmp(node->Name, CDS_TAG_ITEM) == 0) { newObj = CDS_DeserializeDidlToObjectEx(node, attribs, 1, Elements, lastResultPos, 1); if(newObj == NULL) { /* free attribute mappings */ ILibDestructXMLAttributeList(attribs); break; } isItemFlag = 1; } else if (strcmp(node->Name, CDS_TAG_DIDL) == 0) { /* this is didl-lite root node, go to first child */ node = node->Next; } else { /* this node is not supported, go to next sibling/peer */ if (node->Peer != NULL) { node = node->Peer; } else if(node->Parent!=NULL) { node = node->Parent->Peer; } else { node = NULL; } } /* free attribute mappings */ ILibDestructXMLAttributeList(attribs); if(newObj != NULL) { break; } } else { node = node->Next; } } } if(newObj != NULL) { createObjArg = (struct MSA_CdsCreateObj*) malloc (sizeof(struct MSA_CdsCreateObj)); memset(createObjArg, 0, sizeof(struct MSA_CdsCreateObj)); createObjArg->UserObject = NULL; createObjArg->IpAddrList = NULL; _MSA_Helper_PopulateIpInfoEx(msa->InternalState, upnptoken, createObjArg); method = _CreateMethod(MSA_CDS_CREATEOBJECT, msa, upnptoken); _AddMethodParameter(method, (METHOD_PARAM) createObjArg); _AddMethodParameter(method, (METHOD_PARAM) newObj); _ExecuteCallbackThroughThreadPool(msa, method); } else { MediaServer_Response_Error(upnptoken, 712, "Bad Metadata - Cannot parse DIDL-Lite."); } /* free resources from XML parsing */ ILibDestructXMLNodeList(nodeList); } else { MediaServer_Response_Error(upnptoken, 402, "Missing value for the 'Elements' argument in the CreateObject"); } } void MediaServer_ContentDirectory_DestroyObject(void* upnptoken, char* ObjectID) { struct MSA_CdsDestroyObj *destroyObjArg; struct MSA_InternalState* state; ContextSwitchCall method = NULL; MSA msa = (MSA) MediaServer_GetTag(((struct ILibWebServer_Session*)upnptoken)->User); state = (struct MSA_InternalState*) msa->InternalState; #ifdef _DEBUG printf("UPnP Invoke: MediaServer_ContentDirectory_DestroyObject() - ID %s;\r\n", ObjectID); #endif if(ObjectID == NULL || strlen(ObjectID) == 0) { MediaServer_Response_Error(upnptoken, 402, "Missing value for the 'ObjectID' argument in the DestroyObject"); return; } destroyObjArg = (struct MSA_CdsDestroyObj*) malloc (sizeof(struct MSA_CdsDestroyObj)); memset(destroyObjArg, 0, sizeof(struct MSA_CdsDestroyObj)); destroyObjArg->ObjectID = ILibString_Copy(ObjectID, -1); destroyObjArg->UserObject = NULL; method = _CreateMethod(MSA_CDS_DESTROYOBJECT, msa, upnptoken); _AddMethodParameter(method, (METHOD_PARAM) destroyObjArg); _ExecuteCallbackThroughThreadPool(msa, method); } int MSA_ForCreateObjectResponse_Accept(MSA msa_obj, void* upnp_session, struct MSA_CdsCreateObj* create_obj_arg, struct CdsObject* cds_obj) { char *didl; int didlLen; unsigned int filter = 0; /* ToDo: check if uploadFileName is set to NULL, if so, the Application has rejected the upload */ /* * Get the XML form and send it. */ #ifndef METADATA_IS_XML_ESCAPED /* * TODO: Optimize by defining METADATA_IS_XML_ESCAPED * and implementing a metadata source that writes * XML-escaped data. */ #define METADATA_IS_XML_ESCAPED 0 #endif /* we want to print all Res elements and DLNA-specific attributes */ filter |= CdsFilter_ResAllAttribs; filter |= CdsFilter_DlnaContainerType; filter |= CdsFilter_DlnaManaged; /* convert CDS object to DIDL-Lite */ didl = CDS_SerializeObjectToDidl(cds_obj, METADATA_IS_XML_ESCAPED, filter, 1, &didlLen); if(strlen(didl) == 0) { /* * print an error message if we couldn't get the DIDL. */ fprintf(stderr, " failed to serialize object %s. Reason=%d.\r\n", cds_obj->ID, didlLen); /* * an error occurred during the response */ MediaServer_Response_Error(upnp_session, 712, "Error - Deserializing response to DIDL-Lite format."); } else { MediaServer_AsyncResponse_START(upnp_session, CDS_STRING_CREATE_OBJECT, CDS_STRING_URN_CDS); MediaServer_AsyncResponse_OUT(upnp_session, "ObjectID", cds_obj->ID, (int)strlen(cds_obj->ID), ILibAsyncSocket_MemoryOwnership_USER, 1, 1); MediaServer_AsyncResponse_OUT(upnp_session, "Result", didl, (int)strlen(didl), ILibAsyncSocket_MemoryOwnership_USER, 1, 1); MediaServer_AsyncResponse_DONE(upnp_session, CDS_STRING_CREATE_OBJECT); } /* Free resources */ ILibWebServer_Release(upnp_session); free(didl); free(create_obj_arg->IpAddrList); free(create_obj_arg); return 0; } int MSA_ForCreateObjectResponse_AcceptUpload(MSA msa_obj, void* upnp_session, struct MSA_CdsCreateObj* create_obj_arg, struct CdsObject* cds_obj) { char *didl; int didlLen; unsigned int filter = 0; /* ToDo: check if uploadFileName is set to NULL, if so, the Application has rejected the upload */ /* * Get the XML form and send it. */ #ifndef METADATA_IS_XML_ESCAPED /* * TODO: Optimize by defining METADATA_IS_XML_ESCAPED * and implementing a metadata source that writes * XML-escaped data. */ #define METADATA_IS_XML_ESCAPED 0 #endif /* we want to print all Res elements and DLNA-specific attributes */ filter |= CdsFilter_ResAllAttribs; filter |= CdsFilter_DlnaContainerType; filter |= CdsFilter_DlnaManaged; /* convert CDS object to DIDL-Lite */ didl = CDS_SerializeObjectToDidl(cds_obj, METADATA_IS_XML_ESCAPED, filter, 1, &didlLen); if(strlen(didl) == 0) { /* * print an error message if we couldn't get the DIDL. */ fprintf(stderr, " failed to serialize object %s. Reason=%d.\r\n", cds_obj->ID, didlLen); /* * an error occurred during the response */ MediaServer_Response_Error(upnp_session, 712, "Error - Deserializing response to DIDL-Lite format."); } else { MediaServer_AsyncResponse_START(upnp_session, CDS_STRING_CREATE_OBJECT, CDS_STRING_URN_CDS); MediaServer_AsyncResponse_OUT(upnp_session, "ObjectID", cds_obj->ID, (int)strlen(cds_obj->ID), ILibAsyncSocket_MemoryOwnership_USER, 1, 1); MediaServer_AsyncResponse_OUT(upnp_session, "Result", didl, (int)strlen(didl), ILibAsyncSocket_MemoryOwnership_USER, 1, 1); MediaServer_AsyncResponse_DONE(upnp_session, CDS_STRING_CREATE_OBJECT); } /* Free resources */ ILibWebServer_Release(upnp_session); free(didl); free(create_obj_arg->IpAddrList); free(create_obj_arg); return 0; } int MSA_ForCreateObjectResponse_Reject(MSA msa_obj, void* upnp_session, struct MSA_CdsCreateObj* create_obj_arg, struct CdsObject* cds_obj, int error_code, char* error_msg) { /* * an error occurred during the response */ MediaServer_Response_Error(upnp_session, error_code, error_msg); /* Free resources */ ILibWebServer_Release(upnp_session); free(create_obj_arg->IpAddrList); free(create_obj_arg); return 0; } #endif /* see header file */ MSA MSA_CreateMediaServer(void* chain, MediaServer_MicroStackToken upnp_stack, void* lifetime_monitor, unsigned int system_update_id, const char* sink_protocol_info, const char* source_protocol_info, const char* sortable_fields, const char* searchable_fields, ILibThreadPool thread_pool, void* msa_user_obj) { MSA msa = NULL; struct MSA_InternalState* internalState = NULL; /* Allocate the MSA and internal state structures */ msa = (MSA) malloc(sizeof(struct MSA_Instance)); if(msa == NULL) { return NULL; } memset(msa, 0, sizeof(struct MSA_Instance)); internalState = (struct MSA_InternalState* )malloc(sizeof(struct MSA_InternalState)); if(internalState == NULL) { return NULL; } memset(internalState, 0, sizeof(struct MSA_InternalState)); internalState->Statistics = (struct MSA_Stats*) malloc(sizeof(struct MSA_Stats)); memset(internalState->Statistics, 0, sizeof(struct MSA_Stats*)); internalState->UserObject = msa_user_obj; sem_init(&(internalState->Lock), 0, 1); MediaServer_SetState_ContentDirectory_SystemUpdateID(upnp_stack, internalState->SystemUpdateID); MediaServer_SetState_ContentDirectory_ContainerUpdateIDs(upnp_stack, ""); /* set initial source_protocol_info */ internalState->SourceProtocolInfo = (char*) malloc(strlen(source_protocol_info) + 1); strcpy(internalState->SourceProtocolInfo, source_protocol_info); MediaServer_SetState_ConnectionManager_SourceProtocolInfo(upnp_stack, internalState->SourceProtocolInfo); /* set initial sink_protocol_info */ internalState->SinkProtocolInfo = (char*) malloc(strlen(sink_protocol_info) + 1); strcpy(internalState->SinkProtocolInfo, sink_protocol_info); MediaServer_SetState_ConnectionManager_SinkProtocolInfo(upnp_stack,internalState->SinkProtocolInfo); /* no connections */ MediaServer_SetState_ConnectionManager_CurrentConnectionIDs(upnp_stack, ""); /* set sort capabilities */ internalState->SortCapabilitiesString = (char*) malloc(strlen(sortable_fields) + 1); strcpy(internalState->SortCapabilitiesString, sortable_fields); /* set search cabilities */ internalState->SearchCapabilitiesString = (char*) malloc(strlen(searchable_fields) + 1); strcpy(internalState->SearchCapabilitiesString, searchable_fields); msa->DeviceMicroStack = upnp_stack; msa->InternalState = internalState; msa->ThreadPool = thread_pool; msa->LifeTimeMonitor = lifetime_monitor; msa->Destroy = MSA_DestroyMediaServer; MediaServer_SetTag(upnp_stack, (void*)msa); ILibAddToChain(chain, msa); // // Initialize All the Handlers: // // // Connection Manager // MediaServer_FP_ConnectionManager_GetCurrentConnectionIDs = (MediaServer__ActionHandler_ConnectionManager_GetCurrentConnectionIDs)&MediaServer_ConnectionManager_GetCurrentConnectionIDs; MediaServer_FP_ConnectionManager_GetCurrentConnectionInfo = (MediaServer__ActionHandler_ConnectionManager_GetCurrentConnectionInfo)&MediaServer_ConnectionManager_GetCurrentConnectionInfo; MediaServer_FP_ConnectionManager_GetProtocolInfo = (MediaServer__ActionHandler_ConnectionManager_GetProtocolInfo)&MediaServer_ConnectionManager_GetProtocolInfo; // // Content Directory // MediaServer_FP_ContentDirectory_Browse = (MediaServer__ActionHandler_ContentDirectory_Browse)&MediaServer_ContentDirectory_Browse; MediaServer_FP_ContentDirectory_GetSearchCapabilities = (MediaServer__ActionHandler_ContentDirectory_GetSearchCapabilities)&MediaServer_ContentDirectory_GetSearchCapabilities; MediaServer_FP_ContentDirectory_GetSortCapabilities = (MediaServer__ActionHandler_ContentDirectory_GetSortCapabilities)&MediaServer_ContentDirectory_GetSortCapabilities; MediaServer_FP_ContentDirectory_GetSystemUpdateID = (MediaServer__ActionHandler_ContentDirectory_GetSystemUpdateID)&MediaServer_ContentDirectory_GetSystemUpdateID; MediaServer_FP_ContentDirectory_Search = (MediaServer__ActionHandler_ContentDirectory_Search)&MediaServer_ContentDirectory_Search; #if defined(INCLUDE_FEATURE_UPLOAD) MediaServer_FP_ContentDirectory_CreateObject = (MediaServer__ActionHandler_ContentDirectory_CreateObject)&MediaServer_ContentDirectory_CreateObject; MediaServer_FP_ContentDirectory_DestroyObject = (MediaServer__ActionHandler_ContentDirectory_DestroyObject)&MediaServer_ContentDirectory_DestroyObject; #else MediaServer_GetConfiguration()->ContentDirectory->CreateObject = NULL; MediaServer_GetConfiguration()->ContentDirectory->DestroyObject = NULL; #endif return msa; } /* see header file */ void MSA_DeallocateCdsQuery(struct MSA_CdsQuery *cdsQuery) { if (cdsQuery->Filter != NULL) free (cdsQuery->Filter); if (cdsQuery->ObjectID != NULL) free (cdsQuery->ObjectID); if (cdsQuery->SortCriteria != NULL) free (cdsQuery->SortCriteria); if (cdsQuery->SearchCriteria != NULL) free (cdsQuery->SearchCriteria); if (cdsQuery->IpAddrList != NULL) free (cdsQuery->IpAddrList); free (cdsQuery); } /* see header file */ void MSA_ForResponse_RespondError(MSA msa_obj, void* upnp_session, int error_code, const char* error_msg) { if(upnp_session == NULL) return; MediaServer_Response_Error(upnp_session, error_code, error_msg); ILibWebServer_Release(upnp_session); } /* see header file */ int MSA_ForQueryResponse_Start(MSA msa_obj, void* upnp_session, struct MSA_CdsQuery* cds_query, int send_didl_header_flag) { int status = 0; ASSERT(cds_query != NULL); /* don't bother sending data if the socket disconnected */ if (upnp_session == NULL) return -1; if (cds_query->QueryType == MSA_Query_Search) { status = MediaServer_AsyncResponse_START(upnp_session, CDS_STRING_SEARCH, CDS_STRING_URN_CDS); } else { status = MediaServer_AsyncResponse_START(upnp_session, CDS_STRING_BROWSE, CDS_STRING_URN_CDS); } if ((send_didl_header_flag != 0) && (status >= 0)) { unsigned int filter = CDS_ConvertCsvStringToBitString(cds_query->Filter); if(CDS_FilterContainsDlnaElements(filter)) { status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, CDS_DIDL_HEADER_ESCAPED, CDS_DIDL_HEADER_ESCAPED_LEN, ILibAsyncSocket_MemoryOwnership_STATIC, 1, 0); } else { status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, CDS_DIDL_HEADER_ESCAPED_NO_DLNA_NAMESPACES, CDS_DIDL_HEADER_ESCAPED_NO_DLNA_NAMESPACES_LEN, ILibAsyncSocket_MemoryOwnership_STATIC, 1, 0); } } else { status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, "", 0, ILibAsyncSocket_MemoryOwnership_STATIC, 1, 0); } return status; } /* see header file */ int MSA_ForQueryResponse_ResultArgumentRaw(MSA msa_obj, void* upnp_session, struct MSA_CdsQuery* cds_query, const char* xml_escaped_utf8_didl, int didl_size) { int status = 0; ASSERT(cds_query != NULL); /* don't bother sending data if the socket disconnected */ if (upnp_session == NULL) return -1; status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, xml_escaped_utf8_didl, didl_size, ILibAsyncSocket_MemoryOwnership_USER, 0, 0); return status; } /* see header file */ int MSA_ForQueryResponse_FinishResponse(MSA msa_obj, void* upnp_session, struct MSA_CdsQuery* cds_query, int send_did_footer_flag, unsigned int number_returned, unsigned int total_matches, unsigned int update_id) { char numResult[30]; int status = 0; ASSERT(cds_query != NULL); /* don't bother sending data if the socket disconnected */ if (upnp_session == NULL) return -1; if (send_did_footer_flag != 0) { status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, CDS_DIDL_FOOTER_ESCAPED, CDS_DIDL_FOOTER_ESCAPED_LEN, ILibAsyncSocket_MemoryOwnership_STATIC, 0, 1); } else { status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_RESULT, "", 0, ILibAsyncSocket_MemoryOwnership_STATIC, 0, 1); } if (status >= 0) { /* * Instruct the generated microstack to send the data for the last * three out-arguments of the Browse request. */ sprintf(numResult, "%u", number_returned); status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_NUMBER_RETURNED, numResult, (int) strlen(numResult), ILibAsyncSocket_MemoryOwnership_USER, 1,1); if (status >= 0) { sprintf(numResult, "%u", total_matches); status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_TOTAL_MATCHES, numResult, (int) strlen(numResult), ILibAsyncSocket_MemoryOwnership_USER, 1,1); if (status >= 0) { sprintf(numResult, "%u", update_id); status = MediaServer_AsyncResponse_OUT(upnp_session, CDS_STRING_UPDATE_ID, numResult, (int) strlen(numResult), ILibAsyncSocket_MemoryOwnership_USER, 1,1); if (status >= 0) { if (cds_query->QueryType == MSA_Query_Search) { status = MediaServer_AsyncResponse_DONE(upnp_session, CDS_STRING_SEARCH); } else { status = MediaServer_AsyncResponse_DONE(upnp_session, CDS_STRING_BROWSE); } } } } } /* we are not going to call any more MSA_ForQueryResponse_xxx methods for this UPnP response */ ILibWebServer_Release(upnp_session); return status; } void MSA_ForQueryResponse_Cancelled(MSA msa_obj, void* upnp_session, struct MSA_CdsQuery *cdsQuery) { ASSERT(cdsQuery != NULL); if (upnp_session == NULL) return; /* we are not going to call any more MSA_ForQueryResponse_xxx methods for this UPnP response */ ILibWebServer_Release(upnp_session); } /* see header file */ void MSA_IncrementSystemUpdateID(MSA msa_obj) { struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa_obj->InternalState; state->SystemUpdateID++; #ifdef _DEBUG printf("UPnP SystemUpdate Event Fired: %d\r\n", state->SystemUpdateID); #endif MediaServer_SetState_ContentDirectory_SystemUpdateID(msa_obj->DeviceMicroStack, state->SystemUpdateID); } /* see header file */ void MSA_UpdateContainerID(MSA msa_obj, const char *container_id, unsigned int container_update_id) { struct MSA_InternalState *state; struct MSA_ContainerUpdate *cu; struct MSA_ContainerUpdate *fcu; struct MSA_ContainerUpdate *lcu; if(msa_obj == NULL || container_id == NULL) return; state = (struct MSA_InternalState*) msa_obj->InternalState; if(state == NULL) return; /* lock state */ sem_wait(&(state->Lock)); /* * Attempt to find an existing ContainerUpdate * object for the specified containerID. */ cu = state->ContainerUpdateID; lcu = fcu = NULL; while ((cu != NULL) && (fcu == NULL)) { if (strcmp(cu->ContainerID, container_id) == 0) { fcu = cu; } lcu = cu; cu = cu->Next; } if (fcu == NULL) { /* * If fcu is NULL, then we need to add * a new MSA_ContainerUpdate to the object. */ if(lcu){ fcu = lcu->Next = (struct MSA_ContainerUpdate*) malloc(sizeof(struct MSA_ContainerUpdate)); } else{ fcu = state->ContainerUpdateID = (struct MSA_ContainerUpdate*) malloc(sizeof(struct MSA_ContainerUpdate)); } fcu->ContainerID = ILibString_Copy(container_id, -1); fcu->UpdateID = 0; fcu->Next = NULL; } ASSERT(fcu != NULL); if(container_update_id > 0) { /* * Assign a new UpdateID for the specified containerID. */ fcu->UpdateID = container_update_id; } /* Call MSA_Helper_UpdateModerated_ContainerUpdateID(msa_obj) if you need to switch to aggregate events at once */ MSA_Helper_UpdateImmediate_ContainerUpdateID(msa_obj); /* unlock */ sem_post(&(state->Lock)); } void MSA_UpdateIpInfo(MSA msa_obj, int *ip_addr_list, int ip_addr_list_len) { int size; struct MSA_InternalState *state; state = (struct MSA_InternalState*) msa_obj->InternalState; /* copy the ip addresses to the msa object */ sem_wait(&(state->Lock)); if (state->IpAddrList != NULL) { free(state->IpAddrList); } size = (int) (ip_addr_list_len * sizeof(int)); state->IpAddrList = (int*) malloc(size); memcpy(state->IpAddrList, ip_addr_list, size); state->IpAddrListLen = ip_addr_list_len; sem_post(&(state->Lock)); } unsigned int MSA_GetSystemUpdateID(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->SystemUpdateID; } return -1; } void MSA_SetSystemUpdateID(MSA msa_obj, unsigned int system_update_id) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; state->SystemUpdateID = system_update_id; /* set the UPnP state to send the event out to subscribed control points. */ MediaServer_SetState_ContentDirectory_SystemUpdateID(msa_obj->DeviceMicroStack, state->SystemUpdateID); } } void MSA_LockState(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; sem_wait(&(state->Lock)); } } void MSA_UnLockState(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; sem_post(&(state->Lock)); } } void* MSA_GetUserObject(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->UserObject; } return NULL; } void MSA_SetSourceProtocolInfo(MSA msa_obj, const char* source_protocol_info) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; if(state->SourceProtocolInfo != NULL) { free(state->SourceProtocolInfo); } state->SourceProtocolInfo = (char*) malloc(strlen(source_protocol_info) + 1); strcpy(state->SourceProtocolInfo, source_protocol_info); /* set the UPnP state to send the event out to subscribed control points. */ MediaServer_SetState_ConnectionManager_SourceProtocolInfo(msa_obj->DeviceMicroStack, state->SourceProtocolInfo); } } const char* MSA_GetSourceProtocolInfo(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->SourceProtocolInfo; } return NULL; } void MSA_SetSinkProtocolInfo(MSA msa_obj, const char* sink_protocol_info) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; if(state->SinkProtocolInfo != NULL) { free(state->SinkProtocolInfo); } state->SinkProtocolInfo = (char*) malloc(strlen(sink_protocol_info) + 1); strcpy(state->SinkProtocolInfo, sink_protocol_info); /* set the UPnP state to send the event out to subscribed control points. */ MediaServer_SetState_ConnectionManager_SourceProtocolInfo(msa_obj->DeviceMicroStack, state->SinkProtocolInfo); } } const char* MSA_GetSinkProtocolInfo(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->SinkProtocolInfo; } return NULL; } void MSA_SetSortableProperties(MSA msa_obj, const char* sortable_fields) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; if(state->SortCapabilitiesString != NULL) { free(state->SortCapabilitiesString); } state->SortCapabilitiesString = (char*) malloc(strlen(sortable_fields) + 1); strcpy(state->SortCapabilitiesString, sortable_fields); /* set the UPnP state to send the event out to subscribed control points. */ MediaServer_SetState_ConnectionManager_SourceProtocolInfo(msa_obj->DeviceMicroStack, state->SortCapabilitiesString); } } const char* MSA_GetSortableProperties(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->SortCapabilitiesString; } return NULL; } void MSA_SetSearchableProperties(MSA msa_obj, const char* searchable_fields) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; if(state->SearchCapabilitiesString != NULL) { free(state->SearchCapabilitiesString); } state->SearchCapabilitiesString = (char*) malloc(strlen(searchable_fields) + 1); strcpy(state->SearchCapabilitiesString, searchable_fields); /* set the UPnP state to send the event out to subscribed control points. */ MediaServer_SetState_ConnectionManager_SourceProtocolInfo(msa_obj->DeviceMicroStack, state->SearchCapabilitiesString); } } const char* MSA_GetSearchableProperties(MSA msa_obj) { struct MSA_InternalState *state; if(msa_obj!=NULL) { state = (struct MSA_InternalState*) msa_obj->InternalState; return state->SearchCapabilitiesString; } return NULL; } /** Generic respond methods for all supported UPnP action **/ void MSA_RespondBrowse(MSA msa_obj, void* upnp_session, const char* result, const unsigned int number_returned, const unsigned int total_matches, const unsigned int update_id) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_Browse(upnp_session, result, number_returned, total_matches, update_id); ILibWebServer_Release(upnp_session); } void MSA_RespondSearch(MSA msa_obj, void* upnp_session, const char* result, const unsigned int number_returned, const unsigned int total_matches, const unsigned int update_id) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_Search(upnp_session, result, number_returned, total_matches, update_id); ILibWebServer_Release(upnp_session); } void MSA_RespondGetSystemUpdateID(MSA msa_obj, void* upnp_session, const unsigned int id) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_GetSystemUpdateID(upnp_session, id); ILibWebServer_Release(upnp_session); } void MSA_RespondGetSearchCapabilities(MSA msa_obj, void* upnp_session, const char* search_caps) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_GetSearchCapabilities(upnp_session, search_caps); ILibWebServer_Release(upnp_session); } void MSA_RespondGetSortCapabilities(MSA msa_obj, void* upnp_session, const char* sort_caps) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_GetSortCapabilities(upnp_session, sort_caps); ILibWebServer_Release(upnp_session); } void MSA_RespondGetProtocolInfo(MSA msa_obj, void* upnp_session, const char* source, const char* sink) { if(upnp_session == NULL) return; MediaServer_Response_ConnectionManager_GetProtocolInfo(upnp_session, source, sink); ILibWebServer_Release(upnp_session); } void MSA_RespondGetCurrentConnectionIDs(MSA msa_obj, void* upnp_session, const char* connection_ids) { if(upnp_session == NULL) return; MediaServer_Response_ConnectionManager_GetCurrentConnectionIDs(upnp_session, connection_ids); ILibWebServer_Release(upnp_session); } void MSA_RespondGetCurrentConnectionInfo(MSA msa_obj, void* upnp_session, const int rcs_ic, const int av_transport_Id, const char* protocol_info, const char* peer_connection_manager, const int peer_connection_id, const char* direction, const char* status) { if(upnp_session == NULL) return; MediaServer_Response_ConnectionManager_GetCurrentConnectionInfo(upnp_session, rcs_ic, av_transport_Id, protocol_info, peer_connection_manager, peer_connection_id, direction, status); ILibWebServer_Release(upnp_session); } #if defined(INCLUDE_FEATURE_UPLOAD) void MSA_RespondCreateObject(MSA msa_obj, void* upnp_session, const char* object_id, const char* result) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_CreateObject(upnp_session, object_id, result); ILibWebServer_Release(upnp_session); } void MSA_RespondDestroyObject(MSA msa_obj, void* upnp_session) { if(upnp_session == NULL) return; MediaServer_Response_ContentDirectory_DestroyObject(upnp_session); ILibWebServer_Release(upnp_session); } #endif void _ExecuteCallback(ILibThreadPool threadPool, void* context_switch) { MSA msa = NULL; struct MSA_InternalState* internal_state = NULL; ContextSwitchCall contextSwitch = (ContextSwitchCall) context_switch; if(contextSwitch == NULL) { return; } msa = contextSwitch->MSA_Object; internal_state = (struct MSA_InternalState*) msa->InternalState; switch(contextSwitch->ActionId) { case MSA_CDS_BROWSE: { if(msa->OnBrowse != NULL && contextSwitch->ParameterCount == 1) { struct MSA_CdsQuery* query = (struct MSA_CdsQuery*) contextSwitch->Parameters[0]; msa->OnBrowse(msa, contextSwitch->UPnPSession, query); } else if(msa->OnBrowse == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CDS_SEARCH: { if(msa->OnBrowse != NULL && contextSwitch->ParameterCount == 1) { struct MSA_CdsQuery* query = (struct MSA_CdsQuery*) contextSwitch->Parameters[0]; msa->OnBrowse(msa, contextSwitch->UPnPSession, query); } else if(msa->OnBrowse == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CDS_GETSYSTEMUPDATEID: { if(msa->OnGetSystemUpdateID != NULL && contextSwitch->ParameterCount == 0) { msa->OnGetSystemUpdateID(msa, contextSwitch->UPnPSession); } else if(msa->OnGetSystemUpdateID == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CDS_GETSEARCHCAPABILITIES: { if(msa->OnGetSearchCapabilities != NULL && contextSwitch->ParameterCount == 0) { msa->OnGetSearchCapabilities(msa, contextSwitch->UPnPSession); } else if(msa->OnGetSearchCapabilities == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CDS_GETSORTCAPABILITIES: { if(msa->OnGetSortCapabilities != NULL && contextSwitch->ParameterCount == 0) { msa->OnGetSortCapabilities(msa, contextSwitch->UPnPSession); } else if(msa->OnGetSortCapabilities == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CMS_GETPROTOCOLINFO: { if(msa->OnGetProtocolInfo != NULL && contextSwitch->ParameterCount == 0) { msa->OnGetProtocolInfo(msa, contextSwitch->UPnPSession); } else if(msa->OnGetProtocolInfo == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CMS_GETCURRENTCONNECTIONIDS: { if(msa->OnGetCurrentConnectionIDs != NULL && contextSwitch->ParameterCount == 0) { msa->OnGetCurrentConnectionIDs(msa, contextSwitch->UPnPSession); } else if(msa->OnGetCurrentConnectionIDs == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CMS_GETCURRENTCONNECTIONINFO: { if(msa->OnGetCurrentConnectionInfo != NULL && contextSwitch->ParameterCount == 1) { msa->OnGetCurrentConnectionInfo(msa, contextSwitch->UPnPSession, (int) contextSwitch->Parameters[0]); } else if(msa->OnGetCurrentConnectionInfo == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; #if defined(INCLUDE_FEATURE_UPLOAD) case MSA_CDS_CREATEOBJECT: { if(msa->OnCreateObject != NULL && contextSwitch->ParameterCount == 2) { struct MSA_CdsCreateObj* createObjArg = (struct MSA_CdsCreateObj*) contextSwitch->Parameters[0]; struct CdsObject* newObj = (struct CdsObject*) contextSwitch->Parameters[1]; msa->OnCreateObject(msa, contextSwitch->UPnPSession, createObjArg, newObj); } else if(msa->OnCreateObject == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; case MSA_CDS_DESTROYOBJECT: { if(msa->OnDestroyObject != NULL && contextSwitch->ParameterCount == 1) { struct MSA_CdsDestroyObj* destroyObjArg = (struct MSA_CdsDestroyObj*) contextSwitch->Parameters[0]; msa->OnDestroyObject(msa, contextSwitch->UPnPSession, destroyObjArg); } else if(msa->OnDestroyObject == NULL) { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Action Not Implemented"); } else { MSA_ForResponse_RespondError(msa, contextSwitch->UPnPSession, 501, "Action Failed: Program Error"); } } break; #endif default: return; } free(contextSwitch); } MSA_Error _ExecuteCallbackThroughThreadPool(MSA msa_obj, ContextSwitchCall context_switch) { if(msa_obj == NULL) { return MSA_ERROR_INTERNALERROR; } /* add ref to UPnP Session, because the callback could be executing on a different thread */ ILibWebServer_AddRef(context_switch->UPnPSession); if(msa_obj->ContextSwitchBitMask & context_switch->ActionId) { /* bit mask indicates that this action handler will be called using context switch through ThreadPool */ ILibThreadPool_QueueUserWorkItem(msa_obj->ThreadPool, (void*)context_switch, &_ExecuteCallback); } else { /* no context switch, just execute the callback using the same thread */ _ExecuteCallback(NULL, (void*)context_switch); } return MSA_ERROR_NONE; } /* END SECTION - public methods */ /************************************************************************************/
30.656087
308
0.729282
[ "object" ]
37c7efcaf891a342b1c3896e44020c2db4d5ce39
9,585
h
C
kernel/include/los_mux.h
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
kernel/include/los_mux.h
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
null
null
null
kernel/include/los_mux.h
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the 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 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. */ /** * @defgroup los_mux Mutex * @ingroup kernel */ #ifndef _LOS_MUX_H #define _LOS_MUX_H #include "los_base.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif /* __cplusplus */ #endif /* __cplusplus */ enum { LOS_MUX_PRIO_NONE = 0, LOS_MUX_PRIO_INHERIT = 1, LOS_MUX_PRIO_PROTECT = 2 }; enum { LOS_MUX_NORMAL = 0, LOS_MUX_RECURSIVE = 1, LOS_MUX_ERRORCHECK = 2, LOS_MUX_DEFAULT = LOS_MUX_RECURSIVE }; typedef struct { UINT8 protocol; UINT8 prioceiling; UINT8 type; UINT8 reserved; } LosMuxAttr; /** * @ingroup los_mux * Mutex object. */ typedef struct OsMux { UINT32 magic; /**< magic number */ LosMuxAttr attr; /**< Mutex attribute */ LOS_DL_LIST holdList; /**< The task holding the lock change */ LOS_DL_LIST muxList; /**< Mutex linked list */ VOID *owner; /**< The current thread that is locking a mutex */ UINT16 muxCount; /**< Times of locking a mutex */ } LosMux; extern UINT32 LOS_MuxAttrInit(LosMuxAttr *attr); extern UINT32 LOS_MuxAttrDestroy(LosMuxAttr *attr); extern UINT32 LOS_MuxAttrGetType(const LosMuxAttr *attr, INT32 *outType); extern UINT32 LOS_MuxAttrSetType(LosMuxAttr *attr, INT32 type); extern UINT32 LOS_MuxAttrGetProtocol(const LosMuxAttr *attr, INT32 *protocol); extern UINT32 LOS_MuxAttrSetProtocol(LosMuxAttr *attr, INT32 protocol); extern UINT32 LOS_MuxAttrGetPrioceiling(const LosMuxAttr *attr, INT32 *prioceiling); extern UINT32 LOS_MuxAttrSetPrioceiling(LosMuxAttr *attr, INT32 prioceiling); extern UINT32 LOS_MuxSetPrioceiling(LosMux *mutex, INT32 prioceiling, INT32 *oldPrioceiling); extern UINT32 LOS_MuxGetPrioceiling(const LosMux *mutex, INT32 *prioceiling); extern BOOL LOS_MuxIsValid(const LosMux *mutex); /** * @ingroup los_mux * @brief Init a mutex. * * @par Description: * This API is used to Init a mutex. A mutex handle is assigned to muxHandle when the mutex is init successfully. * Return LOS_OK on creating successful, return specific error code otherwise. * @attention * <ul> * <li>The total number of mutexes is pre-configured. If there are no available mutexes, the mutex creation fails.</li> * </ul> * * @param mutex [IN] Handle pointer of the successfully init mutex. * @param attr [IN] The mutex attribute. * * @retval #LOS_EINVAL The mutex pointer is NULL. * @retval #LOS_OK The mutex is successfully created. * @par Dependency: * <ul><li>los_mux.h: the header file that contains the API declaration.</li></ul> * @see LOS_MuxDestroy */ extern UINT32 LOS_MuxInit(LosMux *mutex, const LosMuxAttr *attr); /** * @ingroup los_mux * @brief Destroy a mutex. * * @par Description: * This API is used to delete a specified mutex. Return LOS_OK on deleting successfully, return specific error code * otherwise. * @attention * <ul> * <li>The specific mutex should be created firstly.</li> * <li>The mutex can be deleted successfully only if no other tasks pend on it.</li> * </ul> * * @param mutex [IN] Handle of the mutex to be deleted. * * @retval #LOS_EINVAL The mutex pointer is NULL. * @retval #LOS_EBUSY Tasks pended on this mutex. * @retval #LOS_EBADF The lock has been destroyed or broken. * @retval #LOS_OK The mutex is successfully deleted. * @par Dependency: * <ul><li>los_mux.h: the header file that contains the API declaration.</li></ul> * @see LOS_MuxInit */ extern UINT32 LOS_MuxDestroy(LosMux *mutex); /** * @ingroup los_mux * @brief Wait to lock a mutex. * * @par Description: * This API is used to wait for a specified period of time to lock a mutex. * @attention * <ul> * <li>The specific mutex should be created firstly.</li> * <li>The function fails if the mutex that is waited on is already locked by another thread when the task scheduling * is disabled.</li> * <li>Do not wait on a mutex during an interrupt.</li> * <li>The priority inheritance protocol is supported. If a higher-priority thread is waiting on a mutex, it changes * the priority of the thread that owns the mutex to avoid priority inversion.</li> * <li>A recursive mutex can be locked more than once by the same thread.</li> * <li>Do not call this API in software timer callback. </li> * </ul> * * @param mutex [IN] Handle of the mutex to be waited on. * @param timeout [IN] Waiting time. The value range is [0, LOS_WAIT_FOREVER](unit: Tick). * * @retval #LOS_EINVAL The mutex pointer is NULL, The timeout is zero or Lock status error. * @retval #LOS_EINTR The mutex is being locked during an interrupt. * @retval #LOS_EBUSY Tasks pended on this mutex. * @retval #LOS_EBADF The lock has been destroyed or broken. * @retval #LOS_EDEADLK Mutex error check failed or System locked task scheduling. * @retval #LOS_ETIMEDOUT The mutex waiting times out. * @retval #LOS_OK The mutex is successfully locked. * @par Dependency: * <ul><li>los_mux.h: the header file that contains the API declaration.</li></ul> * @see LOS_MuxInit | LOS_MuxUnlock */ extern UINT32 LOS_MuxLock(LosMux *mutex, UINT32 timeout); /** * @ingroup los_mux * @brief Try wait to lock a mutex. * * @par Description: * This API is used to wait for a specified period of time to lock a mutex. * @attention * <ul> * <li>The specific mutex should be created firstly.</li> * <li>The function fails if the mutex that is waited on is already locked by another thread when the task scheduling * is disabled.</li> * <li>Do not wait on a mutex during an interrupt.</li> * <li>The priority inheritance protocol is supported. If a higher-priority thread is waiting on a mutex, it changes * the priority of the thread that owns the mutex to avoid priority inversion.</li> * <li>A recursive mutex can be locked more than once by the same thread.</li> * <li>Do not call this API in software timer callback. </li> * </ul> * * @param mutex [IN] Handle of the mutex to be waited on. * * @retval #LOS_EINVAL The mutex pointer is NULL or Lock status error. * @retval #LOS_EINTR The mutex is being locked during an interrupt. * @retval #LOS_EBUSY Tasks pended on this mutex. * @retval #LOS_EBADF The lock has been destroyed or broken. * @retval #LOS_EDEADLK Mutex error check failed or System locked task scheduling. * @retval #LOS_ETIMEDOUT The mutex waiting times out. * @retval #LOS_OK The mutex is successfully locked. * @par Dependency: * <ul><li>los_mux.h: the header file that contains the API declaration.</li></ul> * @see LOS_MuxInit | LOS_MuxUnlock */ extern UINT32 LOS_MuxTrylock(LosMux *mutex); /** * @ingroup los_mux * @brief Release a mutex. * * @par Description: * This API is used to release a specified mutex. * @attention * <ul> * <li>The specific mutex should be created firstly.</li> * <li>Do not release a mutex during an interrupt.</li> * <li>If a recursive mutex is locked for many times, it must be unlocked for the same times to be released.</li> * </ul> * * @param mutex [IN] Handle of the mutex to be released. * * @retval #LOS_EINVAL The mutex pointer is NULL, The timeout is zero or Lock status error. * @retval #LOS_EINTR The mutex is being locked during an interrupt. * @retval #LOS_EBUSY Tasks pended on this mutex. * @retval #LOS_EBADF The lock has been destroyed or broken. * @retval #LOS_EDEADLK Mutex error check failed or System locked task scheduling. * @retval #LOS_ETIMEDOUT The mutex waiting times out. * @retval #LOS_OK The mutex is successfully locked. * @par Dependency: * <ul><li>los_mux.h: the header file that contains the API declaration.</li></ul> * @see LOS_MuxInit | LOS_MuxLock */ extern UINT32 LOS_MuxUnlock(LosMux *mutex); #ifdef __cplusplus #if __cplusplus } #endif #endif /* __cplusplus */ #endif /* _LOS_MUX_H */
39.444444
119
0.712989
[ "object" ]
37ca17240370b44803540bbec673d13f725cc4b6
4,592
h
C
services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_connection.h
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
null
null
null
services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_connection.h
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
null
null
null
services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_connection.h
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
1
2021-09-13T12:07:54.000Z
2021-09-13T12:07:54.000Z
/* * Copyright (c) 2021 Huawei Device 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 I_KV_DB_CONNECTION_H #define I_KV_DB_CONNECTION_H #include <string> #include <functional> #include "types.h" #include "db_types.h" #include "macro_utils.h" #include "query.h" namespace DistributedDB { class IKvDB; class IKvDBSnapshot; class KvDBObserverHandle; class KvDBCommitNotifyData; class IKvDBResultSet; using KvDBObserverAction = std::function<void(const KvDBCommitNotifyData &data)>; using KvDBConflictAction = std::function<void(const KvDBCommitNotifyData &data)>; class IKvDBConnection { public: IKvDBConnection() = default; virtual ~IKvDBConnection() {}; DISABLE_COPY_ASSIGN_MOVE(IKvDBConnection); // Get the value from the database. virtual int Get(const IOption &option, const Key &key, Value &value) const = 0; // Put the value to the database. virtual int Put(const IOption &option, const Key &key, const Value &value) = 0; // Delete the value from the database. virtual int Delete(const IOption &option, const Key &key) = 0; // Clear all the data from the database. virtual int Clear(const IOption &option) = 0; // Get all the data from the database. virtual int GetEntries(const IOption &option, const Key &keyPrefix, std::vector<Entry> &entries) const = 0; virtual int GetEntries(const IOption &option, const Query &query, std::vector<Entry> &entries) const = 0; virtual int GetCount(const IOption &option, const Query &query, int &count) const = 0; // Put the batch values to the database. virtual int PutBatch(const IOption &option, const std::vector<Entry> &entries) = 0; // Delete the batch values from the database. virtual int DeleteBatch(const IOption &option, const std::vector<Key> &keys) = 0; // Get the snapshot. virtual int GetSnapshot(IKvDBSnapshot *&snapshot) const = 0; // Release the created snapshot. virtual void ReleaseSnapshot(IKvDBSnapshot *&snapshot) = 0; // Start the transaction. virtual int StartTransaction() = 0; // Commit the transaction. virtual int Commit() = 0; // Roll back the transaction. virtual int RollBack() = 0; // Check if the transaction already started manually virtual bool IsTransactionStarted() const = 0; // Register observer. virtual KvDBObserverHandle *RegisterObserver(unsigned mode, const Key &key, const KvDBObserverAction &action, int &errCode) = 0; // Unregister observer. virtual int UnRegisterObserver(const KvDBObserverHandle *observerHandle) = 0; // Register a conflict notifier. virtual int SetConflictNotifier(int conflictType, const KvDBConflictAction &action) = 0; // Close and release the connection. virtual int Close() = 0; virtual std::string GetIdentifier() const = 0; // Pragma interface. virtual int Pragma(int cmd, void *parameter) = 0; // Rekey the database. virtual int Rekey(const CipherPassword &passwd) = 0; // Empty passwords represent non-encrypted files. // Export existing database files to a specified database file in the specified directory. virtual int Export(const std::string &filePath, const CipherPassword &passwd) = 0; // Import the existing database files to the specified database file in the specified directory. virtual int Import(const std::string &filePath, const CipherPassword &passwd) = 0; // Get the result set virtual int GetResultSet(const IOption &option, const Key &keyPrefix, IKvDBResultSet *&resultSet) const = 0; virtual int GetResultSet(const IOption &option, const Query &query, IKvDBResultSet *&resultSet) const = 0; // Release the result set virtual void ReleaseResultSet(IKvDBResultSet *&resultSet) = 0; virtual int RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier &notifier) = 0; // Get the securityLabel and securityFlag virtual int GetSecurityOption(int &securityLabel, int &securityFlag) const = 0; }; } // namespace DistributedDB #endif // I_KV_DB_CONNECTION_H
35.053435
112
0.72365
[ "vector" ]
37ca4a40a07d439da5952735012a2edf176f8fe2
11,704
h
C
CBPC/config.h
Acro748/CBPCSSE
fabd56ce8f8ac10cde17325f0bd61ecc8cbcda20
[ "MIT" ]
null
null
null
CBPC/config.h
Acro748/CBPCSSE
fabd56ce8f8ac10cde17325f0bd61ecc8cbcda20
[ "MIT" ]
null
null
null
CBPC/config.h
Acro748/CBPCSSE
fabd56ce8f8ac10cde17325f0bd61ecc8cbcda20
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <vector> #include <iostream> #include <string> #include <fstream> #include <shared_mutex> #include <concurrent_vector.h> #include <concurrent_unordered_map.h> #include "skse64/NiGeometry.h" #include "skse64\GameReferences.h" #include "skse64\PapyrusEvents.h" #include "skse64\GameRTTI.h" #include "skse64\GameSettings.h" #include "skse64_common/skse_version.h" #include "skse64/NiNodes.h" #include "skse64/NiGeometry.h" #include "skse64/NiRTTI.h" #include "skse64/PapyrusNativeFunctions.h" #include "skse64\PapyrusActor.h" #include <skse64/PapyrusKeyword.h> #include "Utility.hpp" #include "skse64/GameMenus.h" #include "skse64/GameData.h" #include "skse64/GameEvents.h" #include <atomic> #ifdef RUNTIME_VR_VERSION_1_4_15 #include "skse64/openvr_1_0_12.h" #endif typedef concurrency::concurrent_unordered_map<std::string, float> configEntry_t; typedef concurrency::concurrent_unordered_map<std::string, configEntry_t> config_t; extern concurrency::concurrent_unordered_map<std::string, std::string> configMap; extern int configReloadCount; extern config_t config; extern config_t config0weight; extern int collisionSkipFrames; extern int collisionSkipFramesPelvis; extern concurrency::concurrent_unordered_map<std::string, bool> ActorNodeStoppedPhysicsMap; //typedef std::unordered_map<std::string, bool> nodeCollisionMap; //typedef std::unordered_map<std::string, NiPoint3> nodeCollisionAmountMap; //extern std::unordered_map<Actor*, nodeCollisionMap> LeftBreastCollisionMap; //extern std::unordered_map<Actor*, nodeCollisionMap> RightBreastCollisionMap; // //extern std::unordered_map<Actor*, nodeCollisionAmountMap> BreastCollisionAmountMap; void loadConfig(); void GameLoad(); extern int gridsize; extern int adjacencyValue; extern int tuningModeCollision; extern int malePhysics; //extern int malePhysicsOnlyForExtraRaces; extern float actorDistance; extern float actorBounceDistance; extern int actorAngle; extern int inCombatActorCount; extern int outOfCombatActorCount; extern float cbellybulge; extern float cbellybulgemax; extern float cbellybulgeposlowest; extern std::vector<std::string> bellybulgenodesList; extern float vaginaOpeningLimit; extern float vaginaOpeningMultiplier; extern float anusOpeningLimit; extern float anusOpeningMultiplier; extern float bellyBulgeReturnTime; //extern std::vector<std::string> extraRacesList; extern int logging; extern int useCamera; extern int fpsCorrectionEnabled; extern std::vector<std::string> noJitterFixNodesList; //extern int useOldHook; extern std::atomic<bool> dialogueMenuOpen; extern std::atomic<bool> raceSexMenuClosed; extern std::atomic<bool> raceSexMenuOpen; extern std::atomic<bool> MainMenuOpen; extern std::atomic<bool> consoleConfigReload; extern std::atomic<bool> modPaused; extern BSFixedString breastGravityReferenceBoneString; extern BSFixedString GroundReferenceBone; extern BSFixedString HighheelReferenceBone; extern BGSKeyword* KeywordArmorClothing; extern BGSKeyword* KeywordArmorLight; extern BGSKeyword* KeywordArmorHeavy; extern BGSKeyword* KeywordActorTypeNPC; extern BSFixedString KeywordNameAsNakedL; extern BSFixedString KeywordNameAsNakedR; extern BSFixedString KeywordNameAsClothingL; extern BSFixedString KeywordNameAsClothingR; extern BSFixedString KeywordNameAsLightL; extern BSFixedString KeywordNameAsLightR; extern BSFixedString KeywordNameAsHeavyL; extern BSFixedString KeywordNameAsHeavyR; extern BSFixedString KeywordNameNoPushUpL; extern BSFixedString KeywordNameNoPushUpR; extern UInt32 VampireLordBeastRaceFormId; extern EventDispatcher<SKSEModCallbackEvent>* g_modEventDispatcher; extern concurrency::concurrent_vector<std::string> PlayerCollisionEventNodes; extern float MinimumCollisionDurationForEvent; struct PlayerCollisionEvent { bool collisionInThisCycle = false; float durationFilled = 0.0f; float totalDurationFilled = 0.0f; }; extern concurrency::concurrent_unordered_map<std::string, PlayerCollisionEvent> ActorNodePlayerCollisionEventMap; enum eLogLevels { LOGLEVEL_ERR = 0, LOGLEVEL_WARN, LOGLEVEL_INFO, }; void Log(const int msgLogLevel, const char * fmt, ...); #define LOG(fmt, ...) Log(LOGLEVEL_WARN, fmt, ##__VA_ARGS__) #define LOG_ERR(fmt, ...) Log(LOGLEVEL_ERR, fmt, ##__VA_ARGS__) #define LOG_INFO(fmt, ...) Log(LOGLEVEL_INFO, fmt, ##__VA_ARGS__) #ifdef RUNTIME_VR_VERSION_1_4_15 extern unsigned short hapticFrequency; extern int hapticStrength; extern bool leftHandedMode; #endif //Collision Stuff struct Sphere { NiPoint3 offset0 = NiPoint3(0, 0, 0); NiPoint3 offset100 = NiPoint3(0, 0, 0); double radius0 = 4.0; double radius100 = 4.0; double radius100pwr2 = 16.0; NiPoint3 worldPos = NiPoint3(0, 0, 0); std::string NodeName; UInt32 index = -1; }; struct Capsule { NiPoint3 End1_offset0 = NiPoint3(0, 0, 0); NiPoint3 End1_offset100 = NiPoint3(0, 0, 0); NiPoint3 End1_worldPos = NiPoint3(0, 0, 0); double End1_radius0 = 4.0; double End1_radius100 = 4.0; double End1_radius100pwr2 = 16.0; NiPoint3 End2_offset0 = NiPoint3(0, 0, 0); NiPoint3 End2_offset100 = NiPoint3(0, 0, 0); NiPoint3 End2_worldPos = NiPoint3(0, 0, 0); double End2_radius0 = 4.0; double End2_radius100 = 4.0; double End2_radius100pwr2 = 16.0; std::string NodeName; UInt32 index = -1; }; struct ConfigLine { std::vector<Sphere> CollisionSpheres; std::vector<Capsule> CollisionCapsules; std::string NodeName; std::vector<std::string> IgnoredColliders; std::vector<std::string> IgnoredSelfColliders; bool IgnoreAllSelfColliders = false; float scaleWeight = 1.0f; }; enum ConditionType { IsRaceFormId, IsRaceName, ActorFormId, ActorName, ActorWeightGreaterThan, IsMale, IsFemale, IsPlayer, IsInFaction, HasKeywordId, HasKeywordName, RaceHasKeywordId, RaceHasKeywordName, IsActorBase, IsPlayerTeammate, IsUnique, IsVoiceType, IsCombatStyle, IsClass }; struct ConditionItem { //multiple items std::vector<ConditionItem> OrItems; //single item bool single = true; bool Not = false; ConditionType type; UInt32 id; std::string str; }; struct Conditions { std::vector<ConditionItem> AndItems; }; extern concurrency::concurrent_unordered_map<std::string, Conditions> nodeConditionsMap; struct SpecificNPCConfig { Conditions conditions; int ConditionPriority = 50; std::vector<std::string> AffectedNodeLines; std::vector<std::string> ColliderNodeLines; concurrency::concurrent_vector<ConfigLine> AffectedNodesList; concurrency::concurrent_vector<ConfigLine> ColliderNodesList; float cbellybulge; float cbellybulgemax; float cbellybulgeposlowest; std::vector<std::string> bellybulgenodesList; float bellyBulgeReturnTime = 1.5f; float vaginaOpeningLimit = 5.0f; float vaginaOpeningMultiplier = 4.0f; float anusOpeningLimit = 5.0f; float anusOpeningMultiplier = 4.0f; }; extern std::vector<SpecificNPCConfig> specificNPCConfigList; struct SpecificNPCBounceConfig { Conditions conditions; int ConditionPriority = 50; config_t config; config_t config0weight; }; extern std::vector<SpecificNPCBounceConfig> specificNPCBounceConfigList; bool compareConfigs(const SpecificNPCConfig& config1, const SpecificNPCConfig& config2); bool compareBounceConfigs(const SpecificNPCBounceConfig& config1, const SpecificNPCBounceConfig& config2); bool GetSpecificNPCBounceConfigForActor(Actor* actor, SpecificNPCBounceConfig& snbc); bool IsConfigActuallyAllocated(SpecificNPCBounceConfig snbc, std::string section); //If the config of that part is not set and just set to default, return false #ifdef RUNTIME_VR_VERSION_1_4_15 extern std::vector<std::string> PlayerNodeLines; extern std::vector<ConfigLine> PlayerNodesList; //Player nodes that can collide nodes std::string GetWeaponTypeName(UInt8 kType); void GetSettings(); extern float MeleeWeaponTranslateX; extern float MeleeWeaponTranslateY; extern float MeleeWeaponTranslateZ; //Weapon Collision Stuff struct Triangle { NiPoint3 orga; NiPoint3 orgb; NiPoint3 orgc; NiPoint3 a; NiPoint3 b; NiPoint3 c; }; struct WeaponConfigLine { Triangle CollisionTriangle; std::string WeaponName; }; extern std::vector<WeaponConfigLine> WeaponCollidersList; //Weapon colliders std::vector<Triangle> GetCollisionTriangles(std::string name, UInt8 kType); void ConfigWeaponLineSplitter(std::string &line, Triangle &newTriangle); void LoadWeaponCollisionConfig(); #endif class AllMenuEventHandler : public BSTEventSink <MenuOpenCloseEvent> { public: virtual EventResult ReceiveEvent(MenuOpenCloseEvent * evn, EventDispatcher<MenuOpenCloseEvent> * dispatcher); }; extern AllMenuEventHandler menuEvent; void MenuOpened(std::string name); void MenuClosed(std::string name); extern std::vector<std::string> AffectedNodeLines; extern std::vector<std::string> ColliderNodeLines; extern concurrency::concurrent_vector<ConfigLine> AffectedNodesList; //Nodes that can be collided with extern concurrency::concurrent_vector<ConfigLine> ColliderNodesList; //Nodes that can collide nodes void loadCollisionConfig(); void loadMasterConfig(); void loadExtraCollisionConfig(); void loadSystemConfig(); void LoadPlayerCollisionEventConfig(); void ConfigLineSplitterSphere(std::string &line, Sphere &newSphere); void ConfigLineSplitterCapsule(std::string &line, Capsule &newCapsule); int GetConfigSettingsValue(std::string line, std::string &variable); std::string GetConfigSettingsStringValue(std::string line, std::string& variable); std::string GetConfigSettings2StringValues(std::string line, std::string& variable, std::string& value2); float GetConfigSettingsFloatValue(std::string line, std::string &variable); void printSpheresMessage(std::string message, std::vector<Sphere> spheres); std::vector<std::string> ConfigLineVectorToStringVector(std::vector<ConfigLine> linesList); //The basic unit is parallel processing, but some physics chain nodes need sequential loading extern std::vector<std::vector<std::string>> affectedBones; bool GetSpecificNPCConfigForActor(Actor * actor, SpecificNPCConfig &snc); bool IsActorMale(Actor* actor); bool ConditionCheck(Actor* actor, ConditionItem& condition); bool CheckActorForConditions(Actor* actor, Conditions& conditions); std::string GetActorNodeString(Actor* actor, BSFixedString nodeName); std::string GetFormIdNodeString(UInt32 id, BSFixedString nodeName); bool RegisterFuncs(VMClassRegistry* registry); BSFixedString GetVersion(StaticFunctionTag* base); BSFixedString GetVersionMinor(StaticFunctionTag* base); BSFixedString GetVersionBeta(StaticFunctionTag* base); void ReloadConfig(StaticFunctionTag* base); void StartPhysics(StaticFunctionTag* base, Actor* actor, BSFixedString nodeName); void StopPhysics(StaticFunctionTag* base, Actor* actor, BSFixedString nodeName); bool AttachColliderSphere(StaticFunctionTag* base, Actor* actor, BSFixedString nodeName, VMArray<float> position, float radius, float scaleWeight, UInt32 index, bool IsAffectedNodes); bool AttachColliderCapsule(StaticFunctionTag* base, Actor* actor, BSFixedString nodeName, VMArray<float> End1_position, float End1_radius, VMArray<float> End2_position, float End2_radius, float scaleWeight, UInt32 index, bool IsAffectedNodes); bool DetachCollider(StaticFunctionTag* base, Actor* actor, BSFixedString nodeName, UInt32 type, UInt32 index, bool IsAffectedNodes); extern std::string versionStr; extern UInt32 version; class TESEquipEventHandler : public BSTEventSink <TESEquipEvent> { public: virtual EventResult ReceiveEvent(TESEquipEvent* evn, EventDispatcher<TESEquipEvent>* dispatcher); }; extern EventDispatcher<TESEquipEvent>* g_TESEquipEventDispatcher; extern TESEquipEventHandler g_TESEquipEventHandler; extern bool debugtimelog;
27.409836
243
0.808014
[ "vector" ]
37cf46cbf78ffe03f5a2849c739c47c59f7f140d
2,456
h
C
gcr-3.34.0/gcr/gcr-key-mechanisms.h
BeanGreen247/surf
a56d1b0ceb43c578c6a3258e4ffb2903dc691fe2
[ "MIT" ]
null
null
null
gcr-3.34.0/gcr/gcr-key-mechanisms.h
BeanGreen247/surf
a56d1b0ceb43c578c6a3258e4ffb2903dc691fe2
[ "MIT" ]
null
null
null
gcr-3.34.0/gcr/gcr-key-mechanisms.h
BeanGreen247/surf
a56d1b0ceb43c578c6a3258e4ffb2903dc691fe2
[ "MIT" ]
null
null
null
/* * Copyright (C) 2011 Collabora Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see <http://www.gnu.org/licenses/>. * * Author: Stef Walter <stefw@collabora.co.uk> */ #if !defined (__GCR_INSIDE_HEADER__) && !defined (GCR_COMPILATION) #error "Only <gcr/gcr.h> or <gcr/gcr-base.h> can be included directly." #endif #ifndef __GCR_KEY_MECHANISMS_H__ #define __GCR_KEY_MECHANISMS_H__ #include <glib-object.h> #include "gck/gck.h" G_BEGIN_DECLS gulong _gcr_key_mechanisms_check (GckObject *key, const gulong *mechanisms, gsize n_mechanisms, gulong action_attr_type, GCancellable *cancellable, GError **error); void _gcr_key_mechanisms_check_async (GckObject *key, const gulong *mechanisms, gsize n_mechanisms, gulong action_attr_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); gulong _gcr_key_mechanisms_check_finish (GckObject *key, GAsyncResult *result, GError **error); G_END_DECLS #endif /* __GCR_KEY_MECHANISMS_H__ */
44.654545
92
0.49145
[ "object" ]
37cfe53c4757033e06c3b6a38582d71ec311ac2e
326
h
C
LiuHe/LiuHe/Classes/HomeViewController/View/CellView/DataCell.h
bigstarH/LiuHe
7996991ddf6c1e3501cb9b66d6c29bfcd8c9fcf6
[ "Apache-2.0" ]
null
null
null
LiuHe/LiuHe/Classes/HomeViewController/View/CellView/DataCell.h
bigstarH/LiuHe
7996991ddf6c1e3501cb9b66d6c29bfcd8c9fcf6
[ "Apache-2.0" ]
null
null
null
LiuHe/LiuHe/Classes/HomeViewController/View/CellView/DataCell.h
bigstarH/LiuHe
7996991ddf6c1e3501cb9b66d6c29bfcd8c9fcf6
[ "Apache-2.0" ]
null
null
null
// // DataCell.h // LiuHe // // Created by huxingqin on 2016/12/1. // Copyright © 2016年 huxingqin. All rights reserved. // #import <UIKit/UIKit.h> #import "DataModel.h" /** 资料cell */ @interface DataCell : UITableViewCell + (instancetype)dataCell:(UITableView *)tableView; - (void)setCellData:(DataModel *)model; @end
16.3
53
0.687117
[ "model" ]
37dcc1c369db3eeb3f427295128b07480b5792b1
7,521
h
C
include/cutlass/epilogue/threadblock/epilogue_base.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
44
2020-09-15T05:31:25.000Z
2022-03-22T08:02:02.000Z
include/cutlass/epilogue/threadblock/epilogue_base.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
null
null
null
include/cutlass/epilogue/threadblock/epilogue_base.h
MegEngine/cutlass
31798848e40c2752d4b3db193491a63b77455029
[ "BSD-3-Clause" ]
7
2020-09-16T15:18:21.000Z
2022-03-28T10:06:11.000Z
/*************************************************************************************************** * Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, *this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright *notice, this list of conditions and the following disclaimer in the *documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the names of its *contributors may be used to endorse or promote products derived from this *software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY DIRECT, *INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY *OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TOR (INCLUDING *NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, *EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/ /*! \file \brief Epilogue for threadblock scoped GEMMs using Tensor Ops. The epilogue rearranges the result of a matrix product through shared memory to match canonical tensor layouts in global memory. Epilogues support conversion and reduction operations. */ #pragma once #if defined(__CUDACC_RTC__) #include <cuda/std/cassert> #else #include <assert.h> #endif #include "cutlass/cutlass.h" #include "cutlass/matrix_shape.h" #include "cutlass/numeric_types.h" #include "cutlass/array.h" #include "cutlass/layout/vector.h" #include "cutlass/layout/tensor.h" #include "cutlass/tensor_coord.h" #include "cutlass/aligned_buffer.h" #include "cutlass/gemm/gemm.h" #include "cutlass/transform/pitch_linear_thread_map.h" //////////////////////////////////////////////////////////////////////////////// namespace cutlass { namespace epilogue { namespace threadblock { //////////////////////////////////////////////////////////////////////////////// /// Base class for epilogues defining warp-level template <typename Shape_, ///< Shape of threadblock tile (concept: GemmShape) typename WarpShape_, ///< Warp-level MMA operator (concept: ///< gemm::warp::MmaTensorOp) int PartitionsK, ///< Number of partitions of the K dimension typename AccumulatorFragmentIterator_, ///< Fragment iterator ///< selecting accumulators typename WarpTileIterator_, ///< Warp-scoped tile iterator writing ///< accumulators to SMEM typename Padding_ ///< Padding added to SMEM allocation to avoid bank ///< conflicts (concept: MatrixShape) > class EpilogueBase { public: using Shape = Shape_; using WarpShape = WarpShape_; static int const kPartitionsK = PartitionsK; using AccumulatorFragmentIterator = AccumulatorFragmentIterator_; using WarpTileIterator = WarpTileIterator_; using Padding = Padding_; /// Output layout is always row-major using Layout = layout::RowMajor; /// The complete warp-level accumulator tile using AccumulatorTile = typename AccumulatorFragmentIterator::AccumulatorTile; /// Accumulator element using ElementAccumulator = typename AccumulatorTile::Element; /// Number of warps using WarpCount = gemm::GemmShape<Shape::kM / WarpShape::kM, Shape::kN / WarpShape::kN, kPartitionsK>; public: /// Shared storage allocation needed by the epilogue struct SharedStorage { // // Type definitions // /// Element type of shared memory using Element = typename WarpTileIterator::Element; /// Tensor reference to shared memory allocation using TensorRef = typename WarpTileIterator::TensorRef; /// Layout of shared memory allocation using Layout = typename WarpTileIterator::Layout; /// Logical shape of the shared memory tile written to by all warps. using Shape = MatrixShape<WarpCount::kM * WarpTileIterator::Shape::kRow * WarpCount::kK, WarpCount::kN * WarpTileIterator::Shape::kColumn>; /// Shape of the shared memory allocation for the epilogue using StorageShape = MatrixShape<Shape::kRow + Padding::kRow, Shape::kColumn + Padding::kColumn>; // // Data members // AlignedBuffer<Element, StorageShape::kCount> storage; // // Methods // /// Returns a pointer to the shared memory buffer CUTLASS_DEVICE Element* data() { return storage.data(); } /// Returns a tensor reference to the shared memory buffer CUTLASS_DEVICE TensorRef reference() { return TensorRef(storage.data(), Layout::packed({StorageShape::kRow, StorageShape::kColumn})); } }; protected: // // Data members // SharedStorage& shared_storage_; /// Stores a warp's fragment of accumulators to SMEM WarpTileIterator warp_tile_iterator_; public: /// Constructor CUTLASS_DEVICE EpilogueBase(SharedStorage& shared_storage, ///< Shared storage object int thread_idx, ///< ID of a thread within the threadblock int warp_idx, ///< ID of warp within threadblock int lane_idx ///< Id of thread within warp ) : shared_storage_(shared_storage), warp_tile_iterator_(shared_storage.reference(), lane_idx) { // Compute warp location within threadblock tile by mapping the warp_id // to three coordinates: // // _m: the warp's position within the threadblock along the M // dimension _n: the warp's position within the threadblock along the // N dimension _k: the warp's position within the threadblock along // the K dimension int warp_k = warp_idx / (WarpCount::kM * WarpCount::kN); int warp_mn = warp_idx % (WarpCount::kM * WarpCount::kN); int warp_m = warp_mn % WarpCount::kM; int warp_n = warp_mn / WarpCount::kM; MatrixCoord warp_offset{warp_k * WarpCount::kM + warp_m, warp_n}; warp_tile_iterator_.add_tile_offset(warp_offset); } }; //////////////////////////////////////////////////////////////////////////////// } // namespace threadblock } // namespace epilogue } // namespace cutlass ////////////////////////////////////////////////////////////////////////////////
38.569231
100
0.612153
[ "object", "shape", "vector", "transform" ]
37dcceb13c0d14639df93e848a54de9fcb7dca3a
17,971
h
C
aws-cpp-sdk-groundstation/include/aws/groundstation/model/DescribeContactResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-groundstation/include/aws/groundstation/model/DescribeContactResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-groundstation/include/aws/groundstation/model/DescribeContactResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/groundstation/GroundStation_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/groundstation/model/ContactStatus.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/DateTime.h> #include <aws/groundstation/model/Elevation.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/groundstation/model/DataflowDetail.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace GroundStation { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/groundstation-2019-05-23/DescribeContactResponse">AWS * API Reference</a></p> */ class AWS_GROUNDSTATION_API DescribeContactResult { public: DescribeContactResult(); DescribeContactResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DescribeContactResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>UUID of a contact.</p> */ inline const Aws::String& GetContactId() const{ return m_contactId; } /** * <p>UUID of a contact.</p> */ inline void SetContactId(const Aws::String& value) { m_contactId = value; } /** * <p>UUID of a contact.</p> */ inline void SetContactId(Aws::String&& value) { m_contactId = std::move(value); } /** * <p>UUID of a contact.</p> */ inline void SetContactId(const char* value) { m_contactId.assign(value); } /** * <p>UUID of a contact.</p> */ inline DescribeContactResult& WithContactId(const Aws::String& value) { SetContactId(value); return *this;} /** * <p>UUID of a contact.</p> */ inline DescribeContactResult& WithContactId(Aws::String&& value) { SetContactId(std::move(value)); return *this;} /** * <p>UUID of a contact.</p> */ inline DescribeContactResult& WithContactId(const char* value) { SetContactId(value); return *this;} /** * <p>Status of a contact.</p> */ inline const ContactStatus& GetContactStatus() const{ return m_contactStatus; } /** * <p>Status of a contact.</p> */ inline void SetContactStatus(const ContactStatus& value) { m_contactStatus = value; } /** * <p>Status of a contact.</p> */ inline void SetContactStatus(ContactStatus&& value) { m_contactStatus = std::move(value); } /** * <p>Status of a contact.</p> */ inline DescribeContactResult& WithContactStatus(const ContactStatus& value) { SetContactStatus(value); return *this;} /** * <p>Status of a contact.</p> */ inline DescribeContactResult& WithContactStatus(ContactStatus&& value) { SetContactStatus(std::move(value)); return *this;} /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline const Aws::Vector<DataflowDetail>& GetDataflowList() const{ return m_dataflowList; } /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline void SetDataflowList(const Aws::Vector<DataflowDetail>& value) { m_dataflowList = value; } /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline void SetDataflowList(Aws::Vector<DataflowDetail>&& value) { m_dataflowList = std::move(value); } /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline DescribeContactResult& WithDataflowList(const Aws::Vector<DataflowDetail>& value) { SetDataflowList(value); return *this;} /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline DescribeContactResult& WithDataflowList(Aws::Vector<DataflowDetail>&& value) { SetDataflowList(std::move(value)); return *this;} /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline DescribeContactResult& AddDataflowList(const DataflowDetail& value) { m_dataflowList.push_back(value); return *this; } /** * <p>List describing source and destination details for each dataflow edge.</p> */ inline DescribeContactResult& AddDataflowList(DataflowDetail&& value) { m_dataflowList.push_back(std::move(value)); return *this; } /** * <p>End time of a contact.</p> */ inline const Aws::Utils::DateTime& GetEndTime() const{ return m_endTime; } /** * <p>End time of a contact.</p> */ inline void SetEndTime(const Aws::Utils::DateTime& value) { m_endTime = value; } /** * <p>End time of a contact.</p> */ inline void SetEndTime(Aws::Utils::DateTime&& value) { m_endTime = std::move(value); } /** * <p>End time of a contact.</p> */ inline DescribeContactResult& WithEndTime(const Aws::Utils::DateTime& value) { SetEndTime(value); return *this;} /** * <p>End time of a contact.</p> */ inline DescribeContactResult& WithEndTime(Aws::Utils::DateTime&& value) { SetEndTime(std::move(value)); return *this;} /** * <p>Error message for a contact.</p> */ inline const Aws::String& GetErrorMessage() const{ return m_errorMessage; } /** * <p>Error message for a contact.</p> */ inline void SetErrorMessage(const Aws::String& value) { m_errorMessage = value; } /** * <p>Error message for a contact.</p> */ inline void SetErrorMessage(Aws::String&& value) { m_errorMessage = std::move(value); } /** * <p>Error message for a contact.</p> */ inline void SetErrorMessage(const char* value) { m_errorMessage.assign(value); } /** * <p>Error message for a contact.</p> */ inline DescribeContactResult& WithErrorMessage(const Aws::String& value) { SetErrorMessage(value); return *this;} /** * <p>Error message for a contact.</p> */ inline DescribeContactResult& WithErrorMessage(Aws::String&& value) { SetErrorMessage(std::move(value)); return *this;} /** * <p>Error message for a contact.</p> */ inline DescribeContactResult& WithErrorMessage(const char* value) { SetErrorMessage(value); return *this;} /** * <p>Ground station for a contact.</p> */ inline const Aws::String& GetGroundStation() const{ return m_groundStation; } /** * <p>Ground station for a contact.</p> */ inline void SetGroundStation(const Aws::String& value) { m_groundStation = value; } /** * <p>Ground station for a contact.</p> */ inline void SetGroundStation(Aws::String&& value) { m_groundStation = std::move(value); } /** * <p>Ground station for a contact.</p> */ inline void SetGroundStation(const char* value) { m_groundStation.assign(value); } /** * <p>Ground station for a contact.</p> */ inline DescribeContactResult& WithGroundStation(const Aws::String& value) { SetGroundStation(value); return *this;} /** * <p>Ground station for a contact.</p> */ inline DescribeContactResult& WithGroundStation(Aws::String&& value) { SetGroundStation(std::move(value)); return *this;} /** * <p>Ground station for a contact.</p> */ inline DescribeContactResult& WithGroundStation(const char* value) { SetGroundStation(value); return *this;} /** * <p>Maximum elevation angle of a contact.</p> */ inline const Elevation& GetMaximumElevation() const{ return m_maximumElevation; } /** * <p>Maximum elevation angle of a contact.</p> */ inline void SetMaximumElevation(const Elevation& value) { m_maximumElevation = value; } /** * <p>Maximum elevation angle of a contact.</p> */ inline void SetMaximumElevation(Elevation&& value) { m_maximumElevation = std::move(value); } /** * <p>Maximum elevation angle of a contact.</p> */ inline DescribeContactResult& WithMaximumElevation(const Elevation& value) { SetMaximumElevation(value); return *this;} /** * <p>Maximum elevation angle of a contact.</p> */ inline DescribeContactResult& WithMaximumElevation(Elevation&& value) { SetMaximumElevation(std::move(value)); return *this;} /** * <p>ARN of a mission profile.</p> */ inline const Aws::String& GetMissionProfileArn() const{ return m_missionProfileArn; } /** * <p>ARN of a mission profile.</p> */ inline void SetMissionProfileArn(const Aws::String& value) { m_missionProfileArn = value; } /** * <p>ARN of a mission profile.</p> */ inline void SetMissionProfileArn(Aws::String&& value) { m_missionProfileArn = std::move(value); } /** * <p>ARN of a mission profile.</p> */ inline void SetMissionProfileArn(const char* value) { m_missionProfileArn.assign(value); } /** * <p>ARN of a mission profile.</p> */ inline DescribeContactResult& WithMissionProfileArn(const Aws::String& value) { SetMissionProfileArn(value); return *this;} /** * <p>ARN of a mission profile.</p> */ inline DescribeContactResult& WithMissionProfileArn(Aws::String&& value) { SetMissionProfileArn(std::move(value)); return *this;} /** * <p>ARN of a mission profile.</p> */ inline DescribeContactResult& WithMissionProfileArn(const char* value) { SetMissionProfileArn(value); return *this;} /** * <p>Amount of time after a contact ends that you’d like to receive a CloudWatch * event indicating the pass has finished.</p> */ inline const Aws::Utils::DateTime& GetPostPassEndTime() const{ return m_postPassEndTime; } /** * <p>Amount of time after a contact ends that you’d like to receive a CloudWatch * event indicating the pass has finished.</p> */ inline void SetPostPassEndTime(const Aws::Utils::DateTime& value) { m_postPassEndTime = value; } /** * <p>Amount of time after a contact ends that you’d like to receive a CloudWatch * event indicating the pass has finished.</p> */ inline void SetPostPassEndTime(Aws::Utils::DateTime&& value) { m_postPassEndTime = std::move(value); } /** * <p>Amount of time after a contact ends that you’d like to receive a CloudWatch * event indicating the pass has finished.</p> */ inline DescribeContactResult& WithPostPassEndTime(const Aws::Utils::DateTime& value) { SetPostPassEndTime(value); return *this;} /** * <p>Amount of time after a contact ends that you’d like to receive a CloudWatch * event indicating the pass has finished.</p> */ inline DescribeContactResult& WithPostPassEndTime(Aws::Utils::DateTime&& value) { SetPostPassEndTime(std::move(value)); return *this;} /** * <p>Amount of time prior to contact start you’d like to receive a CloudWatch * event indicating an upcoming pass.</p> */ inline const Aws::Utils::DateTime& GetPrePassStartTime() const{ return m_prePassStartTime; } /** * <p>Amount of time prior to contact start you’d like to receive a CloudWatch * event indicating an upcoming pass.</p> */ inline void SetPrePassStartTime(const Aws::Utils::DateTime& value) { m_prePassStartTime = value; } /** * <p>Amount of time prior to contact start you’d like to receive a CloudWatch * event indicating an upcoming pass.</p> */ inline void SetPrePassStartTime(Aws::Utils::DateTime&& value) { m_prePassStartTime = std::move(value); } /** * <p>Amount of time prior to contact start you’d like to receive a CloudWatch * event indicating an upcoming pass.</p> */ inline DescribeContactResult& WithPrePassStartTime(const Aws::Utils::DateTime& value) { SetPrePassStartTime(value); return *this;} /** * <p>Amount of time prior to contact start you’d like to receive a CloudWatch * event indicating an upcoming pass.</p> */ inline DescribeContactResult& WithPrePassStartTime(Aws::Utils::DateTime&& value) { SetPrePassStartTime(std::move(value)); return *this;} /** * <p>Region of a contact.</p> */ inline const Aws::String& GetRegion() const{ return m_region; } /** * <p>Region of a contact.</p> */ inline void SetRegion(const Aws::String& value) { m_region = value; } /** * <p>Region of a contact.</p> */ inline void SetRegion(Aws::String&& value) { m_region = std::move(value); } /** * <p>Region of a contact.</p> */ inline void SetRegion(const char* value) { m_region.assign(value); } /** * <p>Region of a contact.</p> */ inline DescribeContactResult& WithRegion(const Aws::String& value) { SetRegion(value); return *this;} /** * <p>Region of a contact.</p> */ inline DescribeContactResult& WithRegion(Aws::String&& value) { SetRegion(std::move(value)); return *this;} /** * <p>Region of a contact.</p> */ inline DescribeContactResult& WithRegion(const char* value) { SetRegion(value); return *this;} /** * <p>ARN of a satellite.</p> */ inline const Aws::String& GetSatelliteArn() const{ return m_satelliteArn; } /** * <p>ARN of a satellite.</p> */ inline void SetSatelliteArn(const Aws::String& value) { m_satelliteArn = value; } /** * <p>ARN of a satellite.</p> */ inline void SetSatelliteArn(Aws::String&& value) { m_satelliteArn = std::move(value); } /** * <p>ARN of a satellite.</p> */ inline void SetSatelliteArn(const char* value) { m_satelliteArn.assign(value); } /** * <p>ARN of a satellite.</p> */ inline DescribeContactResult& WithSatelliteArn(const Aws::String& value) { SetSatelliteArn(value); return *this;} /** * <p>ARN of a satellite.</p> */ inline DescribeContactResult& WithSatelliteArn(Aws::String&& value) { SetSatelliteArn(std::move(value)); return *this;} /** * <p>ARN of a satellite.</p> */ inline DescribeContactResult& WithSatelliteArn(const char* value) { SetSatelliteArn(value); return *this;} /** * <p>Start time of a contact.</p> */ inline const Aws::Utils::DateTime& GetStartTime() const{ return m_startTime; } /** * <p>Start time of a contact.</p> */ inline void SetStartTime(const Aws::Utils::DateTime& value) { m_startTime = value; } /** * <p>Start time of a contact.</p> */ inline void SetStartTime(Aws::Utils::DateTime&& value) { m_startTime = std::move(value); } /** * <p>Start time of a contact.</p> */ inline DescribeContactResult& WithStartTime(const Aws::Utils::DateTime& value) { SetStartTime(value); return *this;} /** * <p>Start time of a contact.</p> */ inline DescribeContactResult& WithStartTime(Aws::Utils::DateTime&& value) { SetStartTime(std::move(value)); return *this;} /** * <p>Tags assigned to a contact.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; } /** * <p>Tags assigned to a contact.</p> */ inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tags = value; } /** * <p>Tags assigned to a contact.</p> */ inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tags = std::move(value); } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;} /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;} /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(const Aws::String& key, const Aws::String& value) { m_tags.emplace(key, value); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(Aws::String&& key, const Aws::String& value) { m_tags.emplace(std::move(key), value); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(const Aws::String& key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(Aws::String&& key, Aws::String&& value) { m_tags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(const char* key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(Aws::String&& key, const char* value) { m_tags.emplace(std::move(key), value); return *this; } /** * <p>Tags assigned to a contact.</p> */ inline DescribeContactResult& AddTags(const char* key, const char* value) { m_tags.emplace(key, value); return *this; } private: Aws::String m_contactId; ContactStatus m_contactStatus; Aws::Vector<DataflowDetail> m_dataflowList; Aws::Utils::DateTime m_endTime; Aws::String m_errorMessage; Aws::String m_groundStation; Elevation m_maximumElevation; Aws::String m_missionProfileArn; Aws::Utils::DateTime m_postPassEndTime; Aws::Utils::DateTime m_prePassStartTime; Aws::String m_region; Aws::String m_satelliteArn; Aws::Utils::DateTime m_startTime; Aws::Map<Aws::String, Aws::String> m_tags; }; } // namespace Model } // namespace GroundStation } // namespace Aws
32.206093
149
0.646041
[ "vector", "model" ]
37e49ca100bb6f154922ed3f4cf75be8119dc422
9,409
h
C
src/gui/symbology/qgsrendererwidget.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/gui/symbology/qgsrendererwidget.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/gui/symbology/qgsrendererwidget.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsrendererwidget.h --------------------- begin : November 2009 copyright : (C) 2009 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSRENDERERWIDGET_H #define QGSRENDERERWIDGET_H #include <QWidget> #include <QMenu> #include <QStackedWidget> #include "qgssymbol.h" #include "qgspanelwidget.h" #include "qgssymbolwidgetcontext.h" #include "qgssymbollayer.h" class QgsDataDefinedSizeLegend; class QgsDataDefinedSizeLegendWidget; class QgsVectorLayer; class QgsStyle; class QgsFeatureRenderer; class QgsMapCanvas; /** * \ingroup gui Base class for renderer settings widgets WORKFLOW: - open renderer dialog with some RENDERER (never null!) - find out which widget to use - instantiate it and set in stacked widget - on any change of renderer type, create some default (dummy?) version and change the stacked widget - when clicked OK/Apply, get the renderer from active widget and clone it for the layer */ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget { Q_OBJECT public: QgsRendererWidget( QgsVectorLayer *layer, QgsStyle *style ); //! Returns pointer to the renderer (no transfer of ownership) virtual QgsFeatureRenderer *renderer() = 0; //! show a dialog with renderer's symbol level settings void showSymbolLevelsDialog( QgsFeatureRenderer *r ); /** * Sets the context in which the renderer widget is shown, e.g., the associated map canvas and expression contexts. * \param context symbol widget context * \see context() * \since QGIS 3.0 */ virtual void setContext( const QgsSymbolWidgetContext &context ); /** * Returns the context in which the renderer widget is shown, e.g., the associated map canvas and expression contexts. * \see setContext() * \since QGIS 3.0 */ QgsSymbolWidgetContext context() const; /** * Returns the vector layer associated with the widget. * \since QGIS 2.12 */ const QgsVectorLayer *vectorLayer() const { return mLayer; } /** * This method should be called whenever the renderer is actually set on the layer. */ void applyChanges(); signals: /** * Emitted when expression context variables on the associated * vector layers have been changed. Will request the parent dialog * to re-synchronize with the variables. */ void layerVariablesChanged(); protected: QgsVectorLayer *mLayer = nullptr; QgsStyle *mStyle = nullptr; QMenu *contextMenu = nullptr; QAction *mCopyAction = nullptr; QAction *mPasteAction = nullptr; //! Context in which widget is shown QgsSymbolWidgetContext mContext; /** * Subclasses may provide the capability of changing multiple symbols at once by implementing the following two methods and by connecting the slot contextMenuViewCategories(const QPoint&)*/ virtual QList<QgsSymbol *> selectedSymbols() { return QList<QgsSymbol *>(); } virtual void refreshSymbolView() {} /** * Creates widget to setup data-defined size legend. * Returns newly created panel - may be NULLPTR if it could not be opened. Ownership is transferred to the caller. * \since QGIS 3.0 */ QgsDataDefinedSizeLegendWidget *createDataDefinedSizeLegendWidget( const QgsMarkerSymbol *symbol, const QgsDataDefinedSizeLegend *ddsLegend ) SIP_FACTORY; protected slots: void contextMenuViewCategories( QPoint p ); //! Change color of selected symbols void changeSymbolColor(); //! Change opacity of selected symbols void changeSymbolOpacity(); //! Change units mm/map units of selected symbols void changeSymbolUnit(); //! Change line widths of selected symbols void changeSymbolWidth(); //! Change marker sizes of selected symbols void changeSymbolSize(); //! Change marker angles of selected symbols void changeSymbolAngle(); virtual void copy() {} virtual void paste() {} private: /** * This will be called whenever the renderer is set on a layer. * This can be overwritten in subclasses. */ virtual void apply() SIP_FORCE; }; //////////// #include <QObject> class QMenu; class QgsField; class QgsFields; #include "ui_widget_set_dd_value.h" #include "qgis_gui.h" /** * \ingroup gui Utility classes for "en masse" size definition */ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataDefinedValueBaseDialog, private QgsExpressionContextGenerator { Q_OBJECT public: /** * Constructor * \param symbolList must not be empty * \param layer must not be NULLPTR * \param label value label */ QgsDataDefinedValueDialog( const QList<QgsSymbol *> &symbolList, QgsVectorLayer *layer, const QString &label ); /** * Sets the context in which the symbol widget is shown, e.g., the associated map canvas and expression contexts. * \param context symbol widget context * \see context() * \since QGIS 3.0 */ void setContext( const QgsSymbolWidgetContext &context ); /** * Returns the context in which the symbol widget is shown, e.g., the associated map canvas and expression contexts. * \see setContext() * \since QGIS 3.0 */ QgsSymbolWidgetContext context() const; /** * Returns the vector layer associated with the widget. * \since QGIS 2.12 */ const QgsVectorLayer *vectorLayer() const { return mLayer; } public slots: void dataDefinedChanged(); protected: /** * Should be called in the constructor of child classes. * * \note May be missing Python bindings depending on the platform. */ void init( int propertyKey ); // needed in children ctor to call virtual private: QgsProperty symbolDataDefined() const SIP_FORCE; virtual QgsProperty symbolDataDefined( const QgsSymbol * ) const = 0 SIP_FORCE; virtual double value( const QgsSymbol * ) const = 0 SIP_FORCE; virtual void setDataDefined( QgsSymbol *symbol, const QgsProperty &dd ) = 0 SIP_FORCE; QList<QgsSymbol *> mSymbolList; QgsVectorLayer *mLayer = nullptr; QgsSymbolWidgetContext mContext; QgsExpressionContext createExpressionContext() const override; }; /** * \ingroup gui * \class QgsDataDefinedSizeDialog */ class GUI_EXPORT QgsDataDefinedSizeDialog : public QgsDataDefinedValueDialog { Q_OBJECT public: QgsDataDefinedSizeDialog( const QList<QgsSymbol *> &symbolList, QgsVectorLayer *layer ) : QgsDataDefinedValueDialog( symbolList, layer, tr( "Size" ) ) { init( QgsSymbolLayer::PropertySize ); if ( !symbolList.isEmpty() && symbolList.at( 0 ) && vectorLayer() ) { mAssistantSymbol.reset( static_cast<const QgsMarkerSymbol *>( symbolList.at( 0 ) )->clone() ); mDDBtn->setSymbol( mAssistantSymbol ); } } protected: QgsProperty symbolDataDefined( const QgsSymbol *symbol ) const override; double value( const QgsSymbol *symbol ) const override { return static_cast<const QgsMarkerSymbol *>( symbol )->size(); } void setDataDefined( QgsSymbol *symbol, const QgsProperty &dd ) override; private: std::shared_ptr< QgsMarkerSymbol > mAssistantSymbol; }; /** * \ingroup gui * \class QgsDataDefinedRotationDialog */ class GUI_EXPORT QgsDataDefinedRotationDialog : public QgsDataDefinedValueDialog { Q_OBJECT public: QgsDataDefinedRotationDialog( const QList<QgsSymbol *> &symbolList, QgsVectorLayer *layer ) : QgsDataDefinedValueDialog( symbolList, layer, tr( "Rotation" ) ) { init( QgsSymbolLayer::PropertyAngle ); } protected: QgsProperty symbolDataDefined( const QgsSymbol *symbol ) const override; double value( const QgsSymbol *symbol ) const override { return static_cast<const QgsMarkerSymbol *>( symbol )->angle(); } void setDataDefined( QgsSymbol *symbol, const QgsProperty &dd ) override; }; /** * \ingroup gui * \class QgsDataDefinedWidthDialog */ class GUI_EXPORT QgsDataDefinedWidthDialog : public QgsDataDefinedValueDialog { Q_OBJECT public: QgsDataDefinedWidthDialog( const QList<QgsSymbol *> &symbolList, QgsVectorLayer *layer ) : QgsDataDefinedValueDialog( symbolList, layer, tr( "Width" ) ) { init( QgsSymbolLayer::PropertyStrokeWidth ); } protected: QgsProperty symbolDataDefined( const QgsSymbol *symbol ) const override; double value( const QgsSymbol *symbol ) const override { return static_cast<const QgsLineSymbol *>( symbol )->width(); } void setDataDefined( QgsSymbol *symbol, const QgsProperty &dd ) override; }; #endif // QGSRENDERERWIDGET_H
31.259136
158
0.669678
[ "vector" ]
37ed5bd23d32800fc9666c96a4119068c94c012a
4,463
h
C
Library/Sources/Stroika/Foundation/Containers/STL/Utilities.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Containers/STL/Utilities.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Containers/STL/Utilities.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Containers_STL_Utilities_h_ #define _Stroika_Foundation_Containers_STL_Utilities_h_ 1 #include "../../StroikaPreComp.h" #include <set> #include <vector> #include "../../Common/Compare.h" #include "../../Configuration/Common.h" /** * \file * * \version <a href="Code-Status.md#Alpha-Late">Alpha-Late</a> * * TODO: * */ namespace Stroika::Foundation::Containers::STL { /** * \note similar to std::equal () - but takes iterables as arguments, not iterators */ template <typename ITERABLE_OF_T, typename T = typename ITERABLE_OF_T::value_type, typename EQUALS_COMPARER = equal_to<T>, enable_if_t<Common::IsPotentiallyComparerRelation<T, EQUALS_COMPARER> ()>* = nullptr> bool equal (const ITERABLE_OF_T& lhs, const ITERABLE_OF_T& rhs, EQUALS_COMPARER&& equalsComparer = {}); /* * STL container constructors take a begin/end combo, but no CONTAINER ctor (except for same as starting). * So to convert from set<T> to vector<T> is a pain (if you have a function returning set<>). To do pretty * easily with STL, you need a named temporary. Thats basically all this helper function does. * * So instead of: * set<T> tmp = funCall_returning_set(); * vector<T> realAnswer = vector<T> (tmp.begin (), tmp.end ()); * * You can write: * vector<T> realAnswer = STL::Make<vector<T>> (funCall_returning_set()); */ template <typename CREATE_CONTAINER_TYPE, typename FROM_CONTAINER_TYPE> CREATE_CONTAINER_TYPE Make (const FROM_CONTAINER_TYPE& rhs); /** * Though you can append to a vector<> with * insert (this->begin (), arg.begin (), arg.end ()) * That's awkward if 'arg' is an unnamed value - say the result of a function. You must * assign to a named temporary. This helper makes that unneeded. */ template <typename TARGET_CONTAINER> void Append (TARGET_CONTAINER* v); template <typename TARGET_CONTAINER, typename SRC_CONTAINER> void Append (TARGET_CONTAINER* v, const SRC_CONTAINER& v2); template <typename TARGET_CONTAINER, typename SRC_CONTAINER, typename... Args> void Append (TARGET_CONTAINER* v, const SRC_CONTAINER& v2, Args... args); /** * \brief construct a new STL container by concatenating the args together. * * \note Hard to believe this is so awkward in STL! * * @see Concatenate */ template <typename TARGET_CONTAINER, typename SRC_CONTAINER, typename... Args> TARGET_CONTAINER Concat (const SRC_CONTAINER& v2, Args... args); /** * \brief construct a new vector<T> by concatenating the args together. Alias for Concat<vector<typename SRC_CONTAINER::value_type>> () * * @see Concat */ template <typename SRC_CONTAINER, typename... Args> vector<typename SRC_CONTAINER::value_type> Concatenate (const SRC_CONTAINER& v2, Args... args); /** * Returns true if the intersetion of s1 and s2 is non-empty */ template <typename T> bool Intersects (const set<T>& s1, const set<T>& s2); /** *@todo - redo with RHS as arbirrary container. Probably redo with stroika Set<> // maybe osbolete cuz can alway use // (Containers::Set<T> (s1) & s2).As<vector<T>> () */ template <typename T> set<T> Intersection (const set<T>& s1, const set<T>& s2); template <typename T> void Intersection (set<T>* s1, const set<T>& s2); template <typename T> vector<T> Intersection (const vector<T>& s1, const vector<T>& s2); /** */ template <typename T, typename FROMCONTAINER> void Union (set<T>* s1, const FROMCONTAINER& s2); template <typename T, typename FROMCONTAINER> set<T> Union (const set<T>& s1, const FROMCONTAINER& s2); /** */ template <typename T, typename FROMCONTAINER> void Difference (set<T>* s1, const FROMCONTAINER& s2); template <typename T, typename FROMCONTAINER> set<T> Difference (const set<T>& s1, const FROMCONTAINER& s2); } /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "Utilities.inl" #endif /*_Stroika_Foundation_Containers_STL_Utilities_h_*/
37.191667
212
0.636343
[ "vector" ]
37eedb9eb9d5b598cac8cded7a2f237172126830
4,342
h
C
marstd2/marstd.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:35.000Z
2020-05-20T12:31:35.000Z
marstd2/marstd.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
null
null
null
marstd2/marstd.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:40.000Z
2020-05-20T12:31:40.000Z
#ifndef __marstd_h__ #define __marstd_h__ ////////////////////////////////////////////////////////////////////// // MarSTD version 2004 - (c)2004 - Marcel Smit // // // // Marcel_Smit_101@hotmail.com // // marcel.athlon@hccnet.nl // // // // This code may not be used in a commercial product without my // // permission. If you redistribute it, this message must remain // // intact. If you use this code, some acknowledgement would be // // appreciated. ;-) // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** @file marstd.h: MarSTD main include file. */ ////////////////////////////////////////////////////////////////////// /** \mainpage MarSTD 2004 documentation <TT> //////////////////////////////////////////////////////////////////////<BR> // MarSTD version 2004 - (c)2004 - Marcel Smit <BR> // <BR> // Marcel_Smit_101@hotmail.com <BR> // marcel.athlon@hccnet.nl <BR> // <BR> // This code may not be used in a commercial product without my <BR> // permission. If you redistribute it, this message must remain <BR> // intact. If you use this code, some acknowledgement would be <BR> // appreciated. ;-) <BR> //////////////////////////////////////////////////////////////////////<BR> </TT> <BR> MarSTD is a librairy written by Marcel Smit that provides some basic classes to define and manipulate geometry. It also includes some math functions, geometry generators, geometry compilers, a general purpose file class, and more.<BR> <BR> Main features: - Many geometric primitives. - Advanced geometric operations like CSG and BSP tree construction. - Floating point stability. - Ease of use. - Quite robust and stable if I may say so. ;) Take a look at the examples for a good introduction to the librairy. Use these docs as a reference to fill in the gaps. The classes are all meant to be easy and natural to use.<BR> IMHO documentation generated from source code is generally quite poor and not a good starting point to learn use a librairy at all. So again, please take a look at the example code first. */ //#define MARSTD_3DNOW ///< Uncomment to use 3DNow! instructions. TODO: Implement 3DNow!. // DEBUG CODE #include "CDebug.h" // NEW CODE #include "CList.h" // dll: helper macros #include "CDynArray.h" // stack: helper macros #include "CVector.h" // geometry: vector #include "CVertex.h" // geometry: vertex #include "CSphere.h" // geometry: sphere #include "CPoly.h" // geometry: polygon, mesh #include "CMatrix.h" // math: 3x3 matrix and stack #include "CMatrix4.h" // math: 4x4 matrix and stack #include "CMath.h" // math: angle conversions, etc #include "CIsosurface.h" // geometry: metaballs #include "CFile.h" // io: file #include "CGeomBuilder.h" // geometry: primitives builder #include "CGeomCompiler.h" // geometry: geometry compiler #include "CBezier.h" // geometry: bezier patches #include "CCsg2D.h" // geometry: 2D csg #include "CCsg3D.h" // geometry: 3D csg // OLD CODE. DON'T USE! (YET) #include "CBsp.h" // bsp operations #include "CBrush.h" // geometry: brushes //#include "COctree.h" // geometry: octree #include "inline/CVertex.inl" #include "inline/CPoly.inl" //#include "inline/COctree.inl" #include "inline/CMatrix.inl" #include "inline/CMatrix4.inl" #include "inline/CIsosurface.inl" #include "inline/CGeomCompiler.inl" #include "inline/CGeomBuilder.inl" #include "inline/CBsp.inl" #include "inline/CBrush.inl" #include "inline/CBezier.inl" #include "inline/CCsg2D.inl" #include "inline/CCsg3D.inl" #endif
45.229167
132
0.52257
[ "mesh", "geometry", "vector", "3d" ]
37f4adb0c1a8ec962e3c4f1c92dfa3047ac242b4
7,625
h
C
PWGHF/vertexingHF/AliAnalysisTaskSEDStarCharmFraction.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGHF/vertexingHF/AliAnalysisTaskSEDStarCharmFraction.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGHF/vertexingHF/AliAnalysisTaskSEDStarCharmFraction.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
#ifndef ALIANALYSISTASKSEDSTARCHARMFRACTION_H #define ALIANALYSISTASKSEDSTARCHARMFRACTION_H /* Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ //************************************************************************* // Class AliAnalysisTaskSEDStarCharmFraction // AliAnalysisTask for the extraction of the fraction of prompt charm for D* // using the charm hadron impact parameter to the primary vertex // // Author: Jasper van der Maarel <J.vanderMaarel@uu.nl> //************************************************************************* class TH1D; class AliRDHFCutsDStartoKpipi; class AliNormalizationCounter; class TList; class AliAODRecoCascadeHF; class TClonesArray; class AliAODMCParticle; class AliAODEvent; class AliAODVertex; #include "AliAnalysisTaskSE.h" class AliAnalysisTaskSEDStarCharmFraction : public AliAnalysisTaskSE { public: AliAnalysisTaskSEDStarCharmFraction(); AliAnalysisTaskSEDStarCharmFraction(const char *name, AliRDHFCutsDStartoKpipi *cuts); virtual ~AliAnalysisTaskSEDStarCharmFraction(); // Implementation of interface methods virtual void UserCreateOutputObjects(); virtual void Init(); virtual void LocalInit() {Init();} virtual void UserExec(Option_t *option); virtual void Terminate(Option_t *option); void SetReadMC(Bool_t readMC = kTRUE) { fReadMC = readMC; } Bool_t GetReadMC() { return fReadMC; } void SetSkipHijing(Bool_t skipHijing = kTRUE) { fSkipHijing = skipHijing; } Bool_t GetSkipHijing() { return fSkipHijing; } void SetSingleSideband(Bool_t singleSideband = kTRUE) { fSingleSideband = singleSideband; } Bool_t GetSingleSideband() { return fSingleSideband; } void SetPeakCut(Double_t *peakCut) { for (Int_t i=0;i<fNPtBins;i++) { fPeakCut[i] = peakCut[i]; } } Double_t *GetPeakCut() { return fPeakCut; } void SetSidebandCut(Double_t *sidebandCut) { for (Int_t i=0;i<fNPtBins;i++) { fSidebandCut[i] = sidebandCut[i]; } } Double_t *GetSidebandCut() { return fSidebandCut; } void SetSidebandWindow(Double_t *sidebandWindow) { for (Int_t i=0;i<fNPtBins;i++) { fSidebandWindow[i] = sidebandWindow[i]; } } Double_t *GetSidebandWindow() { return fSidebandWindow; } void SetCuts(AliRDHFCutsDStartoKpipi *cuts) { fCuts = new AliRDHFCutsDStartoKpipi(*cuts); } AliRDHFCutsDStartoKpipi *GetCuts() { return fCuts; } void SetImpParCut(Double_t impParCut) { fImpParCut = TMath::Abs(impParCut); } Double_t GetImpParCut() { return fImpParCut; } private: AliRDHFCutsDStartoKpipi *fCuts; // Cut object AliNormalizationCounter *fCounter; // Counter for normalization Bool_t fReadMC; // Flag to switch on/off the access of MC Bool_t fSkipHijing; // Flag to switch on/off the skipping of D from Hijing Bool_t fSingleSideband; // Flag to switch on/off single sideband instead of double sideband Double_t fImpParCut; // Lower value for impact parameter cut Double_t fPDGMDStarD0; // Difference between masses of D* and D0 from PDG Int_t fNPtBins; // Number of pt bins TH1D *fNEvents; // Event count histogram TTree *fTreeCandidate; // Tree for D* candidates TList *fListCandidate; // List for D* candidates TList *fListSignal; // List for D* signal (MC) TList *fListSignalPrompt; // List for prompt D* (MC) TList *fListSignalFromB; // List for D* from B (MC) TList *fListBackground; // List for D* background (MC) Double_t fPeakCut[30]; // Max distance from delta inv mass for peak region Double_t fSidebandCut[30]; // Sideband region starts at this distance from peak Double_t fSidebandWindow[30]; // Size of sideband region Bool_t fIsSideband; // Candidate is in sideband Bool_t fIsPeak; // Candidate is in peak region Bool_t fIsSignal; // Candidate is actual D* (from MC) Bool_t fIsSignalPrompt; // Candidate is actual prompt D* (from MC) Bool_t fIsSignalFromB; // Candidate is actual D* from B (from MC) Bool_t fIsBackground; // Candidate is fake (from MC) AliAODVertex *fNewPrimVtx; // Newly determined primary vertex without D* daughters AliAODVertex *fDStarVtx; // D* vertex Double_t fMagneticField; // Magnetic field strength in current event Double_t fPtForTree; // Use this to fill pT branch Double_t fInvMassForTree; // Use this to fill invariant mass branch Double_t fImpParForTree; // Use this to fill impact parameter branch Double_t fTrueImpParForTree; // Use this to fill true impact parameter branch Short_t fTypeForTree; // Use this to fill the type branch (0=other, 1=peak, 2=SB left, 3=SB right) Short_t fSignalTypeForTree; // Use this to fill the signal type branch (data: -1, MC: 0=background, 1=signal prompt, 2=signal non-prompt) void SetUpList(TList *list); // Fill a TList with histograms void CheckInvMassDStar(AliAODRecoCascadeHF *cand); // Check if D* candidate falls within peak or sideband region Bool_t IsFromB(TClonesArray *arrayMC, const AliAODMCParticle *mcPartCandidate); // Check if the MC particle comes from a B Bool_t IsFromHijing(TClonesArray *arrayMC, const AliAODMCParticle *mcPartCandidate); // Check if the MC particle is from Hijing Bool_t CalculateImpactParameter(AliAODTrack *track, Double_t &d0, Double_t &d0Err); // Calculate impact parameter for a track Double_t CalculateImpactParameterDStar(AliAODRecoCascadeHF *cand); // Calculate impact parameter of the D* Double_t CalculateTrueImpactParameterDStar(AliAODMCHeader *headerMC, TClonesArray *arrayMC, AliAODRecoCascadeHF* cand); // Calculate true impact parameter of the D* void FillHistograms(AliAODRecoCascadeHF *cand); // Fill histograms for a D* candidate void FillHistogram(const char *name, Double_t value); // Fill a specific histogram in multiple lists void FillRegionHistogram(const char *name, Double_t value); // Fill a specific histogram in multiple lists, in the approprate regions (all, peak region, sideband region) void FillTrueImpactParameter(AliAODRecoCascadeHF* cand); // Fill histogram with true impact parameter distribution for D from B AliAODVertex *RemoveDaughtersFromPrimaryVtx(AliAODEvent *aod, AliAODRecoCascadeHF *cand); // Determine primary vertex without D* daughters AliAODVertex *ReconstructDStarVtx(AliAODRecoCascadeHF *cand); //Determine the D* vertex AliAnalysisTaskSEDStarCharmFraction(const AliAnalysisTaskSEDStarCharmFraction&); // Not implemented AliAnalysisTaskSEDStarCharmFraction& operator=(const AliAnalysisTaskSEDStarCharmFraction&); // Not implemented ClassDef(AliAnalysisTaskSEDStarCharmFraction, 2); // Analysis task for D* prompt charm fraction }; #endif
65.17094
173
0.65023
[ "object" ]
37f5e25388dc6062d27fb60cf120a1aea692d2c0
3,024
h
C
Sonora/Classes/NSManagedObjectContext-SNRAdditions.h
cyg02032015/Sonora
0e9c031c3924bf7b30cca448e064ba38f612e03f
[ "BSD-3-Clause" ]
470
2015-01-10T19:08:56.000Z
2022-03-28T11:43:40.000Z
Sonora/Classes/NSManagedObjectContext-SNRAdditions.h
cyg02032015/Sonora
0e9c031c3924bf7b30cca448e064ba38f612e03f
[ "BSD-3-Clause" ]
12
2015-01-21T19:31:40.000Z
2019-05-29T05:50:47.000Z
Sonora/Classes/NSManagedObjectContext-SNRAdditions.h
cyg02032015/Sonora
0e9c031c3924bf7b30cca448e064ba38f612e03f
[ "BSD-3-Clause" ]
78
2015-01-19T11:32:23.000Z
2022-02-21T20:16:58.000Z
/* * Copyright (C) 2012 Indragie Karunaratne <i@indragie.com> * 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 Indragie Karunaratne nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import "SNRArtist.h" #import "SNRAlbum.h" #import "SNRMix.h" #import "SNRSong.h" extern NSString* const kCompilationsArtistName; @interface NSManagedObjectContext (SNRAdditions) #pragma mark - General Convenience - (BOOL)saveChanges; - (id)createObjectOfEntityName:(NSString*)entityName; - (BOOL)deleteObjects:(NSArray*)objects ofEntity:(NSString*)entity; - (NSArray*)fetchObjectsOfEntity:(NSString*)entity sortDescriptors:(NSArray*)descriptors predicate:(NSPredicate*)predicate batchSize:(NSUInteger)batchSize fetchLimit:(NSUInteger)limit relationshipKeyPathsForPrefetching:(NSArray*)keypaths; #pragma mark - Artists - (SNRArtist*)artistWithName:(NSString*)name create:(BOOL)create; - (SNRArtist*)compilationsArtist; #pragma mark - Albums - (SNRAlbum*)albumWithName:(NSString*)name byArtist:(SNRArtist*)artist create:(BOOL)create; #pragma mark - Mixes - (SNRMix*)mixWithiTunesPersistentID:(NSString*)iTunesPersistentID; - (NSUInteger)numberOfMixes; #pragma mark - Songs - (SNRSong*)songWithiTunesPersistentID:(NSString*)iTunesPersistentID; - (NSArray*)songsWithName:(NSString*)name albumName:(NSString*)albumName artistName:(NSString*)artistName; - (NSArray*)songsAtSourcePath:(NSString*)path; #pragma mark - Object Conversions - (NSArray*)objectsWithIDs:(NSArray*)ids; - (NSArray*)objectsWithURLs:(NSArray*)urls; - (NSArray*)objectsWithURLStrings:(NSArray*)strings; @end
42.591549
238
0.769841
[ "object" ]
5305dc81d2492f86f2debc4d8634d3f6e5796c51
41,845
h
C
external/webkit/Source/WebKit/android/plugins/android_npapi.h
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-05-19T08:53:12.000Z
2017-08-28T11:59:26.000Z
external/webkit/Source/WebKit/android/plugins/android_npapi.h
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
external/webkit/Source/WebKit/android/plugins/android_npapi.h
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
/* * Copyright 2009, The Android Open Source Project * * 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. * * 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. */ /* Defines the android-specific types and functions as part of npapi In particular, defines the window and event types that are passed to NPN_GetValue, NPP_SetWindow and NPP_HandleEvent. To minimize what native libraries the plugin links against, some functionality is provided via function-ptrs (e.g. time, sound) */ #ifndef android_npapi_h #define android_npapi_h #include <stdint.h> #include "npapi.h" /////////////////////////////////////////////////////////////////////////////// // General types enum ANPBitmapFormats { kUnknown_ANPBitmapFormat = 0, kRGBA_8888_ANPBitmapFormat = 1, kRGB_565_ANPBitmapFormat = 2 }; typedef int32_t ANPBitmapFormat; struct ANPPixelPacking { uint8_t AShift; uint8_t ABits; uint8_t RShift; uint8_t RBits; uint8_t GShift; uint8_t GBits; uint8_t BShift; uint8_t BBits; }; struct ANPBitmap { void* baseAddr; ANPBitmapFormat format; int32_t width; int32_t height; int32_t rowBytes; }; struct ANPRectF { float left; float top; float right; float bottom; }; struct ANPRectI { int32_t left; int32_t top; int32_t right; int32_t bottom; }; struct ANPCanvas; struct ANPMatrix; struct ANPPaint; struct ANPPath; struct ANPRegion; struct ANPTypeface; enum ANPMatrixFlags { kIdentity_ANPMatrixFlag = 0, kTranslate_ANPMatrixFlag = 0x01, kScale_ANPMatrixFlag = 0x02, kAffine_ANPMatrixFlag = 0x04, kPerspective_ANPMatrixFlag = 0x08, }; typedef uint32_t ANPMatrixFlag; /////////////////////////////////////////////////////////////////////////////// // NPN_GetValue /** queries for a specific ANPInterface. Maybe called with NULL for the NPP instance NPN_GetValue(inst, interface_enum, ANPInterface*) */ #define kLogInterfaceV0_ANPGetValue ((NPNVariable)1000) #define kAudioTrackInterfaceV0_ANPGetValue ((NPNVariable)1001) #define kCanvasInterfaceV0_ANPGetValue ((NPNVariable)1002) #define kMatrixInterfaceV0_ANPGetValue ((NPNVariable)1003) #define kPaintInterfaceV0_ANPGetValue ((NPNVariable)1004) #define kPathInterfaceV0_ANPGetValue ((NPNVariable)1005) #define kTypefaceInterfaceV0_ANPGetValue ((NPNVariable)1006) #define kWindowInterfaceV0_ANPGetValue ((NPNVariable)1007) #define kBitmapInterfaceV0_ANPGetValue ((NPNVariable)1008) #define kSurfaceInterfaceV0_ANPGetValue ((NPNVariable)1009) #define kSystemInterfaceV0_ANPGetValue ((NPNVariable)1010) #define kEventInterfaceV0_ANPGetValue ((NPNVariable)1011) #define kAudioTrackInterfaceV1_ANPGetValue ((NPNVariable)1012) #define kOpenGLInterfaceV0_ANPGetValue ((NPNVariable)1013) #define kWindowInterfaceV1_ANPGetValue ((NPNVariable)1014) #define kVideoInterfaceV0_ANPGetValue ((NPNVariable)1015) #define kSystemInterfaceV1_ANPGetValue ((NPNVariable)1016) #define kSystemInterfaceV2_ANPGetValue ((NPNVariable)1017) #define kWindowInterfaceV2_ANPGetValue ((NPNVariable)1018) #define kNativeWindowInterfaceV0_ANPGetValue ((NPNVariable)1019) #define kVideoInterfaceV1_ANPGetValue ((NPNVariable)1020) /** queries for the drawing models supported on this device. NPN_GetValue(inst, kSupportedDrawingModel_ANPGetValue, uint32_t* bits) */ #define kSupportedDrawingModel_ANPGetValue ((NPNVariable)2000) /** queries for the context (android.content.Context) of the plugin. If no instance is specified the application's context is returned. If the instance is given then the context returned is identical to the context used to create the webview in which that instance resides. NOTE: Holding onto a non-application context after your instance has been destroyed will cause a memory leak. Refer to the android documentation to determine what context is best suited for your particular scenario. NPN_GetValue(inst, kJavaContext_ANPGetValue, jobject context) */ #define kJavaContext_ANPGetValue ((NPNVariable)2001) /////////////////////////////////////////////////////////////////////////////// // NPN_SetValue /** Request to set the drawing model. SetValue will return false if the drawing model is not supported or has insufficient information for configuration. NPN_SetValue(inst, kRequestDrawingModel_ANPSetValue, (void*)foo_ANPDrawingModel) */ #define kRequestDrawingModel_ANPSetValue ((NPPVariable)1000) /** These are used as bitfields in ANPSupportedDrawingModels_EnumValue, and as-is in ANPRequestDrawingModel_EnumValue. The drawing model determines how to interpret the ANPDrawingContext provided in the Draw event and how to interpret the NPWindow->window field. */ enum ANPDrawingModels { /** Draw into a bitmap from the browser thread in response to a Draw event. NPWindow->window is reserved (ignore) */ kBitmap_ANPDrawingModel = 1 << 0, /** Draw into a surface (e.g. raster, openGL, etc.) using the Java surface interface. When this model is used the browser will invoke the Java class specified in the plugin's apk manifest. From that class the browser will invoke the appropriate method to return an an instance of a android Java View. The instance is then embedded in the html. The plugin can then manipulate the view as it would any normal Java View in android. Unlike the bitmap model, a surface model is opaque so no html content behind the plugin will be visible. Unless the plugin needs to be transparent the surface model should be chosen over the bitmap model as it will have better performance. Further, a plugin can manipulate some surfaces in native code using the ANPSurfaceInterface. This interface can be used to manipulate Java objects that extend Surface.class by allowing them to access the surface's underlying bitmap in native code. For instance, if a raster surface is used the plugin can lock, draw directly into the bitmap, and unlock the surface in native code without making JNI calls to the Java surface object. */ kSurface_ANPDrawingModel = 1 << 1, kOpenGL_ANPDrawingModel = 1 << 2, }; typedef int32_t ANPDrawingModel; /** Request to receive/disable events. If the pointer is NULL then all flags will be disabled. Otherwise, the event type will be enabled iff its corresponding bit in the EventFlags bit field is set. NPN_SetValue(inst, ANPAcceptEvents, (void*)EventFlags) */ #define kAcceptEvents_ANPSetValue ((NPPVariable)1001) /** The EventFlags are a set of bits used to determine which types of events the plugin wishes to receive. For example, if the value is 0x03 then both key and touch events will be provided to the plugin. */ enum ANPEventFlag { kKey_ANPEventFlag = 0x01, kTouch_ANPEventFlag = 0x02, }; typedef uint32_t ANPEventFlags; /////////////////////////////////////////////////////////////////////////////// // NPP_GetValue /** Requests that the plugin return a java surface to be displayed. This will only be used if the plugin has choosen the kSurface_ANPDrawingModel. NPP_GetValue(inst, kJavaSurface_ANPGetValue, jobject surface) */ #define kJavaSurface_ANPGetValue ((NPPVariable)2000) /////////////////////////////////////////////////////////////////////////////// // ANDROID INTERFACE DEFINITIONS /** Interfaces provide additional functionality to the plugin via function ptrs. Once an interface is retrieved, it is valid for the lifetime of the plugin (just like browserfuncs). All ANPInterfaces begin with an inSize field, which must be set by the caller (plugin) with the number of bytes allocated for the interface. e.g. SomeInterface si; si.inSize = sizeof(si); browser->getvalue(..., &si); */ struct ANPInterface { uint32_t inSize; // size (in bytes) of this struct }; enum ANPLogTypes { kError_ANPLogType = 0, // error kWarning_ANPLogType = 1, // warning kDebug_ANPLogType = 2 // debug only (informational) }; typedef int32_t ANPLogType; struct ANPLogInterfaceV0 : ANPInterface { /** dumps printf messages to the log file e.g. interface->log(instance, kWarning_ANPLogType, "value is %d", value); */ void (*log)(ANPLogType, const char format[], ...); }; struct ANPBitmapInterfaceV0 : ANPInterface { /** Returns true if the specified bitmap format is supported, and if packing is non-null, sets it to the packing info for that format. */ bool (*getPixelPacking)(ANPBitmapFormat, ANPPixelPacking* packing); }; struct ANPMatrixInterfaceV0 : ANPInterface { /** Return a new identity matrix */ ANPMatrix* (*newMatrix)(); /** Delete a matrix previously allocated by newMatrix() */ void (*deleteMatrix)(ANPMatrix*); ANPMatrixFlag (*getFlags)(const ANPMatrix*); void (*copy)(ANPMatrix* dst, const ANPMatrix* src); /** Return the matrix values in a float array (allcoated by the caller), where the values are treated as follows: w = x * [6] + y * [7] + [8]; x' = (x * [0] + y * [1] + [2]) / w; y' = (x * [3] + y * [4] + [5]) / w; */ void (*get3x3)(const ANPMatrix*, float[9]); /** Initialize the matrix from values in a float array, where the values are treated as follows: w = x * [6] + y * [7] + [8]; x' = (x * [0] + y * [1] + [2]) / w; y' = (x * [3] + y * [4] + [5]) / w; */ void (*set3x3)(ANPMatrix*, const float[9]); void (*setIdentity)(ANPMatrix*); void (*preTranslate)(ANPMatrix*, float tx, float ty); void (*postTranslate)(ANPMatrix*, float tx, float ty); void (*preScale)(ANPMatrix*, float sx, float sy); void (*postScale)(ANPMatrix*, float sx, float sy); void (*preSkew)(ANPMatrix*, float kx, float ky); void (*postSkew)(ANPMatrix*, float kx, float ky); void (*preRotate)(ANPMatrix*, float degrees); void (*postRotate)(ANPMatrix*, float degrees); void (*preConcat)(ANPMatrix*, const ANPMatrix*); void (*postConcat)(ANPMatrix*, const ANPMatrix*); /** Return true if src is invertible, and if so, return its inverse in dst. If src is not invertible, return false and ignore dst. */ bool (*invert)(ANPMatrix* dst, const ANPMatrix* src); /** Transform the x,y pairs in src[] by this matrix, and store the results in dst[]. The count parameter is treated as the number of pairs in the array. It is legal for src and dst to point to the same memory, but illegal for the two arrays to partially overlap. */ void (*mapPoints)(ANPMatrix*, float dst[], const float src[], int32_t count); }; struct ANPPathInterfaceV0 : ANPInterface { /** Return a new path */ ANPPath* (*newPath)(); /** Delete a path previously allocated by ANPPath() */ void (*deletePath)(ANPPath*); /** Make a deep copy of the src path, into the dst path (already allocated by the caller). */ void (*copy)(ANPPath* dst, const ANPPath* src); /** Returns true if the two paths are the same (i.e. have the same points) */ bool (*equal)(const ANPPath* path0, const ANPPath* path1); /** Remove any previous points, initializing the path back to empty. */ void (*reset)(ANPPath*); /** Return true if the path is empty (has no lines, quads or cubics). */ bool (*isEmpty)(const ANPPath*); /** Return the path's bounds in bounds. */ void (*getBounds)(const ANPPath*, ANPRectF* bounds); void (*moveTo)(ANPPath*, float x, float y); void (*lineTo)(ANPPath*, float x, float y); void (*quadTo)(ANPPath*, float x0, float y0, float x1, float y1); void (*cubicTo)(ANPPath*, float x0, float y0, float x1, float y1, float x2, float y2); void (*close)(ANPPath*); /** Offset the src path by [dx, dy]. If dst is null, apply the change directly to the src path. If dst is not null, write the changed path into dst, and leave the src path unchanged. In that case dst must have been previously allocated by the caller. */ void (*offset)(ANPPath* src, float dx, float dy, ANPPath* dst); /** Transform the path by the matrix. If dst is null, apply the change directly to the src path. If dst is not null, write the changed path into dst, and leave the src path unchanged. In that case dst must have been previously allocated by the caller. */ void (*transform)(ANPPath* src, const ANPMatrix*, ANPPath* dst); }; /** ANPColor is always defined to have the same packing on all platforms, and it is always unpremultiplied. This is in contrast to 32bit format(s) in bitmaps, which are premultiplied, and their packing may vary depending on the platform, hence the need for ANPBitmapInterface::getPixelPacking() */ typedef uint32_t ANPColor; #define ANPColor_ASHIFT 24 #define ANPColor_RSHIFT 16 #define ANPColor_GSHIFT 8 #define ANPColor_BSHIFT 0 #define ANP_MAKE_COLOR(a, r, g, b) \ (((a) << ANPColor_ASHIFT) | \ ((r) << ANPColor_RSHIFT) | \ ((g) << ANPColor_GSHIFT) | \ ((b) << ANPColor_BSHIFT)) enum ANPPaintFlag { kAntiAlias_ANPPaintFlag = 1 << 0, kFilterBitmap_ANPPaintFlag = 1 << 1, kDither_ANPPaintFlag = 1 << 2, kUnderlineText_ANPPaintFlag = 1 << 3, kStrikeThruText_ANPPaintFlag = 1 << 4, kFakeBoldText_ANPPaintFlag = 1 << 5, }; typedef uint32_t ANPPaintFlags; enum ANPPaintStyles { kFill_ANPPaintStyle = 0, kStroke_ANPPaintStyle = 1, kFillAndStroke_ANPPaintStyle = 2 }; typedef int32_t ANPPaintStyle; enum ANPPaintCaps { kButt_ANPPaintCap = 0, kRound_ANPPaintCap = 1, kSquare_ANPPaintCap = 2 }; typedef int32_t ANPPaintCap; enum ANPPaintJoins { kMiter_ANPPaintJoin = 0, kRound_ANPPaintJoin = 1, kBevel_ANPPaintJoin = 2 }; typedef int32_t ANPPaintJoin; enum ANPPaintAligns { kLeft_ANPPaintAlign = 0, kCenter_ANPPaintAlign = 1, kRight_ANPPaintAlign = 2 }; typedef int32_t ANPPaintAlign; enum ANPTextEncodings { kUTF8_ANPTextEncoding = 0, kUTF16_ANPTextEncoding = 1, }; typedef int32_t ANPTextEncoding; enum ANPTypefaceStyles { kBold_ANPTypefaceStyle = 1 << 0, kItalic_ANPTypefaceStyle = 1 << 1 }; typedef uint32_t ANPTypefaceStyle; typedef uint32_t ANPFontTableTag; struct ANPFontMetrics { /** The greatest distance above the baseline for any glyph (will be <= 0) */ float fTop; /** The recommended distance above the baseline (will be <= 0) */ float fAscent; /** The recommended distance below the baseline (will be >= 0) */ float fDescent; /** The greatest distance below the baseline for any glyph (will be >= 0) */ float fBottom; /** The recommended distance to add between lines of text (will be >= 0) */ float fLeading; }; struct ANPTypefaceInterfaceV0 : ANPInterface { /** Return a new reference to the typeface that most closely matches the requested name and style. Pass null as the name to return the default font for the requested style. Will never return null The 5 generic font names "serif", "sans-serif", "monospace", "cursive", "fantasy" are recognized, and will be mapped to their logical font automatically by this call. @param name May be NULL. The name of the font family. @param style The style (normal, bold, italic) of the typeface. @return reference to the closest-matching typeface. Caller must call unref() when they are done with the typeface. */ ANPTypeface* (*createFromName)(const char name[], ANPTypefaceStyle); /** Return a new reference to the typeface that most closely matches the requested typeface and specified Style. Use this call if you want to pick a new style from the same family of the existing typeface. If family is NULL, this selects from the default font's family. @param family May be NULL. The name of the existing type face. @param s The style (normal, bold, italic) of the type face. @return reference to the closest-matching typeface. Call must call unref() when they are done. */ ANPTypeface* (*createFromTypeface)(const ANPTypeface* family, ANPTypefaceStyle); /** Return the owner count of the typeface. A newly created typeface has an owner count of 1. When the owner count is reaches 0, the typeface is deleted. */ int32_t (*getRefCount)(const ANPTypeface*); /** Increment the owner count on the typeface */ void (*ref)(ANPTypeface*); /** Decrement the owner count on the typeface. When the count goes to 0, the typeface is deleted. */ void (*unref)(ANPTypeface*); /** Return the style bits for the specified typeface */ ANPTypefaceStyle (*getStyle)(const ANPTypeface*); /** Some fonts are stored in files. If that is true for the fontID, then this returns the byte length of the full file path. If path is not null, then the full path is copied into path (allocated by the caller), up to length bytes. If index is not null, then it is set to the truetype collection index for this font, or 0 if the font is not in a collection. Note: getFontPath does not assume that path is a null-terminated string, so when it succeeds, it only copies the bytes of the file name and nothing else (i.e. it copies exactly the number of bytes returned by the function. If the caller wants to treat path[] as a C string, it must be sure that it is allocated at least 1 byte larger than the returned size, and it must copy in the terminating 0. If the fontID does not correspond to a file, then the function returns 0, and the path and index parameters are ignored. @param fontID The font whose file name is being queried @param path Either NULL, or storage for receiving up to length bytes of the font's file name. Allocated by the caller. @param length The maximum space allocated in path (by the caller). Ignored if path is NULL. @param index Either NULL, or receives the TTC index for this font. If the font is not a TTC, then will be set to 0. @return The byte length of th font's file name, or 0 if the font is not baked by a file. */ int32_t (*getFontPath)(const ANPTypeface*, char path[], int32_t length, int32_t* index); /** Return a UTF8 encoded path name for the font directory, or NULL if not supported. If returned, this string address will be valid for the life of the plugin instance. It will always end with a '/' character. */ const char* (*getFontDirectoryPath)(); }; struct ANPPaintInterfaceV0 : ANPInterface { /** Return a new paint object, which holds all of the color and style attributes that affect how things (geometry, text, bitmaps) are drawn in a ANPCanvas. The paint that is returned is not tied to any particular plugin instance, but it must only be accessed from one thread at a time. */ ANPPaint* (*newPaint)(); void (*deletePaint)(ANPPaint*); ANPPaintFlags (*getFlags)(const ANPPaint*); void (*setFlags)(ANPPaint*, ANPPaintFlags); ANPColor (*getColor)(const ANPPaint*); void (*setColor)(ANPPaint*, ANPColor); ANPPaintStyle (*getStyle)(const ANPPaint*); void (*setStyle)(ANPPaint*, ANPPaintStyle); float (*getStrokeWidth)(const ANPPaint*); float (*getStrokeMiter)(const ANPPaint*); ANPPaintCap (*getStrokeCap)(const ANPPaint*); ANPPaintJoin (*getStrokeJoin)(const ANPPaint*); void (*setStrokeWidth)(ANPPaint*, float); void (*setStrokeMiter)(ANPPaint*, float); void (*setStrokeCap)(ANPPaint*, ANPPaintCap); void (*setStrokeJoin)(ANPPaint*, ANPPaintJoin); ANPTextEncoding (*getTextEncoding)(const ANPPaint*); ANPPaintAlign (*getTextAlign)(const ANPPaint*); float (*getTextSize)(const ANPPaint*); float (*getTextScaleX)(const ANPPaint*); float (*getTextSkewX)(const ANPPaint*); void (*setTextEncoding)(ANPPaint*, ANPTextEncoding); void (*setTextAlign)(ANPPaint*, ANPPaintAlign); void (*setTextSize)(ANPPaint*, float); void (*setTextScaleX)(ANPPaint*, float); void (*setTextSkewX)(ANPPaint*, float); /** Return the typeface ine paint, or null if there is none. This does not modify the owner count of the returned typeface. */ ANPTypeface* (*getTypeface)(const ANPPaint*); /** Set the paint's typeface. If the paint already had a non-null typeface, its owner count is decremented. If the new typeface is non-null, its owner count is incremented. */ void (*setTypeface)(ANPPaint*, ANPTypeface*); /** Return the width of the text. If bounds is not null, return the bounds of the text in that rectangle. */ float (*measureText)(ANPPaint*, const void* text, uint32_t byteLength, ANPRectF* bounds); /** Return the number of unichars specifed by the text. If widths is not null, returns the array of advance widths for each unichar. If bounds is not null, returns the array of bounds for each unichar. */ int (*getTextWidths)(ANPPaint*, const void* text, uint32_t byteLength, float widths[], ANPRectF bounds[]); /** Return in metrics the spacing values for text, respecting the paint's typeface and pointsize, and return the spacing between lines (descent - ascent + leading). If metrics is NULL, it will be ignored. */ float (*getFontMetrics)(ANPPaint*, ANPFontMetrics* metrics); }; struct ANPCanvasInterfaceV0 : ANPInterface { /** Return a canvas that will draw into the specified bitmap. Note: the canvas copies the fields of the bitmap, so it need not persist after this call, but the canvas DOES point to the same pixel memory that the bitmap did, so the canvas should not be used after that pixel memory goes out of scope. In the case of creating a canvas to draw into the pixels provided by kDraw_ANPEventType, those pixels are only while handling that event. The canvas that is returned is not tied to any particular plugin instance, but it must only be accessed from one thread at a time. */ ANPCanvas* (*newCanvas)(const ANPBitmap*); void (*deleteCanvas)(ANPCanvas*); void (*save)(ANPCanvas*); void (*restore)(ANPCanvas*); void (*translate)(ANPCanvas*, float tx, float ty); void (*scale)(ANPCanvas*, float sx, float sy); void (*rotate)(ANPCanvas*, float degrees); void (*skew)(ANPCanvas*, float kx, float ky); void (*concat)(ANPCanvas*, const ANPMatrix*); void (*clipRect)(ANPCanvas*, const ANPRectF*); void (*clipPath)(ANPCanvas*, const ANPPath*); /** Return the current matrix on the canvas */ void (*getTotalMatrix)(ANPCanvas*, ANPMatrix*); /** Return the current clip bounds in local coordinates, expanding it to account for antialiasing edge effects if aa is true. If the current clip is empty, return false and ignore the bounds argument. */ bool (*getLocalClipBounds)(ANPCanvas*, ANPRectF* bounds, bool aa); /** Return the current clip bounds in device coordinates in bounds. If the current clip is empty, return false and ignore the bounds argument. */ bool (*getDeviceClipBounds)(ANPCanvas*, ANPRectI* bounds); void (*drawColor)(ANPCanvas*, ANPColor); void (*drawPaint)(ANPCanvas*, const ANPPaint*); void (*drawLine)(ANPCanvas*, float x0, float y0, float x1, float y1, const ANPPaint*); void (*drawRect)(ANPCanvas*, const ANPRectF*, const ANPPaint*); void (*drawOval)(ANPCanvas*, const ANPRectF*, const ANPPaint*); void (*drawPath)(ANPCanvas*, const ANPPath*, const ANPPaint*); void (*drawText)(ANPCanvas*, const void* text, uint32_t byteLength, float x, float y, const ANPPaint*); void (*drawPosText)(ANPCanvas*, const void* text, uint32_t byteLength, const float xy[], const ANPPaint*); void (*drawBitmap)(ANPCanvas*, const ANPBitmap*, float x, float y, const ANPPaint*); void (*drawBitmapRect)(ANPCanvas*, const ANPBitmap*, const ANPRectI* src, const ANPRectF* dst, const ANPPaint*); }; struct ANPWindowInterfaceV0 : ANPInterface { /** Registers a set of rectangles that the plugin would like to keep on screen. The rectangles are listed in order of priority with the highest priority rectangle in location rects[0]. The browser will attempt to keep as many of the rectangles on screen as possible and will scroll them into view in response to the invocation of this method and other various events. The count specifies how many rectangles are in the array. If the count is zero it signals the browser that any existing rectangles should be cleared and no rectangles will be tracked. */ void (*setVisibleRects)(NPP instance, const ANPRectI rects[], int32_t count); /** Clears any rectangles that are being tracked as a result of a call to setVisibleRects. This call is equivalent to setVisibleRect(inst, NULL, 0). */ void (*clearVisibleRects)(NPP instance); /** Given a boolean value of true the device will be requested to provide a keyboard. A value of false will result in a request to hide the keyboard. Further, the on-screen keyboard will not be displayed if a physical keyboard is active. */ void (*showKeyboard)(NPP instance, bool value); /** Called when a plugin wishes to enter into full screen mode. The plugin's Java class (defined in the plugin's apk manifest) will be called asynchronously to provide a View object to be displayed full screen. */ void (*requestFullScreen)(NPP instance); /** Called when a plugin wishes to exit from full screen mode. As a result, the plugin's full screen view will be discarded by the view system. */ void (*exitFullScreen)(NPP instance); /** Called when a plugin wishes to be zoomed and centered in the current view. */ void (*requestCenterFitZoom)(NPP instance); }; struct ANPWindowInterfaceV1 : ANPWindowInterfaceV0 { /** Returns a rectangle representing the visible area of the plugin on screen. The coordinates are relative to the size of the plugin in the document and therefore will never be negative or exceed the plugin's size. */ ANPRectI (*visibleRect)(NPP instance); }; enum ANPScreenOrientations { /** No preference specified: let the system decide the best orientation. */ kDefault_ANPScreenOrientation = 0, /** Would like to have the screen in a landscape orientation, but it will not allow for 180 degree rotations. */ kFixedLandscape_ANPScreenOrientation = 1, /** Would like to have the screen in a portrait orientation, but it will not allow for 180 degree rotations. */ kFixedPortrait_ANPScreenOrientation = 2, /** Would like to have the screen in landscape orientation, but can use the sensor to change which direction the screen is facing. */ kLandscape_ANPScreenOrientation = 3, /** Would like to have the screen in portrait orientation, but can use the sensor to change which direction the screen is facing. */ kPortrait_ANPScreenOrientation = 4 }; typedef int32_t ANPScreenOrientation; struct ANPWindowInterfaceV2 : ANPWindowInterfaceV1 { /** Called when the plugin wants to specify a particular screen orientation when entering into full screen mode. The orientation must be set prior to entering into full screen. After entering full screen any subsequent changes will be updated the next time the plugin goes full screen. */ void (*requestFullScreenOrientation)(NPP instance, ANPScreenOrientation orientation); }; /////////////////////////////////////////////////////////////////////////////// enum ANPSampleFormats { kUnknown_ANPSamleFormat = 0, kPCM16Bit_ANPSampleFormat = 1, kPCM8Bit_ANPSampleFormat = 2 }; typedef int32_t ANPSampleFormat; /** The audio buffer is passed to the callback proc to request more samples. It is owned by the system, and the callback may read it, but should not maintain a pointer to it outside of the scope of the callback proc. */ struct ANPAudioBuffer { // RO - repeat what was specified in newTrack() int32_t channelCount; // RO - repeat what was specified in newTrack() ANPSampleFormat format; /** This buffer is owned by the caller. Inside the callback proc, up to "size" bytes of sample data should be written into this buffer. The address is only valid for the scope of a single invocation of the callback proc. */ void* bufferData; /** On input, specifies the maximum number of bytes that can be written to "bufferData". On output, specifies the actual number of bytes that the callback proc wrote into "bufferData". */ uint32_t size; }; enum ANPAudioEvents { /** This event is passed to the callback proc when the audio-track needs more sample data written to the provided buffer parameter. */ kMoreData_ANPAudioEvent = 0, /** This event is passed to the callback proc if the audio system runs out of sample data. In this event, no buffer parameter will be specified (i.e. NULL will be passed to the 3rd parameter). */ kUnderRun_ANPAudioEvent = 1 }; typedef int32_t ANPAudioEvent; /** Called to feed sample data to the track. This will be called in a separate thread. However, you may call trackStop() from the callback (but you cannot delete the track). For example, when you have written the last chunk of sample data, you can immediately call trackStop(). This will take effect after the current buffer has been played. The "user" parameter is the same value that was passed to newTrack() */ typedef void (*ANPAudioCallbackProc)(ANPAudioEvent event, void* user, ANPAudioBuffer* buffer); struct ANPAudioTrack; // abstract type for audio tracks struct ANPAudioTrackInterfaceV0 : ANPInterface { /** Create a new audio track, or NULL on failure. The track is initially in the stopped state and therefore ANPAudioCallbackProc will not be called until the track is started. */ ANPAudioTrack* (*newTrack)(uint32_t sampleRate, // sampling rate in Hz ANPSampleFormat, int channelCount, // MONO=1, STEREO=2 ANPAudioCallbackProc, void* user); /** Deletes a track that was created using newTrack. The track can be deleted in any state and it waits for the ANPAudioCallbackProc thread to exit before returning. */ void (*deleteTrack)(ANPAudioTrack*); void (*start)(ANPAudioTrack*); void (*pause)(ANPAudioTrack*); void (*stop)(ANPAudioTrack*); /** Returns true if the track is not playing (e.g. pause or stop was called, or start was never called. */ bool (*isStopped)(ANPAudioTrack*); }; struct ANPAudioTrackInterfaceV1 : ANPAudioTrackInterfaceV0 { /** Returns the track's latency in milliseconds. */ uint32_t (*trackLatency)(ANPAudioTrack*); }; /////////////////////////////////////////////////////////////////////////////// // DEFINITION OF VALUES PASSED THROUGH NPP_HandleEvent enum ANPEventTypes { kNull_ANPEventType = 0, kKey_ANPEventType = 1, /** Mouse events are triggered by either clicking with the navigational pad or by tapping the touchscreen (if the kDown_ANPTouchAction is handled by the plugin then no mouse event is generated). The kKey_ANPEventFlag has to be set to true in order to receive these events. */ kMouse_ANPEventType = 2, /** Touch events are generated when the user touches on the screen. The kTouch_ANPEventFlag has to be set to true in order to receive these events. */ kTouch_ANPEventType = 3, /** Only triggered by a plugin using the kBitmap_ANPDrawingModel. This event signals that the plugin needs to redraw itself into the provided bitmap. */ kDraw_ANPEventType = 4, kLifecycle_ANPEventType = 5, /** This event type is completely defined by the plugin. When creating an event, the caller must always set the first two fields, the remaining data is optional. ANPEvent evt; evt.inSize = sizeof(ANPEvent); evt.eventType = kCustom_ANPEventType // other data slots are optional evt.other[] = ...; To post a copy of the event, call eventInterface->postEvent(myNPPInstance, &evt); That call makes a copy of the event struct, and post that on the event queue for the plugin. */ kCustom_ANPEventType = 6, /** MultiTouch events are generated when the user touches on the screen. The kTouch_ANPEventFlag has to be set to true in order to receive these events. This type is a replacement for the older kTouch_ANPEventType. */ kMultiTouch_ANPEventType = 7, }; typedef int32_t ANPEventType; enum ANPKeyActions { kDown_ANPKeyAction = 0, kUp_ANPKeyAction = 1, }; typedef int32_t ANPKeyAction; #include "ANPKeyCodes.h" typedef int32_t ANPKeyCode; enum ANPKeyModifiers { kAlt_ANPKeyModifier = 1 << 0, kShift_ANPKeyModifier = 1 << 1, }; // bit-field containing some number of ANPKeyModifier bits typedef uint32_t ANPKeyModifier; enum ANPMouseActions { kDown_ANPMouseAction = 0, kUp_ANPMouseAction = 1, }; typedef int32_t ANPMouseAction; enum ANPTouchActions { /** This occurs when the user first touches on the screen. As such, this action will always occur prior to any of the other touch actions. If the plugin chooses to not handle this action then no other events related to that particular touch gesture will be generated. */ kDown_ANPTouchAction = 0, kUp_ANPTouchAction = 1, kMove_ANPTouchAction = 2, kCancel_ANPTouchAction = 3, // The web view will ignore the return value from the following actions kLongPress_ANPTouchAction = 4, kDoubleTap_ANPTouchAction = 5, }; typedef int32_t ANPTouchAction; enum ANPLifecycleActions { /** The web view containing this plugin has been paused. See documentation on the android activity lifecycle for more information. */ kPause_ANPLifecycleAction = 0, /** The web view containing this plugin has been resumed. See documentation on the android activity lifecycle for more information. */ kResume_ANPLifecycleAction = 1, /** The plugin has focus and is now the recipient of input events (e.g. key, touch, etc.) */ kGainFocus_ANPLifecycleAction = 2, /** The plugin has lost focus and will not receive any input events until it regains focus. This event is always preceded by a GainFocus action. */ kLoseFocus_ANPLifecycleAction = 3, /** The browser is running low on available memory and is requesting that the plugin free any unused/inactive resources to prevent a performance degradation. */ kFreeMemory_ANPLifecycleAction = 4, /** The page has finished loading. This happens when the page's top level frame reports that it has completed loading. */ kOnLoad_ANPLifecycleAction = 5, /** The browser is honoring the plugin's request to go full screen. Upon returning from this event the browser will resize the plugin's java surface to full-screen coordinates. */ kEnterFullScreen_ANPLifecycleAction = 6, /** The browser has exited from full screen mode. Immediately prior to sending this event the browser has resized the plugin's java surface to its original coordinates. */ kExitFullScreen_ANPLifecycleAction = 7, /** The plugin is visible to the user on the screen. This event will always occur after a kOffScreen_ANPLifecycleAction event. */ kOnScreen_ANPLifecycleAction = 8, /** The plugin is no longer visible to the user on the screen. This event will always occur prior to an kOnScreen_ANPLifecycleAction event. */ kOffScreen_ANPLifecycleAction = 9, }; typedef uint32_t ANPLifecycleAction; struct TouchPoint { int32_t id; float x; // relative to your "window" (0...width) float y; // relative to your "window" (0...height) float pressure; float size; // normalized to a value between 0...1 }; /* This is what is passed to NPP_HandleEvent() */ struct ANPEvent { uint32_t inSize; // size of this struct in bytes ANPEventType eventType; // use based on the value in eventType union { struct { ANPKeyAction action; ANPKeyCode nativeCode; int32_t virtualCode; // windows virtual key code ANPKeyModifier modifiers; int32_t repeatCount; // 0 for initial down (or up) int32_t unichar; // 0 if there is no value } key; struct { ANPMouseAction action; int32_t x; // relative to your "window" (0...width) int32_t y; // relative to your "window" (0...height) } mouse; struct { ANPTouchAction action; ANPKeyModifier modifiers; int32_t x; // relative to your "window" (0...width) int32_t y; // relative to your "window" (0...height) } touch; struct { ANPLifecycleAction action; } lifecycle; struct { ANPDrawingModel model; // relative to (0,0) in top-left of your plugin ANPRectI clip; // use based on the value in model union { ANPBitmap bitmap; struct { int32_t width; int32_t height; } surface; } data; } draw; struct { int64_t timestamp; int32_t id; ANPTouchAction action; int32_t pointerCount; TouchPoint* touchPoint; } multiTouch; int32_t other[8]; } data; }; struct ANPEventInterfaceV0 : ANPInterface { /** Post a copy of the specified event to the plugin. The event will be delivered to the plugin in its main thread (the thread that receives other ANPEvents). If, after posting before delivery, the NPP instance is torn down, the event will be discarded. */ void (*postEvent)(NPP inst, const ANPEvent* event); }; #endif
40.864258
89
0.654009
[ "geometry", "object", "model", "transform" ]
53117654620935a10d9e4b67b89995f44992366a
3,866
h
C
aimsalgo/src/AimsRegisterFFDEstimate/f77char.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
4
2019-07-09T05:34:10.000Z
2020-10-16T00:03:15.000Z
aimsalgo/src/AimsRegisterFFDEstimate/f77char.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
72
2018-10-31T14:52:50.000Z
2022-03-04T11:22:51.000Z
aimsalgo/src/AimsRegisterFFDEstimate/f77char.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
null
null
null
/* Copyright (C) 2000-2013 CEA * * This software and supporting documentation were developed by * bioPICSEL * CEA/DSV/I²BM/MIRCen/LMN, Batiment 61, * 18, route du Panorama * 92265 Fontenay-aux-Roses * France */ #include <string.h> /* class CHARACTER =============== A minimal class used when passing string arguments from C++ to FORTRAN 77 (received as FORTRAN 77 CHARACTER strings), and subsequently returned back to C++ as properly zero terminated strings. Method used for zero-termination: ================================= When the CHARACTER destructor is activated the zero-termination of the c-string is automatically managed. Zero termination is also done each time a string array is subscripted using CHARACTER::operator()(size_t index) FORTRAN Assumptions: ==================== (1) F77 truncates strings when CHARACTER variable is short (2) F77 pads variable with blanks when assigned string is short (3) F77 represents a string as a pointer followed by a length (4) A string array is stored in contiguous memory Author: Carsten A. Arnholm, 20-AUG-1995 Updates: 04-MAR-1996 Added features for handling arrays of strings 16-MAR-1996 Tested array features, explicit padding included 29-JUL-1996 Tested portability to SGI/Unix, moved declaration of destructor 04-APR-1997 Using strncpy instead of strcpy in void operator=(char* str); */ class CHARACTER { public: CHARACTER(char* cstring); CHARACTER(char* cstring, const size_t lstr); ~CHARACTER(); CHARACTER operator()(size_t index); void pad(size_t first,size_t howmany=1); void operator=(char* str); operator char*(); public: char* rep; // Actual string size_t len; // String length }; inline CHARACTER::CHARACTER(char* cstring) : rep(cstring), len(strlen(cstring)) {}; inline CHARACTER::CHARACTER(char* cstring, const size_t lstr) : rep(cstring), len(lstr) { // find position from where to start padding size_t slen = strlen(rep); // upper limit size_t actual = (slen < len)? slen : len; // actual <= len. for(size_t i=actual;i<len;i++) rep[i]=' '; // Do the padding. } inline CHARACTER::~CHARACTER() { if(rep[len] == '\0') return; // catches string constants for(int i=len-1;i>=0;i--) { if(rep[i] == '\0') break; // already zero terminated if(rep[i] != ' ') { // non-blank discovered, so rep[i+1] = '\0'; // zero-terminate and jump out break; } } } inline CHARACTER CHARACTER::operator()(size_t index) { // Construct a temporary CHARACTER object for the array element // identified by "index" in order to zero-terminate that element size_t pos = index*len; // start pos of array element CHARACTER element(rep+pos,len); // construct new CHARACTER. return element; // destructor called here. } inline void CHARACTER::pad(size_t first,size_t howmany) { size_t pos=0,i=0,stop=first+howmany-1; for(size_t index=first; index<=stop; index++) { pos = index*len; size_t slen = strlen(rep+pos); // upper limit size_t actual = (slen < len)? slen : len; for(i=pos+actual;i<pos+len;i++) rep[i]=' '; // Do the padding. } } inline void CHARACTER::operator=(char* str) { strncpy(rep,str,len); // this will copy a zero if str < rep rep[len-1] = '\0'; // zero terminate in case strncpy did not size_t slen = strlen(rep); // upper limit size_t actual = (slen < len)? slen : len; // actual <= len. for(size_t i=actual;i<len;i++) rep[i]=' '; // Do the padding. } inline CHARACTER::operator char*() { return rep; }
31.950413
82
0.617951
[ "object" ]
1b2e2b939eb436d6a4c74ede1376969484c64d52
5,032
h
C
src/xray/geometry_primitives.h
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/geometry_primitives.h
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/geometry_primitives.h
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 13.11.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #ifndef GEOMETRY_PRIMITIVES_H_INCLUDED #define GEOMETRY_PRIMITIVES_H_INCLUDED namespace xray { namespace geometry_utils{ //////////////////////////////////////////////////////////////////////////// // Oriented Bounding Box //////////////////////////////////////////////////////////////////////////// namespace obb { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 pair_count; extern XRAY_CORE_API const u16 pairs[]; } // namespace obb //////////////////////////////////////////////////////////////////////////// // Rectangle //////////////////////////////////////////////////////////////////////////// namespace rectangle { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 pair_count; extern XRAY_CORE_API const u16 pairs[]; } // namespace Rectangle //////////////////////////////////////////////////////////////////////////// // Ellipsoid //////////////////////////////////////////////////////////////////////////// namespace ellipsoid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[ ]; extern XRAY_CORE_API const u32 pair_count; extern XRAY_CORE_API const u16 pairs[]; } // namespace ellipsoid //////////////////////////////////////////////////////////////////////////// // Cone //////////////////////////////////////////////////////////////////////////// namespace cone { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 pair_count; extern XRAY_CORE_API const u16 pairs[]; } // namespace cone //////////////////////////////////////////////////////////////////////////// // Ellipse //////////////////////////////////////////////////////////////////////////// namespace ellipse { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 pair_count; extern XRAY_CORE_API const u16 pairs[]; } // namespace ellipse //////////////////////////////////////////////////////////////////////////// // Cube solid //////////////////////////////////////////////////////////////////////////// namespace cube_solid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 face_count; extern XRAY_CORE_API const u32 index_count; extern XRAY_CORE_API const u16 faces[]; } //namespace cube_solid //////////////////////////////////////////////////////////////////////////// // Rectangle solid //////////////////////////////////////////////////////////////////////////// namespace rectangle_solid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 face_count; extern XRAY_CORE_API const u32 index_count; extern XRAY_CORE_API const u16 faces[]; } // namespace Rectangle //////////////////////////////////////////////////////////////////////////// // Cone solid //////////////////////////////////////////////////////////////////////////// namespace cone_solid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 face_count; extern XRAY_CORE_API const u32 index_count; extern XRAY_CORE_API const u16 faces[]; } // namespace cone_solid //////////////////////////////////////////////////////////////////////////// // Cylinder //////////////////////////////////////////////////////////////////////////// namespace cylinder_solid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 face_count; extern XRAY_CORE_API const u32 index_count; extern XRAY_CORE_API const u16 faces[]; } //namespace cylinder_solid //////////////////////////////////////////////////////////////////////////// // Ellipsoid solid //////////////////////////////////////////////////////////////////////////// namespace ellipsoid_solid { extern XRAY_CORE_API const u32 vertex_count; extern XRAY_CORE_API const float vertices[]; extern XRAY_CORE_API const u32 face_count; extern XRAY_CORE_API const u32 index_count; extern XRAY_CORE_API const u16 faces[]; } //namespace ellipsoid_solid bool generate_torus ( xray::vectora< math::float3 >& vertices, xray::vectora< u16 >& indices, math::float4x4 transform, float outer_raduius, float inner_raduius, u16 outer_segments, u16 inner_segments ); } // namespace geometry_utils } // namespace xray #endif // #ifndef GEOMETRY_PRIMITIVES_H_INCLUDED
34.944444
122
0.499603
[ "transform", "solid" ]
1b2fe4060e79e1ca9dae55e4d8fc9bc4dec5d962
4,885
h
C
llpc/lower/llpcSpirvLowerMath.h
noahfredriks/llpc
31ca8f9d4a0b1691f0260194f26a87adcf07d746
[ "MIT" ]
null
null
null
llpc/lower/llpcSpirvLowerMath.h
noahfredriks/llpc
31ca8f9d4a0b1691f0260194f26a87adcf07d746
[ "MIT" ]
null
null
null
llpc/lower/llpcSpirvLowerMath.h
noahfredriks/llpc
31ca8f9d4a0b1691f0260194f26a87adcf07d746
[ "MIT" ]
null
null
null
/* *********************************************************************************************************************** * * Copyright (c) 2021-2022 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file llpcSpirvLowerMath.h * @brief LLPC header file: contains declarations of math lowering classes *********************************************************************************************************************** */ #pragma once #include "llpcSpirvLower.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/PassManager.h" namespace Llpc { // ===================================================================================================================== // SPIR-V lowering operations for math transformation. class SpirvLowerMath : public SpirvLower { public: SpirvLowerMath(); protected: void init(llvm::Module &module); void flushDenormIfNeeded(llvm::Instruction *inst); bool isOperandNoContract(llvm::Value *operand); void disableFastMath(llvm::Value *value); bool m_changed; // Whether the module is changed bool m_fp16DenormFlush; // Whether FP mode wants f16 denorms to be flushed to zero bool m_fp32DenormFlush; // Whether FP mode wants f32 denorms to be flushed to zero bool m_fp64DenormFlush; // Whether FP mode wants f64 denorms to be flushed to zero bool m_fp16RoundToZero; // Whether FP mode wants f16 round-to-zero }; // ===================================================================================================================== // SPIR-V lowering operations for math constant folding. class SpirvLowerMathConstFolding : public SpirvLowerMath, public llvm::PassInfoMixin<SpirvLowerMathConstFolding> { public: llvm::PreservedAnalyses run(llvm::Module &module, llvm::ModuleAnalysisManager &analysisManager); // NOTE: We use a function parameter here to get the TargetLibraryInfo object. This is // needed because the passes for the legacy and new pass managers use different ways to // retrieve it. That also ensures the object is retrieved once the passes are properly // initialized. This can be removed once the switch to the new pass manager is completed. bool runImpl(llvm::Module &module, const std::function<llvm::TargetLibraryInfo &()> &getTargetLibraryInfo); static llvm::StringRef name() { return "Lower SPIR-V math constant folding"; } // NOTE: This function is only used by the legacy pass manager wrapper class to retrieve the // entry point. The function can be removed once the switch to the new pass manager is completed. llvm::Function *getEntryPoint(); }; // ===================================================================================================================== // SPIR-V lowering operations for math floating point optimisation. class SpirvLowerMathFloatOp : public SpirvLowerMath, public llvm::PassInfoMixin<SpirvLowerMathFloatOp>, public llvm::InstVisitor<SpirvLowerMathFloatOp> { public: llvm::PreservedAnalyses run(llvm::Module &module, llvm::ModuleAnalysisManager &analysisManager); bool runImpl(llvm::Module &module); virtual void visitBinaryOperator(llvm::BinaryOperator &binaryOp); virtual void visitUnaryOperator(llvm::UnaryOperator &unaryOp); virtual void visitCallInst(llvm::CallInst &callInst); virtual void visitFPTruncInst(llvm::FPTruncInst &fptruncInst); static llvm::StringRef name() { return "Lower SPIR-V math floating point optimisation"; } }; } // namespace Llpc
50.360825
120
0.623337
[ "object" ]
1b345ca1da21d7a44767c58bbbd301aca17e1450
18,421
c
C
src/drivers/network/usb_host.c
gacha/simba
c31af7018990015784af0d84d427812db37917d8
[ "MIT" ]
325
2015-11-12T15:21:39.000Z
2022-01-11T09:39:36.000Z
src/drivers/network/usb_host.c
elektrik-elektronik-muhendisligi/simba
6cf4b92db6a27bef70ceccb6204526e22dd8a863
[ "MIT" ]
216
2016-01-02T10:57:11.000Z
2021-08-25T05:36:51.000Z
src/drivers/network/usb_host.c
elektrik-elektronik-muhendisligi/simba
6cf4b92db6a27bef70ceccb6204526e22dd8a863
[ "MIT" ]
101
2015-12-28T16:21:27.000Z
2022-03-29T11:59:01.000Z
/* * The MIT License (MIT) * * Copyright (c) 2014-2018, Erik Moqvist * * 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. * * This file is part of the Simba project. */ #include "simba.h" #if CONFIG_USB_HOST == 1 /* Only one device supported for now. */ #define DEVICE_ADDRESS 1 struct module_t { int8_t initialized; /* A list of all drivers. */ struct usb_host_driver_t *drivers_p; struct usb_host_device_driver_t *device_drivers_p; #if CONFIG_USB_HOST_FS_COMMAND_LIST == 1 struct fs_command_t cmd_list; #endif }; static int device_enumerate(struct usb_host_device_t *device_p); #include "usb_host_port.i" static struct module_t module; #if CONFIG_USB_HOST_FS_COMMAND_LIST == 1 static int cmd_list_cb(int argc, const char *argv[], void *out_p, void *in_p, void * arg_p, void *call_arg_p) { int i; int verbose = 0; struct usb_host_driver_t *self_p; struct usb_host_device_t *device_p; if (argc == 2) { if (strcmp("-v", argv[1]) == 0) { verbose = 1; } } std_fprintf(out_p, OSTR("BUS ADDRESS VID PID DESCRIPTION\r\n")); self_p = module.drivers_p; while (self_p != NULL) { device_p = &self_p->devices_p[0]; for (i = 0; i < self_p->length; i++, device_p++) { if (device_p->state != USB_HOST_DEVICE_STATE_ATTACHED) { continue; } std_fprintf(out_p, OSTR("%3d %8d %04x %04x %s\r\n"), device_p->self_p->id, device_p->address, device_p->vid, device_p->pid, device_p->description_p); if (verbose == 1) { usb_format_descriptors(out_p, device_p->descriptors.buf, device_p->descriptors.size); } } self_p = self_p->next_p; } return (0); } #endif /** * Set the device address. */ static int device_set_address(struct usb_host_device_t *device_p, uint16_t address) { struct usb_setup_t setup; std_printf(FSTR("Setting device address.\r\n")); /* Initiate the setup. */ setup.request_type = (REQUEST_TYPE_DATA_DIRECTION_HOST_TO_DEVICE); setup.request = REQUEST_SET_ADDRESS; setup.u.set_address.device_address = address; setup.u.set_address.zero = 0; setup.length = 0; /* Write the setup to the hardware and read the response into * dst_p. */ if (usb_host_device_control_transfer(device_p, &setup, NULL, 0) != 0) { std_printf(FSTR("Unable to set device address.\r\n")); return (-1); } device_p->address = address; return (usb_pipe_set_address(device_p->self_p, device_p->pipes[0], address)); } /** * Set the device configuration. */ int usb_host_device_set_configuration(struct usb_host_device_t *device_p, uint8_t configuration) { struct usb_setup_t setup; struct usb_pipe_t *pipe_p; int i, j; uint8_t *buf_p; size_t size; struct usb_descriptor_interface_t *int_p = NULL; struct usb_descriptor_endpoint_t *ep_p = NULL; int type; std_printf(FSTR("Setting device configuration %d.\r\n"), configuration); /* Initiate the setup. */ setup.request_type = REQUEST_TYPE_DATA_DIRECTION_HOST_TO_DEVICE; setup.request = REQUEST_SET_CONFIGURATION; setup.u.set_configuration.configuration_value = configuration; setup.u.set_configuration.zero = 0; setup.length = 0; /* Write the setup to the hardware and read the response into * dst_p. */ if (usb_host_device_control_transfer(device_p, &setup, NULL, 0) != 0) { std_printf(FSTR("Unable to set configration.\r\n")); return (-1); } device_p->current.configuration = configuration; device_p->current.descriptor.conf_p = NULL; /* Iterate over all interfaces in the configuration and allocate a * pipe for each endpoint. */ buf_p = device_p->descriptors.buf; size = device_p->descriptors.size; for (i = 0; (int_p = usb_desc_get_interface(buf_p, size, 1, i)) != NULL; i++) { for (j = 1; (ep_p = usb_desc_get_endpoint(buf_p, size, 1, i, j)) != NULL; j++) { switch (ENDPOINT_ATTRIBUTES_TRANSFER_TYPE(ep_p->attributes)) { case ENDPOINT_ATTRIBUTES_TRANSFER_TYPE_CONTROL: type = USB_PIPE_TYPE_CONTROL; break; case ENDPOINT_ATTRIBUTES_TRANSFER_TYPE_ISOCHRONOUS: type = USB_PIPE_TYPE_ISOCHRONOUS; break; case ENDPOINT_ATTRIBUTES_TRANSFER_TYPE_BULK: type = USB_PIPE_TYPE_BULK; break; case ENDPOINT_ATTRIBUTES_TRANSFER_TYPE_INTERRUPT: type = USB_PIPE_TYPE_INTERRUPT; break; default: return (-1); } pipe_p = usb_pipe_alloc(device_p->self_p, type, (ep_p->endpoint_address & 0x7f), device_p->address, ep_p->interval); if (pipe_p == NULL) { std_printf(FSTR("Pipe allocation failed.\r\n")); return (-1); } } } return (0); } /** * Get the device descriptors from the device. */ static ssize_t device_get_descriptor_device(struct usb_host_device_t *device_p, struct usb_descriptor_device_t *desc_p) { struct usb_setup_t setup; /* Initiate the setup datastructure. */ setup.request_type = REQUEST_TYPE_DATA_DIRECTION_DEVICE_TO_HOST; setup.request = REQUEST_GET_DESCRIPTOR; setup.u.get_descriptor.descriptor_index = 0; setup.u.get_descriptor.descriptor_type = DESCRIPTOR_TYPE_DEVICE; setup.u.get_descriptor.language_id = 0; setup.length = 8; /* Only read 8 bytes in the first read. */ if (usb_host_device_control_transfer(device_p, &setup, desc_p, setup.length) != setup.length) { std_printf(FSTR("failed to read first 8 bytes of the device descriptor.\r\n")); return (-1); } /* Set the maximum packet size the device supports. */ device_p->max_packet_size = desc_p->max_packet_size_0; std_printf(FSTR("max packet size = %d\r\n"), device_p->max_packet_size); /* Read the whole descriptor. */ setup.length = sizeof(*desc_p); if (usb_host_device_control_transfer(device_p, &setup, desc_p, setup.length) != setup.length) { std_printf(FSTR("failed to read the device descriptor.\r\n")); return (-1); } device_p->current.descriptor.dev_p = desc_p; device_p->vid = desc_p->id_vendor; device_p->pid = desc_p->id_product; return (0); } /** * Get a configuration descriptors from the device. */ static ssize_t device_get_descriptor_configuration(struct usb_host_device_t *device_p, uint8_t index, uint8_t *dst_p, size_t size) { struct usb_setup_t setup; struct usb_descriptor_configuration_t *desc_p; desc_p = (struct usb_descriptor_configuration_t *)dst_p; std_printf(FSTR("Getting device configuration.\r\n")); /* Initiate the setup. */ setup.request_type = REQUEST_TYPE_DATA_DIRECTION_DEVICE_TO_HOST; setup.request = REQUEST_GET_DESCRIPTOR; setup.u.get_descriptor.descriptor_index = index; setup.u.get_descriptor.descriptor_type = DESCRIPTOR_TYPE_CONFIGURATION; setup.u.get_descriptor.language_id = 0; setup.length = size; /* Write the setup to the hardware and read the response into */ /* dst_p. */ if (usb_host_device_control_transfer(device_p, &setup, desc_p, setup.length) != setup.length) { std_printf(FSTR("Unable to read the configuration descriptor from the device.\r\n")); return (-1); } return (setup.length); } /** * Get all descriptors from the device. */ static ssize_t device_get_descriptors(struct usb_host_device_t *device_p) { struct usb_descriptor_configuration_t *desc_p; uint8_t *dst_p; dst_p = device_p->descriptors.buf; dst_p += device_p->descriptors.size; /* Get the configuration descriptor at index 0. */ if (device_get_descriptor_configuration(device_p, 0, dst_p, sizeof(struct usb_descriptor_configuration_t)) != sizeof(struct usb_descriptor_configuration_t)) { return (-1); } desc_p = (struct usb_descriptor_configuration_t *)dst_p; if (desc_p->total_length > sizeof(struct usb_descriptor_configuration_t)) { if (device_get_descriptor_configuration(device_p, 0, dst_p, desc_p->total_length) != desc_p->total_length) { return (-1); } } device_p->descriptors.size += desc_p->total_length; return (0); } static struct usb_host_device_driver_t * find_device_driver(struct usb_host_device_t *device_p) { struct usb_host_device_driver_t *driver_p; driver_p = module.device_drivers_p; while (driver_p != NULL) { if (driver_p->supports(device_p)) { return (driver_p); } driver_p = driver_p->next_p; } return (NULL); } /** * Enumerate a detected device. After the enumeration the device has * been configured and is ready to use by the application. */ static int device_enumerate(struct usb_host_device_t *device_p) { struct usb_descriptor_device_t *device_desc_p; struct usb_host_device_driver_t *driver_p; struct usb_pipe_t *pipe_p = NULL; union usb_message_t message; std_printf(FSTR("Starting the USB enumeration process for a device.\r\n")); /* Set the initial maximum packet size.*/ device_p->max_packet_size = 8; /* Reset the device. */ if (device_reset(device_p) != 0) { return (-1); } /* Allocate a control pipe. */ pipe_p = usb_pipe_alloc(device_p->self_p, USB_PIPE_TYPE_CONTROL, 0, 0, 0); if (pipe_p == NULL) { goto err; } device_p->pipes[0] = pipe_p; /* Get the device descriptor. */ device_desc_p = (struct usb_descriptor_device_t *)(device_p->descriptors.buf); if (device_get_descriptor_device(device_p, device_desc_p) != 0) { goto err; } device_p->descriptors.size = sizeof(struct usb_descriptor_device_t); /* Assign the device an address. */ if (device_set_address(device_p, DEVICE_ADDRESS) != 0) { std_printf(FSTR("failed to set device address\r\n")); goto err; } /* Get various descriptors from the device. */ if (device_get_descriptors(device_p) != 0) { std_printf(FSTR("failed to get device descriptors\r\n")); goto err; } driver_p = find_device_driver(device_p); if (driver_p != NULL) { /* Driver specific enumeration. */ if (driver_p->enumerate(device_p) != 0) { goto err; } } else { std_printf(FSTR("Unsupported USB device.\r\n")); } device_p->state = USB_HOST_DEVICE_STATE_ATTACHED; device_p->description_p = ""; std_printf(FSTR("Enumeration done.\r\n")); usb_format_descriptors(sys_get_stdout(), device_p->descriptors.buf, device_p->descriptors.size); /* Notify the controller. */ message.add.header.type = USB_MESSAGE_TYPE_ADD; message.add.device = device_p->id; queue_write(&device_p->self_p->control, &message, sizeof(message)); return (0); err: if (pipe_p != NULL) { usb_pipe_free(device_p->self_p, pipe_p); } return (-1); } int usb_host_module_init(void) { /* Return immediately if the module is already initialized. */ if (module.initialized == 1) { return (0); } module.initialized = 1; #if CONFIG_USB_HOST_FS_COMMAND_LIST == 1 fs_command_init(&module.cmd_list, CSTR("/drivers/usb_host/list"), cmd_list_cb, NULL); fs_command_register(&module.cmd_list); #endif return (0); } int usb_host_init(struct usb_host_driver_t *self_p, struct usb_device_t *dev_p, struct usb_host_device_t *devices_p, size_t length) { ASSERTN(self_p != NULL, EINVAL); ASSERTN(dev_p != NULL, EINVAL); ASSERTN(devices_p != NULL, EINVAL); ASSERTN(length > 0, EINVAL); int i; self_p->dev_p = dev_p; self_p->length = length; self_p->devices_p = devices_p; queue_init(&self_p->control, NULL, 0); for (i = 0; i < length; i++) { self_p->devices_p[i].id = i; self_p->devices_p[i].state = USB_HOST_DEVICE_STATE_NONE; self_p->devices_p[i].self_p = self_p; } return (usb_host_port_init(self_p, dev_p)); } int usb_host_start(struct usb_host_driver_t *self_p) { ASSERTN(self_p != NULL, EINVAL); if (usb_host_port_start(self_p) != 0) { return (-1); } /* Add the driver to the list. */ self_p->next_p = module.drivers_p; module.drivers_p = self_p; return (0); } int usb_host_stop(struct usb_host_driver_t *self_p) { ASSERTN(self_p != NULL, EINVAL); return (usb_host_port_stop(self_p)); } int usb_host_driver_add(struct usb_host_driver_t *self_p, struct usb_host_device_driver_t *driver_p, void *arg_p) { ASSERTN(self_p != NULL, EINVAL); ASSERTN(driver_p != NULL, EINVAL); driver_p->next_p = module.device_drivers_p; module.device_drivers_p = driver_p; return (0); } struct usb_host_device_t * usb_host_device_open(struct usb_host_driver_t *self_p, int device) { ASSERTNRN(self_p != NULL, EINVAL); struct usb_host_device_t *device_p; if (device > self_p->length - 1) { return (NULL); } device_p = &self_p->devices_p[device]; if (device_p->state != USB_HOST_DEVICE_STATE_ATTACHED) { return (NULL); } return (device_p); } int usb_host_device_close(struct usb_host_driver_t *self_p, int device) { ASSERTN(self_p != NULL, EINVAL); if (device > self_p->length - 1) { return (-1); } return (0); } ssize_t usb_host_device_read(struct usb_host_device_t *device_p, int endpoint, void *buf_p, size_t size) { ASSERTN(device_p != NULL, EINVAL); ASSERTN(buf_p != NULL, EINVAL); ASSERTN(size > 0, EINVAL); return (usb_host_port_device_read(device_p, endpoint, buf_p, size)); } ssize_t usb_host_device_write(struct usb_host_device_t *device_p, int endpoint, const void *buf_p, size_t size) { ASSERTN(device_p != NULL, EINVAL); ASSERTN(buf_p != NULL, EINVAL); ASSERTN(size > 0, EINVAL); return (usb_host_port_device_write(device_p, endpoint, buf_p, size)); } ssize_t usb_host_device_control_transfer(struct usb_host_device_t *device_p, struct usb_setup_t *setup_p, void *buf_p, size_t size) { ASSERTN(device_p != NULL, EINVAL); ASSERTN(setup_p != NULL, EINVAL); ASSERTN(buf_p != NULL, EINVAL); ASSERTN(size > 0, EINVAL); std_printf(FSTR("Starting a control transfer.\r\n")); if (usb_host_port_device_write_setup(device_p, setup_p) != sizeof(*setup_p)) { std_printf(FSTR("Failed to write SETUP.\r\n")); return (-1); } /* Data and status stages. */ if (setup_p->request_type & REQUEST_TYPE_DATA_DIRECTION_DEVICE_TO_HOST) { if (size > 0) { /* Read data from the device. */ if (usb_host_port_device_read(device_p, 0, buf_p, size) != size) { return (-1); } } if (usb_host_port_device_write(device_p, 0, NULL, 0) != 0) { return (-1); } } else { if (size > 0) { /* Write data to the device. */ if (usb_host_port_device_write(device_p, 0, buf_p, size) != size) { return (-1); } } if (usb_host_port_device_read(device_p, 0, NULL, 0) != 0) { return (-1); } } return (size); } #endif
28.918367
93
0.590739
[ "3d" ]
1b34670a670ee426c2134ac2e60577ed720d49d8
12,991
h
C
clustal-omega-1.2.4/src/hhalign/hhhalfalignment-C.h
WooMichael/Project_Mendel
ff572f7ce7f9beca148f7351cf34dbf11d670bc8
[ "MIT" ]
null
null
null
clustal-omega-1.2.4/src/hhalign/hhhalfalignment-C.h
WooMichael/Project_Mendel
ff572f7ce7f9beca148f7351cf34dbf11d670bc8
[ "MIT" ]
null
null
null
clustal-omega-1.2.4/src/hhalign/hhhalfalignment-C.h
WooMichael/Project_Mendel
ff572f7ce7f9beca148f7351cf34dbf11d670bc8
[ "MIT" ]
null
null
null
/* -*- mode: c; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /********************************************************************* * Clustal Omega - Multiple sequence alignment * * Copyright (C) 2010 University College Dublin * * Clustal-Omega is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This file is part of Clustal-Omega. * ********************************************************************/ /* * RCS $Id: hhhalfalignment-C.h 315 2016-12-15 17:18:30Z fabian $ */ // hhfullalignment.C #ifndef MAIN #define MAIN #include <iostream> // cin, cout, cerr #include <fstream> // ofstream, ifstream #include <stdio.h> // printf #include <stdlib.h> // exit #include <string> // strcmp, strstr #include <math.h> // sqrt, pow #include <limits.h> // INT_MIN #include <float.h> // FLT_MIN #include <time.h> // clock #include <ctype.h> // islower, isdigit etc using std::ios; using std::ifstream; using std::ofstream; using std::cout; using std::cerr; using std::endl; #include "util-C.h" // imax, fmax, iround, iceil, ifloor, strint, strscn, strcut, substr, uprstr, uprchr, Basename etc. #include "list.h" // list data structure #include "hash.h" // hash data structure #include "hhdecl-C.h" // constants, class #include "hhutil-C.h" // imax, fmax, iround, iceil, ifloor, strint, strscn, strcut, substr, uprstr, uprchr, Basename etc. #include "hhhmm.h" // class HMM #include "hhalignment.h" // class Alignment #include "hhhit.h" #endif //#include "new_new.h" /* memory tracking */ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Methods of class HalfAlignment ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Constructor HalfAlignment::HalfAlignment(int maxseqdis) { n=0; sname=seq=NULL; nss_dssp = nss_pred = nss_conf = nsa_dssp = ncons= -1; h = new int[maxseqdis]; //h[k] = next position of sequence k to be written s = new char*[maxseqdis]; //s[k][h] = character in column h, sequence k of output alignment l = new int*[maxseqdis]; //counts non-gap residues: l[k][i] = index of last residue AT OR BEFORE match state i in seq k m = new int*[maxseqdis]; //counts positions: m[k][i] = position of match state i in string seq[k] } ///////////////////////////////////////////////////////////////////////////////////// // Destructor HalfAlignment::~HalfAlignment() { Unset(); delete[] h; h = NULL; delete[] s; s = NULL; delete[] l; l = NULL; delete[] m; m = NULL; } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Free memory in HalfAlignment arrays s[][], l[][], and m[][] */ void HalfAlignment::Unset() { // Free memory for alignment characters and residue counts for (int k=0; k<n; k++) { delete[] s[k]; s[k] = NULL; delete[] l[k]; l[k] = NULL; delete[] m[k]; m[k] = NULL; } n=0; sname=seq=NULL; nss_dssp = nss_pred = nss_conf = nsa_dssp = ncons= -1; } ////////////////////////////////////////////////////////////////////////////// /** * @brief Prepare a2m/a3m alignment: * Calculate l[k][i] (residue indices) and m[k][i] (position in seq[k]) */ void HalfAlignment::Set(char* name, char** seq_in, char** sname_in, int n_in, int L_in, int n1, int n2, int n3, int n4, int nc, int L_in2/*<--FS*/) { int i; /* counts match states in seq[k] */ int ll; /* counts residues LEFT from or at current position in seq[k] */ int mm; /* counts postions in string seq[k] */ int k; /* counts sequences */ char c; char warned=0; nss_dssp=n1; nss_pred=n2; nss_conf=n3; nsa_dssp=n4; ncons=nc; seq=seq_in; /* flat copy of sequences */ sname=sname_in; /* flat copy of sequence names */ n=n_in; L=L_in; pos=0; /* Allocate memory for alignment characters and residue counts */ for (k=0; k<n; k++) { s[k]=new char[LINELEN]; l[k]=new int[L+10+L_in2/*<--FS*/]; m[k]=new int[L+10+L_in2/*<--FS*/]; if (!s[k] || !l[k] || !m[k]) MemoryError("space for formatting HMM-HMM alignment"); h[k]=0; //starting positions in alignment = 0 } /* k <= 0 < n (= n_in) */ for (k=0; k<n; k++) { m[k][0]=0; // 0'th match state (virtual) is begin state at 0 //if k is consensus sequence if (k==nc) { for (i=1; i<=L; i++) m[k][i]=l[k][i]=i; m[k][L+1]=l[k][L+1]=L; continue; } i=1; mm=1; ll=1; while ((c=seq[k][mm])) { if (MatchChr(c)==c) //count match/delete states { l[k][i]=ll; m[k][i]=mm; i++; } if (WordChr(c)) ll++; //index of next residue mm++; } l[k][i]=ll-1; //set l[k][L+1] eq number of residues in seq k (-1 since there is no residue at L+1st match state) m[k][i]=mm; //set m[k][L+1] if ((i-1)!=L && !warned) { cerr<<"Warning: sequence "<<sname[k]<<" in HMM "<<name<<" has "<<i<<" match states but should have "<<L<<"\n"; warned=1; } } /* k <= 0 < n (= n_in) */ //DEBUG if (v>=5) { printf(" i chr m l\n"); for(i=0;i<=L+1;i++) printf("%3i %1c %3i %3i\n",i,seq[0][m[0][i]],m[0][i],l[0][i]); printf("\n"); } } /*** end HalfAlignment::Set() ***/ ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Fill in insert states following match state i (without inserting '.' to fill up) */ void HalfAlignment::AddInserts(int i) { for (int k=0; k<n; k++) // for all sequences... for (int mm=m[k][i]+1; mm<m[k][i+1]; mm++) // for all inserts between match state i and i+1... s[k][h[k]++]=seq[k][mm]; // fill inserts into output alignment s[k] } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Fill up alignment with gaps '.' to generate flush end (all h[k] equal) */ void HalfAlignment::FillUpGaps() { int k; //counts sequences pos=0; // Determine max position h[k] for (k=0; k<n; k++) pos = imax(h[k],pos); // Fill in gaps up to pos for (k=0; k<n; k++) { for (int hh=h[k]; hh<pos; hh++) s[k][hh]='.'; h[k]=pos; } } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Fill in insert states following match state i and fill up gaps with '.' */ void HalfAlignment::AddInsertsAndFillUpGaps(int i) { AddInserts(i); FillUpGaps(); } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Add gap column '.' */ void HalfAlignment::AddChar(char c) { for (int k=0; k<n; k++) s[k][h[k]++]=c; pos++; } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Add match state column i as is */ void HalfAlignment::AddColumn(int i) { for (int k=0; k<n; k++) s[k][h[k]++]=seq[k][m[k][i]]; pos++; } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Add match state column i as insert state */ void HalfAlignment::AddColumnAsInsert(int i) { char c; for (int k=0; k<n; k++) if ((c=seq[k][m[k][i]])!='-' && (c<'0' || c>'9')) s[k][h[k]++]=InsertChr(c); pos++; } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Remove all characters c from template sequences */ void HalfAlignment::RemoveChars(char c) { int k,h,hh; for (k=0; k<n; k++) { for (h=hh=0; h<pos; h++) if (s[k][h]!=c) s[k][hh++]=s[k][h]; s[k][++hh]='\0'; } } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Transform alignment sequences from A3M to A2M (insert ".") */ void HalfAlignment::BuildFASTA() { AddInserts(0); FillUpGaps(); for (int i=1; i<=L; i++) { AddColumn(i); AddInserts(i); FillUpGaps(); } ToFASTA(); } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Transform alignment sequences from A3M to A2M (insert ".") */ void HalfAlignment::BuildA2M() { AddInserts(0); FillUpGaps(); for (int i=1; i<=L; i++) { AddColumn(i); AddInserts(i); FillUpGaps(); } AddChar('\0'); } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Transform alignment sequences from A3M to A2M (insert ".") */ void HalfAlignment::BuildA3M() { AddInserts(0); for (int i=1; i<=L; i++) { AddColumn(i); AddInserts(i); } AddChar('\0'); } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Transform alignment sequences from A2M to FASTA ( lowercase to uppercase and '.' to '-') */ void HalfAlignment::ToFASTA() { for (int k=0; k<n; k++) { uprstr(s[k]); strtr(s[k],".","-"); } } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Align query (HalfAlignment) to template (i.e. hit) match state structure */ void HalfAlignment::AlignToTemplate(Hit& hit) { int i,j; int step; // column of the HMM-HMM alignment (first:nstep, last:1) char state; if(0) { //par.loc==0) { //////////////////////////////////////////// STILL NEEDED?? // If in global mode: Add part of alignment before first MM state AddInserts(0); // Fill in insert states before first match state for (i=1; i<hit.i[hit.nsteps]; i++) { AddColumnAsInsert(i); AddInserts(i); if (par.outformat<=2) FillUpGaps(); } } // Add endgaps (First state must be an MM state!!) for (j=1; j<hit.j[hit.nsteps]; j++) { AddChar('-'); } // Add alignment between first and last MM state for (step=hit.nsteps; step>=1; step--) { state = hit.states[step]; i = hit.i[step]; switch(state) { case MM: //MM pair state (both query and template in Match state) AddColumn(i); AddInserts(i); break; case DG: //D- state case MI: //MI state AddColumnAsInsert(i); AddInserts(i); break; case GD: //-D state case IM: //IM state AddChar('-'); break; } if (par.outformat<=2) FillUpGaps(); } if(0) { //par.loc==0) { //////////////////////////////////////////// STILL NEEDED?? // If in global mode: Add part of alignment after last MM state for (i=hit.i[1]+1; i<=L; i++) { AddColumnAsInsert(i); AddInserts(i); if (par.outformat==2) FillUpGaps(); } } // Add endgaps for (j=hit.j[1]+1; j<=hit.L; j++) { AddChar('-'); } // Add end-of-string character AddChar('\0'); } ///////////////////////////////////////////////////////////////////////////////////// /** * @brief Write the a2m/a3m alignment into alnfile */ void HalfAlignment::Print(char* alnfile) { int k; //counts sequences int omitted=0; // counts number of sequences with no residues in match states FILE *outf; if (strcmp(alnfile,"stdout")) { if (par.append) outf=fopen(alnfile,"a"); else outf=fopen(alnfile,"w"); if (!outf) OpenFileError(alnfile); } else outf = stdout; if (v>=3) cout<<"Writing alignment to "<<alnfile<<"\n"; for (k=0; k<n; k++) { // Print sequence only if it contains at least one residue in a match state if (1) //strpbrk(s[k],"ABCDEFGHIKLMNPQRSTUVWXYZ1234567890")) { fprintf(outf,">%s\n",sname[k]); fprintf(outf,"%s\n",s[k]); } else { omitted++; if (v>=3) printf("%-14.14s contains no residue in match state. Omitting sequence\n",sname[k]); } } if (v>=2 && omitted) printf("Omitted %i sequences in %s which contained no residue in match state\n",omitted,alnfile); fclose(outf); } /** EOF hhhalfalignment-C.h **/
28.74115
143
0.45724
[ "transform" ]
1b39bd1dc71136356f4435ff2167fa681fd07cc4
9,416
h
C
Headers/java/sql/Timestamp.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
11
2015-12-10T13:23:54.000Z
2019-04-23T02:41:13.000Z
Headers/java/sql/Timestamp.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
7
2015-11-05T22:45:53.000Z
2017-11-05T14:36:36.000Z
Headers/java/sql/Timestamp.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
40
2015-12-10T07:30:58.000Z
2022-03-15T02:50:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: android/libcore/luni/src/main/java/java/sql/Timestamp.java // #include "../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_JavaSqlTimestamp") #ifdef RESTRICT_JavaSqlTimestamp #define INCLUDE_ALL_JavaSqlTimestamp 0 #else #define INCLUDE_ALL_JavaSqlTimestamp 1 #endif #undef RESTRICT_JavaSqlTimestamp #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if !defined (JavaSqlTimestamp_) && (INCLUDE_ALL_JavaSqlTimestamp || defined(INCLUDE_JavaSqlTimestamp)) #define JavaSqlTimestamp_ #define RESTRICT_JavaUtilDate 1 #define INCLUDE_JavaUtilDate 1 #include "../../java/util/Date.h" @class IOSObjectArray; /*! @brief A Java representation of the SQL <code>TIMESTAMP</code> type. It provides the capability of representing the SQL <code>TIMESTAMP</code> nanosecond value, in addition to the regular date/time value which has millisecond resolution. <p> The <code>Timestamp</code> class consists of a regular date/time value, where only the integral seconds value is stored, plus a nanoseconds value where the fractional seconds are stored. <p> The addition of the nanosecond value field to the <code>Timestamp</code> object makes it significantly different from the <code>java.util.Date</code> object which it extends. Users should be aware that <code>Timestamp</code> objects are not interchangable with <code>java.util.Date</code> objects when used outside the confines of the <code>java.sql</code> package. - seealso: Date - seealso: Time - seealso: java.util.Date */ @interface JavaSqlTimestamp : JavaUtilDate #pragma mark Public /*! @brief Returns a <code>Timestamp</code> corresponding to the time specified by the supplied values for <i>Year</i>, <i>Month</i>, <i>Date</i>, <i>Hour</i>, <i>Minutes</i>, <i>Seconds</i> and <i>Nanoseconds</i>. @param theYear specified as the year minus 1900. @param theMonth specified as an integer in the range [0,11]. @param theDate specified as an integer in the range [1,31]. @param theHour specified as an integer in the range [0,23]. @param theMinute specified as an integer in the range [0,59]. @param theSecond specified as an integer in the range [0,59]. @param theNano which defines the nanosecond value of the timestamp specified as an integer in the range [0,999'999'999] @throws IllegalArgumentException if any of the parameters is out of range. */ - (instancetype)initWithInt:(jint)theYear withInt:(jint)theMonth withInt:(jint)theDate withInt:(jint)theHour withInt:(jint)theMinute withInt:(jint)theSecond withInt:(jint)theNano __attribute__((deprecated)); /*! @brief Returns a <code>Timestamp</code> object corresponding to the time represented by a supplied time value. @param theTime a time value in the format of milliseconds since the Epoch (January 1 1970 00:00:00.000 GMT). */ - (instancetype)initWithLong:(jlong)theTime; /*! @brief Returns <code>true</code> if this timestamp object is later than the supplied timestamp, otherwise returns <code>false</code>. @param theTimestamp the timestamp to compare with this timestamp object. @return <code>true</code> if this <code>Timestamp</code> object is later than the supplied timestamp, <code>false</code> otherwise. */ - (jboolean)afterWithJavaSqlTimestamp:(JavaSqlTimestamp *)theTimestamp; /*! @brief Returns <code>true</code> if this <code>Timestamp</code> object is earlier than the supplied timestamp, otherwise returns <code>false</code>. @param theTimestamp the timestamp to compare with this <code>Timestamp</code> object. @return <code>true</code> if this <code>Timestamp</code> object is earlier than the supplied timestamp, <code>false</code> otherwise. */ - (jboolean)beforeWithJavaSqlTimestamp:(JavaSqlTimestamp *)theTimestamp; /*! @brief Compares this <code>Timestamp</code> object with a supplied <code>Timestamp</code> object. @param theObject the timestamp to compare with this <code>Timestamp</code> object, passed as an <code>Object</code>. @return <dd> <dl> <code>0</code> if the two <code>Timestamp</code> objects are equal in time </dl> <dl> a value <code>< 0</code> if this <code>Timestamp</code> object is before the supplied <code>Timestamp</code> and a value </dl> <dl> <code>> 0</code> if this <code>Timestamp</code> object is after the supplied <code>Timestamp</code> </dl> </dd> @throws ClassCastException if the supplied object is not a <code>Timestamp</code> object. */ - (jint)compareToWithId:(JavaUtilDate *)theObject; /*! @brief Compares this <code>Timestamp</code> object with a supplied <code>Timestamp</code> object. @param theTimestamp the timestamp to compare with this <code>Timestamp</code> object, passed in as a <code>Timestamp</code>. @return one of the following: <ul> <li><code>0</code>, if the two <code>Timestamp</code> objects are equal in time</li> <li><code>< 0</code>, if this <code>Timestamp</code> object is before the supplied <code>Timestamp</code></li> <li> <code>> 0</code>, if this <code>Timestamp</code> object is after the supplied <code>Timestamp</code></li> </ul> */ - (jint)compareToWithJavaSqlTimestamp:(JavaSqlTimestamp *)theTimestamp; /*! @brief Tests to see if this timestamp is equal to a supplied object. @param theObject the object to which this timestamp is compared. @return <code>true</code> if this <code>Timestamp</code> object is equal to the supplied <code>Timestamp</code> object<br><code>false</code> if the object is not a <code>Timestamp</code> object or if the object is a <code>Timestamp</code> but represents a different instant in time. */ - (jboolean)isEqual:(id)theObject; /*! @brief Tests to see if this timestamp is equal to a supplied timestamp. @param theTimestamp the timestamp to compare with this <code>Timestamp</code> object, passed as an <code>Object</code>. @return <code>true</code> if this <code>Timestamp</code> object is equal to the supplied <code>Timestamp</code> object, <code>false</code> otherwise. */ - (jboolean)equalsWithJavaSqlTimestamp:(JavaSqlTimestamp *)theTimestamp; /*! @brief Gets this <code>Timestamp</code>'s nanosecond value @return The timestamp's nanosecond value, an integer between 0 and 999,999,999. */ - (jint)getNanos; /*! @brief Returns the time represented by this <code>Timestamp</code> object, as a long value containing the number of milliseconds since the Epoch (January 1 1970, 00:00:00.000 GMT). @return the number of milliseconds that have passed since January 1 1970, 00:00:00.000 GMT. */ - (jlong)getTime; /*! @brief Sets the nanosecond value for this <code>Timestamp</code>. @param n number of nanoseconds. @throws IllegalArgumentException if number of nanoseconds smaller than 0 or greater than 999,999,999. */ - (void)setNanosWithInt:(jint)n; /*! @brief Sets the time represented by this <code>Timestamp</code> object to the supplied time, defined as the number of milliseconds since the Epoch (January 1 1970, 00:00:00.000 GMT). @param theTime number of milliseconds since the Epoch (January 1 1970, 00:00:00.000 GMT). */ - (void)setTimeWithLong:(jlong)theTime; /*! @brief Returns the timestamp formatted as a String in the JDBC Timestamp Escape format, which is <code>"yyyy-MM-dd HH:mm:ss.nnnnnnnnn"</code>. @return A string representing the instant defined by the <code>Timestamp</code> , in JDBC Timestamp escape format. */ - (NSString *)description; /*! @brief Creates a <code>Timestamp</code> object with a time value equal to the time specified by a supplied String holding the time in JDBC timestamp escape format, which is <code>"yyyy-MM-dd HH:mm:ss.nnnnnnnnn</code>" @param s the <code>String</code> containing a time in JDBC timestamp escape format. @return A <code>Timestamp</code> object with time value as defined by the supplied <code>String</code>. @throws IllegalArgumentException if the provided string is <code>null</code>. */ + (JavaSqlTimestamp *)valueOfWithNSString:(NSString *)s; @end J2OBJC_EMPTY_STATIC_INIT(JavaSqlTimestamp) FOUNDATION_EXPORT void JavaSqlTimestamp_initWithInt_withInt_withInt_withInt_withInt_withInt_withInt_(JavaSqlTimestamp *self, jint theYear, jint theMonth, jint theDate, jint theHour, jint theMinute, jint theSecond, jint theNano); FOUNDATION_EXPORT JavaSqlTimestamp *new_JavaSqlTimestamp_initWithInt_withInt_withInt_withInt_withInt_withInt_withInt_(jint theYear, jint theMonth, jint theDate, jint theHour, jint theMinute, jint theSecond, jint theNano) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaSqlTimestamp *create_JavaSqlTimestamp_initWithInt_withInt_withInt_withInt_withInt_withInt_withInt_(jint theYear, jint theMonth, jint theDate, jint theHour, jint theMinute, jint theSecond, jint theNano); FOUNDATION_EXPORT void JavaSqlTimestamp_initWithLong_(JavaSqlTimestamp *self, jlong theTime); FOUNDATION_EXPORT JavaSqlTimestamp *new_JavaSqlTimestamp_initWithLong_(jlong theTime) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaSqlTimestamp *create_JavaSqlTimestamp_initWithLong_(jlong theTime); FOUNDATION_EXPORT JavaSqlTimestamp *JavaSqlTimestamp_valueOfWithNSString_(NSString *s); J2OBJC_TYPE_LITERAL_HEADER(JavaSqlTimestamp) #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_JavaSqlTimestamp")
36.78125
241
0.755629
[ "object" ]
1b3bc423888f001196f15ff23f999ff791c5d7f6
119,199
h
C
resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-tls-utils.h
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
2
2020-09-11T05:51:42.000Z
2020-12-31T11:42:02.000Z
resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-tls-utils.h
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
null
null
null
resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-tls-utils.h
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
null
null
null
/* packet-tls-utils.h * ssl manipulation functions * By Paolo Abeni <paolo.abeni@email.com> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __PACKET_TLS_UTILS_H__ #define __PACKET_TLS_UTILS_H__ #include <stdio.h> /* some APIs we declare take a stdio stream as an argument */ #include <glib.h> #include <epan/packet.h> #include <epan/prefs.h> #include <epan/wmem/wmem.h> #include <epan/expert.h> #include <epan/conversation.h> #include <epan/unit_strings.h> #include <wsutil/wsgcrypt.h> #ifdef HAVE_LIBGNUTLS #include <gnutls/x509.h> #include <gnutls/pkcs12.h> #endif /* HAVE_LIBGNUTLS */ /* TODO inline this now that Libgcrypt is mandatory? */ #define SSL_CIPHER_CTX gcry_cipher_hd_t #define SSL_DECRYPT_DEBUG /* other defines */ typedef enum { SSL_ID_CHG_CIPHER_SPEC = 0x14, SSL_ID_ALERT = 0x15, SSL_ID_HANDSHAKE = 0x16, SSL_ID_APP_DATA = 0x17, SSL_ID_HEARTBEAT = 0x18 } ContentType; typedef enum { SSL_HND_HELLO_REQUEST = 0, SSL_HND_CLIENT_HELLO = 1, SSL_HND_SERVER_HELLO = 2, SSL_HND_HELLO_VERIFY_REQUEST = 3, SSL_HND_NEWSESSION_TICKET = 4, SSL_HND_END_OF_EARLY_DATA = 5, SSL_HND_HELLO_RETRY_REQUEST = 6, SSL_HND_ENCRYPTED_EXTENSIONS = 8, SSL_HND_CERTIFICATE = 11, SSL_HND_SERVER_KEY_EXCHG = 12, SSL_HND_CERT_REQUEST = 13, SSL_HND_SVR_HELLO_DONE = 14, SSL_HND_CERT_VERIFY = 15, SSL_HND_CLIENT_KEY_EXCHG = 16, SSL_HND_FINISHED = 20, SSL_HND_CERT_URL = 21, SSL_HND_CERT_STATUS = 22, SSL_HND_SUPPLEMENTAL_DATA = 23, SSL_HND_KEY_UPDATE = 24, SSL_HND_COMPRESSED_CERTIFICATE = 25, /* Encrypted Extensions was NextProtocol in draft-agl-tls-nextprotoneg-03 * and changed in draft 04. Not to be confused with TLS 1.3 EE. */ SSL_HND_ENCRYPTED_EXTS = 67 } HandshakeType; #define SSL2_HND_ERROR 0x00 #define SSL2_HND_CLIENT_HELLO 0x01 #define SSL2_HND_CLIENT_MASTER_KEY 0x02 #define SSL2_HND_CLIENT_FINISHED 0x03 #define SSL2_HND_SERVER_HELLO 0x04 #define SSL2_HND_SERVER_VERIFY 0x05 #define SSL2_HND_SERVER_FINISHED 0x06 #define SSL2_HND_REQUEST_CERTIFICATE 0x07 #define SSL2_HND_CLIENT_CERTIFICATE 0x08 #define SSL_HND_HELLO_EXT_SERVER_NAME 0 #define SSL_HND_HELLO_EXT_MAX_FRAGMENT_LENGTH 1 #define SSL_HND_HELLO_EXT_CLIENT_CERTIFICATE_URL 2 #define SSL_HND_HELLO_EXT_TRUSTED_CA_KEYS 3 #define SSL_HND_HELLO_EXT_TRUNCATED_HMAC 4 #define SSL_HND_HELLO_EXT_STATUS_REQUEST 5 #define SSL_HND_HELLO_EXT_USER_MAPPING 6 #define SSL_HND_HELLO_EXT_CLIENT_AUTHZ 7 #define SSL_HND_HELLO_EXT_SERVER_AUTHZ 8 #define SSL_HND_HELLO_EXT_CERT_TYPE 9 #define SSL_HND_HELLO_EXT_SUPPORTED_GROUPS 10 /* renamed from "elliptic_curves" (RFC 7919 / TLS 1.3) */ #define SSL_HND_HELLO_EXT_EC_POINT_FORMATS 11 #define SSL_HND_HELLO_EXT_SRP 12 #define SSL_HND_HELLO_EXT_SIGNATURE_ALGORITHMS 13 #define SSL_HND_HELLO_EXT_USE_SRTP 14 #define SSL_HND_HELLO_EXT_HEARTBEAT 15 #define SSL_HND_HELLO_EXT_ALPN 16 #define SSL_HND_HELLO_EXT_STATUS_REQUEST_V2 17 #define SSL_HND_HELLO_EXT_SIGNED_CERTIFICATE_TIMESTAMP 18 #define SSL_HND_HELLO_EXT_CLIENT_CERT_TYPE 19 #define SSL_HND_HELLO_EXT_SERVER_CERT_TYPE 20 #define SSL_HND_HELLO_EXT_PADDING 21 #define SSL_HND_HELLO_EXT_ENCRYPT_THEN_MAC 22 #define SSL_HND_HELLO_EXT_EXTENDED_MASTER_SECRET 23 #define SSL_HND_HELLO_EXT_TOKEN_BINDING 24 #define SSL_HND_HELLO_EXT_CACHED_INFO 25 #define SSL_HND_HELLO_EXT_COMPRESS_CERTIFICATE 27 #define SSL_HND_HELLO_EXT_RECORD_SIZE_LIMIT 28 /* 26-34 Unassigned*/ #define SSL_HND_HELLO_EXT_SESSION_TICKET_TLS 35 /* RFC 8446 (TLS 1.3) */ #define SSL_HND_HELLO_EXT_KEY_SHARE_OLD 40 /* draft-ietf-tls-tls13-22 (removed in -23) */ #define SSL_HND_HELLO_EXT_PRE_SHARED_KEY 41 #define SSL_HND_HELLO_EXT_EARLY_DATA 42 #define SSL_HND_HELLO_EXT_SUPPORTED_VERSIONS 43 #define SSL_HND_HELLO_EXT_COOKIE 44 #define SSL_HND_HELLO_EXT_PSK_KEY_EXCHANGE_MODES 45 #define SSL_HND_HELLO_EXT_TICKET_EARLY_DATA_INFO 46 /* draft-ietf-tls-tls13-18 (removed in -19) */ #define SSL_HND_HELLO_EXT_CERTIFICATE_AUTHORITIES 47 #define SSL_HND_HELLO_EXT_OID_FILTERS 48 #define SSL_HND_HELLO_EXT_POST_HANDSHAKE_AUTH 49 #define SSL_HND_HELLO_EXT_SIGNATURE_ALGORITHMS_CERT 50 #define SSL_HND_HELLO_EXT_KEY_SHARE 51 #define SSL_HND_HELLO_EXT_GREASE_0A0A 2570 #define SSL_HND_HELLO_EXT_GREASE_1A1A 6682 #define SSL_HND_HELLO_EXT_GREASE_2A2A 10794 #define SSL_HND_HELLO_EXT_NPN 13172 /* 0x3374 */ #define SSL_HND_HELLO_EXT_GREASE_3A3A 14906 #define SSL_HND_HELLO_EXT_GREASE_4A4A 19018 #define SSL_HND_HELLO_EXT_GREASE_5A5A 23130 #define SSL_HND_HELLO_EXT_GREASE_6A6A 27242 #define SSL_HND_HELLO_EXT_CHANNEL_ID_OLD 30031 /* 0x754f */ #define SSL_HND_HELLO_EXT_CHANNEL_ID 30032 /* 0x7550 */ #define SSL_HND_HELLO_EXT_GREASE_7A7A 31354 #define SSL_HND_HELLO_EXT_GREASE_8A8A 35466 #define SSL_HND_HELLO_EXT_GREASE_9A9A 39578 #define SSL_HND_HELLO_EXT_GREASE_AAAA 43690 #define SSL_HND_HELLO_EXT_GREASE_BABA 47802 #define SSL_HND_HELLO_EXT_GREASE_CACA 51914 #define SSL_HND_HELLO_EXT_GREASE_DADA 56026 #define SSL_HND_HELLO_EXT_GREASE_EAEA 60138 #define SSL_HND_HELLO_EXT_GREASE_FAFA 64250 #define SSL_HND_HELLO_EXT_RENEGOTIATION_INFO 65281 /* 0xFF01 */ #define SSL_HND_HELLO_EXT_QUIC_TRANSPORT_PARAMETERS 65445 /* 0xffa5 draft-ietf-quic-tls-13 */ #define SSL_HND_HELLO_EXT_ENCRYPTED_SERVER_NAME 65486 /* 0xffce draft-ietf-tls-esni-01 */ #define SSL_HND_CERT_URL_TYPE_INDIVIDUAL_CERT 1 #define SSL_HND_CERT_URL_TYPE_PKIPATH 2 #define SSL_HND_CERT_STATUS_TYPE_OCSP 1 #define SSL_HND_CERT_STATUS_TYPE_OCSP_MULTI 2 #define SSL_HND_CERT_TYPE_RAW_PUBLIC_KEY 2 #define SSL_HND_QUIC_TP_ORIGINAL_CONNECTION_ID 0 #define SSL_HND_QUIC_TP_IDLE_TIMEOUT 1 #define SSL_HND_QUIC_TP_STATELESS_RESET_TOKEN 2 #define SSL_HND_QUIC_TP_MAX_PACKET_SIZE 3 #define SSL_HND_QUIC_TP_INITIAL_MAX_DATA 4 #define SSL_HND_QUIC_TP_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL 5 #define SSL_HND_QUIC_TP_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE 6 #define SSL_HND_QUIC_TP_INITIAL_MAX_STREAM_DATA_UNI 7 #define SSL_HND_QUIC_TP_INITIAL_MAX_STREAMS_BIDI 8 #define SSL_HND_QUIC_TP_INITIAL_MAX_STREAMS_UNI 9 #define SSL_HND_QUIC_TP_ACK_DELAY_EXPONENT 10 #define SSL_HND_QUIC_TP_MAX_ACK_DELAY 11 #define SSL_HND_QUIC_TP_DISABLE_MIGRATION 12 #define SSL_HND_QUIC_TP_PREFERRED_ADDRESS 13 /* * Lookup tables */ extern const value_string ssl_version_short_names[]; extern const value_string ssl_20_msg_types[]; extern value_string_ext ssl_20_cipher_suites_ext; extern const value_string ssl_20_certificate_type[]; extern const value_string ssl_31_content_type[]; extern const value_string ssl_versions[]; extern const value_string ssl_31_change_cipher_spec[]; extern const value_string ssl_31_alert_level[]; extern const value_string ssl_31_alert_description[]; extern const value_string ssl_31_handshake_type[]; extern const value_string tls_heartbeat_type[]; extern const value_string tls_heartbeat_mode[]; extern const value_string ssl_31_compression_method[]; extern const value_string ssl_31_key_exchange_algorithm[]; extern const value_string ssl_31_signature_algorithm[]; extern const value_string ssl_31_client_certificate_type[]; extern const value_string ssl_31_public_value_encoding[]; extern value_string_ext ssl_31_ciphersuite_ext; extern const value_string tls_hello_extension_types[]; extern const value_string tls_hash_algorithm[]; extern const value_string tls_signature_algorithm[]; extern const value_string tls13_signature_algorithm[]; extern const value_string tls_certificate_type[]; extern const value_string tls_cert_chain_type[]; extern const value_string tls_cert_status_type[]; extern const value_string ssl_extension_curves[]; extern const value_string ssl_extension_ec_point_formats[]; extern const value_string ssl_curve_types[]; extern const value_string tls_hello_ext_server_name_type_vs[]; extern const value_string tls_hello_ext_psk_ke_mode[]; extern const value_string tls13_key_update_request[]; extern const value_string compress_certificate_algorithm_vals[]; extern const value_string quic_transport_parameter_id[]; extern const value_string quic_version_vals[]; extern const value_string quic_tp_preferred_address_vals[]; /* XXX Should we use GByteArray instead? */ typedef struct _StringInfo { guchar *data; /* Backing storage which may be larger than data_len */ guint data_len; /* Length of the meaningful part of data */ } StringInfo; #define SSL_WRITE_KEY 1 #define SSL_VER_UNKNOWN 0 #define SSLV2_VERSION 0x0002 /* not in record layer, SSL_CLIENT_SERVER from http://www-archive.mozilla.org/projects/security/pki/nss/ssl/draft02.html */ #define SSLV3_VERSION 0x300 #define TLSV1_VERSION 0x301 #define TLSV1DOT1_VERSION 0x302 #define TLSV1DOT2_VERSION 0x303 #define TLSV1DOT3_VERSION 0x304 #define DTLSV1DOT0_VERSION 0xfeff #define DTLSV1DOT0_OPENSSL_VERSION 0x100 #define DTLSV1DOT2_VERSION 0xfefd /* Returns the TLS 1.3 draft version or 0 if not applicable. */ static inline guint8 extract_tls13_draft_version(guint32 version) { if ((version & 0xff00) == 0x7f00) { return (guint8) version; } return 0; } #define SSL_CLIENT_RANDOM (1<<0) #define SSL_SERVER_RANDOM (1<<1) #define SSL_CIPHER (1<<2) #define SSL_HAVE_SESSION_KEY (1<<3) #define SSL_VERSION (1<<4) #define SSL_MASTER_SECRET (1<<5) #define SSL_PRE_MASTER_SECRET (1<<6) #define SSL_CLIENT_EXTENDED_MASTER_SECRET (1<<7) #define SSL_SERVER_EXTENDED_MASTER_SECRET (1<<8) #define SSL_NEW_SESSION_TICKET (1<<10) #define SSL_ENCRYPT_THEN_MAC (1<<11) #define SSL_SEEN_0RTT_APPDATA (1<<12) #define SSL_QUIC_RECORD_LAYER (1<<13) /* For QUIC (draft >= -13) */ #define SSL_EXTENDED_MASTER_SECRET_MASK (SSL_CLIENT_EXTENDED_MASTER_SECRET|SSL_SERVER_EXTENDED_MASTER_SECRET) /* SSL Cipher Suite modes */ typedef enum { MODE_STREAM, /* GenericStreamCipher */ MODE_CBC, /* GenericBlockCipher */ MODE_GCM, /* GenericAEADCipher */ MODE_CCM, /* AEAD_AES_{128,256}_CCM with 16 byte auth tag */ MODE_CCM_8, /* AEAD_AES_{128,256}_CCM with 8 byte auth tag */ MODE_POLY1305, /* AEAD_CHACHA20_POLY1305 with 16 byte auth tag (RFC 7905) */ } ssl_cipher_mode_t; /* Explicit and implicit nonce length (RFC 5116 - Section 3.2.1) */ #define IMPLICIT_NONCE_LEN 4 #define EXPLICIT_NONCE_LEN 8 #define TLS13_AEAD_NONCE_LENGTH 12 /* TLS 1.3 Record type for selecting the appropriate secret. */ typedef enum { TLS_SECRET_0RTT_APP, TLS_SECRET_HANDSHAKE, TLS_SECRET_APP, } TLSRecordType; #define SSL_DEBUG_USE_STDERR "-" #define SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES 16 /* Record fragment lengths MUST NOT exceed 2^14 (= 0x4000) */ #define TLS_MAX_RECORD_LENGTH 0x4000 typedef struct _SslCipherSuite { gint number; gint kex; gint enc; gint dig; ssl_cipher_mode_t mode; } SslCipherSuite; typedef struct _SslFlow { guint32 byte_seq; guint16 flags; wmem_tree_t *multisegment_pdus; } SslFlow; typedef struct _SslDecompress SslDecompress; typedef struct _SslDecoder { const SslCipherSuite *cipher_suite; gint compression; guchar _mac_key_or_write_iv[48]; StringInfo mac_key; /* for block and stream ciphers */ StringInfo write_iv; /* for AEAD ciphers (at least GCM, CCM) */ SSL_CIPHER_CTX evp; SslDecompress *decomp; guint64 seq; /**< Implicit (TLS) or explicit (DTLS) record sequence number. */ guint16 epoch; SslFlow *flow; StringInfo app_traffic_secret; /**< TLS 1.3 application traffic secret (if applicable), wmem file scope. */ } SslDecoder; /* * TLS 1.3 Cipher context. Simpler than SslDecoder since no compression is * required and all keys are calculated internally. */ typedef struct { gcry_cipher_hd_t hd; guint8 iv[TLS13_AEAD_NONCE_LENGTH]; } tls13_cipher; #define KEX_DHE_DSS 0x10 #define KEX_DHE_PSK 0x11 #define KEX_DHE_RSA 0x12 #define KEX_DH_ANON 0x13 #define KEX_DH_DSS 0x14 #define KEX_DH_RSA 0x15 #define KEX_ECDHE_ECDSA 0x16 #define KEX_ECDHE_PSK 0x17 #define KEX_ECDHE_RSA 0x18 #define KEX_ECDH_ANON 0x19 #define KEX_ECDH_ECDSA 0x1a #define KEX_ECDH_RSA 0x1b #define KEX_KRB5 0x1c #define KEX_PSK 0x1d #define KEX_RSA 0x1e #define KEX_RSA_PSK 0x1f #define KEX_SRP_SHA 0x20 #define KEX_SRP_SHA_DSS 0x21 #define KEX_SRP_SHA_RSA 0x22 #define KEX_IS_DH(n) ((n) >= KEX_DHE_DSS && (n) <= KEX_ECDH_RSA) #define KEX_TLS13 0x23 #define KEX_ECJPAKE 0x24 /* Order is significant, must match "ciphers" array in packet-tls-utils.c */ #define ENC_DES 0x30 #define ENC_3DES 0x31 #define ENC_RC4 0x32 #define ENC_RC2 0x33 #define ENC_IDEA 0x34 #define ENC_AES 0x35 #define ENC_AES256 0x36 #define ENC_CAMELLIA128 0x37 #define ENC_CAMELLIA256 0x38 #define ENC_SEED 0x39 #define ENC_CHACHA20 0x3A #define ENC_NULL 0x3B #define DIG_MD5 0x40 #define DIG_SHA 0x41 #define DIG_SHA256 0x42 #define DIG_SHA384 0x43 #define DIG_NA 0x44 /* Not Applicable */ typedef struct { const gchar *name; guint len; } SslDigestAlgo; typedef struct _SslRecordInfo { guchar *plain_data; /**< Decrypted data. */ guint data_len; /**< Length of decrypted data. */ gint id; /**< Identifies the exact record within a frame (there can be multiple records in a frame). */ ContentType type; /**< Content type of the decrypted record data. */ SslFlow *flow; /**< Flow where this record fragment is a part of. Can be NULL if this record type may not be fragmented. */ guint32 seq; /**< Data offset within the flow. */ struct _SslRecordInfo* next; } SslRecordInfo; typedef struct { SslRecordInfo *records; /**< Decrypted records within this frame. */ guint32 srcport; /**< Used for Decode As */ guint32 destport; } SslPacketInfo; typedef struct _SslSession { gint cipher; gint compression; guint16 version; guchar tls13_draft_version; gint8 client_cert_type; gint8 server_cert_type; guint32 client_ccs_frame; guint32 server_ccs_frame; /* The address/proto/port of the server as determined from heuristics * (e.g. ClientHello) or set externally (via ssl_set_master_secret()). */ address srv_addr; port_type srv_ptype; guint srv_port; /* The Application layer protocol if known (for STARTTLS support) */ dissector_handle_t app_handle; guint32 last_nontls_frame; gboolean is_session_resumed; } SslSession; /* RFC 5246, section 8.1 says that the master secret is always 48 bytes */ #define SSL_MASTER_SECRET_LENGTH 48 struct cert_key_id; /* defined in epan/secrets.h */ /* This holds state information for a SSL conversation */ typedef struct _SslDecryptSession { guchar _master_secret[SSL_MASTER_SECRET_LENGTH]; guchar _session_id[256]; guchar _client_random[32]; guchar _server_random[32]; StringInfo session_id; StringInfo session_ticket; StringInfo server_random; StringInfo client_random; StringInfo master_secret; StringInfo handshake_data; /* the data store for this StringInfo must be allocated explicitly with a capture lifetime scope */ StringInfo pre_master_secret; guchar _server_data_for_iv[24]; StringInfo server_data_for_iv; guchar _client_data_for_iv[24]; StringInfo client_data_for_iv; gint state; const SslCipherSuite *cipher_suite; SslDecoder *server; SslDecoder *client; SslDecoder *server_new; SslDecoder *client_new; #if defined(HAVE_LIBGNUTLS) struct cert_key_id *cert_key_id; /**< SHA-1 Key ID of public key in certificate. */ #endif StringInfo psk; StringInfo app_data_segment; SslSession session; gboolean has_early_data; } SslDecryptSession; /* User Access Table */ typedef struct _ssldecrypt_assoc_t { char* ipaddr; char* port; char* protocol; char* keyfile; char* password; } ssldecrypt_assoc_t; typedef struct ssl_common_options { const gchar *psk; const gchar *keylog_filename; } ssl_common_options_t; /** Map from something to a (pre-)master secret */ typedef struct { GHashTable *session; /* Session ID (1-32 bytes) to master secret. */ GHashTable *tickets; /* Session Ticket to master secret. */ GHashTable *crandom; /* Client Random to master secret */ GHashTable *pre_master; /* First 8 bytes of encrypted pre-master secret to pre-master secret */ GHashTable *pms; /* Client Random to unencrypted pre-master secret */ /* For TLS 1.3: maps Client Random to derived secret. */ GHashTable *tls13_client_early; GHashTable *tls13_client_handshake; GHashTable *tls13_server_handshake; GHashTable *tls13_client_appdata; GHashTable *tls13_server_appdata; GHashTable *tls13_early_exporter; GHashTable *tls13_exporter; /* For QUIC: maps Client Random to derived secret. */ GHashTable *quic_client_early; GHashTable *quic_client_handshake; GHashTable *quic_server_handshake; GHashTable *quic_client_appdata; GHashTable *quic_server_appdata; } ssl_master_key_map_t; gint ssl_get_keyex_alg(gint cipher); gboolean ssldecrypt_uat_fld_ip_chk_cb(void*, const char*, unsigned, const void*, const void*, char** err); gboolean ssldecrypt_uat_fld_port_chk_cb(void*, const char*, unsigned, const void*, const void*, char** err); gboolean ssldecrypt_uat_fld_fileopen_chk_cb(void*, const char*, unsigned, const void*, const void*, char** err); gboolean ssldecrypt_uat_fld_password_chk_cb(void*, const char*, unsigned, const void*, const void*, char** err); gchar* ssl_association_info(const char* dissector_table_name, const char* table_protocol); /** Retrieve a SslSession, creating it if it did not already exist. * @param conversation The SSL conversation. * @param ssl_handle The dissector handle for SSL or DTLS. */ extern SslDecryptSession * ssl_get_session(conversation_t *conversation, dissector_handle_t ssl_handle); /** Set server address and port */ extern void ssl_set_server(SslSession *session, address *addr, port_type ptype, guint32 port); /** Marks this packet as the last one before switching to SSL that is supposed * to encapsulate this protocol. * @param ssl_handle The dissector handle for SSL or DTLS. * @param pinfo Packet Info. * @param app_handle Dissector handle for the protocol inside the decrypted * Application Data record. * @return 0 for the first STARTTLS acknowledgement (success) or if ssl_handle * is NULL. >0 if STARTTLS was started before. */ WS_DLL_PUBLIC guint32 ssl_starttls_ack(dissector_handle_t ssl_handle, packet_info *pinfo, dissector_handle_t app_handle); /** Marks this packet as belonging to an SSL conversation started with STARTTLS. * @param ssl_handle The dissector handle for SSL or DTLS. * @param pinfo Packet Info. * @param app_handle Dissector handle for the protocol inside the decrypted * Application Data record. * @return 0 for the first STARTTLS acknowledgement (success) or if ssl_handle * is NULL. >0 if STARTTLS was started before. */ WS_DLL_PUBLIC guint32 ssl_starttls_post_ack(dissector_handle_t ssl_handle, packet_info *pinfo, dissector_handle_t app_handle); extern dissector_handle_t ssl_find_appdata_dissector(const char *name); /** set the data and len for the stringInfo buffer. buf should be big enough to * contain the provided data @param buf the buffer to update @param src the data source @param len the source data len */ extern void ssl_data_set(StringInfo* buf, const guchar* src, guint len); /** alloc the data with the specified len for the stringInfo buffer. @param str the data source @param len the source data len */ extern gint ssl_data_alloc(StringInfo* str, size_t len); extern gint ssl_cipher_setiv(SSL_CIPHER_CTX *cipher, guchar* iv, gint iv_len); /** Search for the specified cipher suite id @param num the id of the cipher suite to be searched @return pointer to the cipher suite struct (or NULL if not found). */ extern const SslCipherSuite * ssl_find_cipher(int num); /** Returns the Libgcrypt cipher identifier or 0 if unavailable. */ int ssl_get_cipher_algo(const SslCipherSuite *cipher_suite); /** Obtains the block size for a CBC block cipher. * @param cipher_suite a cipher suite as returned by ssl_find_cipher(). * @return the block size of a cipher or 0 if unavailable. */ guint ssl_get_cipher_blocksize(const SslCipherSuite *cipher_suite); gboolean ssl_generate_pre_master_secret(SslDecryptSession *ssl_session, guint32 length, tvbuff_t *tvb, guint32 offset, const gchar *ssl_psk, #ifdef HAVE_LIBGNUTLS GHashTable *key_hash, #endif const ssl_master_key_map_t *mk_map); /** Expand the pre_master_secret to generate all the session information * (master secret, session keys, ivs) @param ssl_session the store for all the session data @return 0 on success */ extern gint ssl_generate_keyring_material(SslDecryptSession*ssl_session); extern void ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server); /** Try to decrypt an ssl record @param ssl ssl_session the store all the session data @param decoder the stream decoder to be used @param ct the content type of this ssl record @param record_version the version as contained in the record @param ignore_mac_failed whether to ignore MAC or authenticity failures @param in a pointer to the ssl record to be decrypted @param inl the record length @param comp_str a pointer to the store the compression data @param out_str a pointer to the store for the decrypted data @param outl the decrypted data len @return 0 on success */ extern gint ssl_decrypt_record(SslDecryptSession *ssl, SslDecoder *decoder, guint8 ct, guint16 record_version, gboolean ignore_mac_failed, const guchar *in, guint16 inl, StringInfo *comp_str, StringInfo *out_str, guint *outl); /** * Given a cipher algorithm and its mode, a hash algorithm and the secret (with * the same length as the hash algorithm), try to build a cipher. The algorithms * and mode are Libgcrypt identifiers. */ tls13_cipher * tls13_cipher_create(const char *label_prefix, int cipher_algo, int cipher_mode, int hash_algo, const StringInfo *secret, const gchar **error); /* Common part between TLS and DTLS dissectors */ /* handling of association between tls/dtls ports and clear text protocol */ extern void ssl_association_add(const char* dissector_table_name, dissector_handle_t main_handle, dissector_handle_t subdissector_handle, guint port, gboolean tcp); extern void ssl_association_remove(const char* dissector_table_name, dissector_handle_t main_handle, dissector_handle_t subdissector_handle, guint port, gboolean tcp); extern gint ssl_packet_from_server(SslSession *session, dissector_table_t table, packet_info *pinfo); /* add to packet data a copy of the specified real data */ extern void ssl_add_record_info(gint proto, packet_info *pinfo, const guchar *data, gint data_len, gint record_id, SslFlow *flow, ContentType type, guint8 curr_layer_num_ssl); /* search in packet data for the specified id; return a newly created tvb for the associated data */ extern tvbuff_t* ssl_get_record_info(tvbuff_t *parent_tvb, gint proto, packet_info *pinfo, gint record_id, guint8 curr_layer_num_ssl, SslRecordInfo **matched_record); /* initialize/reset per capture state data (ssl sessions cache) */ extern void ssl_common_init(ssl_master_key_map_t *master_key_map, StringInfo *decrypted_data, StringInfo *compressed_data); extern void ssl_common_cleanup(ssl_master_key_map_t *master_key_map, FILE **ssl_keylog_file, StringInfo *decrypted_data, StringInfo *compressed_data); /** * Access to the keys in the TLS dissector, for use by the DTLS dissector. * (This is a transition function, it would be nice if the static keylog file * contents was separated from keys derived at runtime.) */ extern ssl_master_key_map_t * tls_get_master_key_map(gboolean load_secrets); /* Process lines from the TLS key log and populate the secrets map. */ extern void tls_keylog_process_lines(const ssl_master_key_map_t *mk_map, const guint8 *data, guint len); /* tries to update the secrets cache from the given filename */ extern void ssl_load_keyfile(const gchar *ssl_keylog_filename, FILE **keylog_file, const ssl_master_key_map_t *mk_map); #ifdef HAVE_LIBGNUTLS /* parse ssl related preferences (private keys and ports association strings) */ extern void ssl_parse_key_list(const ssldecrypt_assoc_t * uats, GHashTable *key_hash, const char* dissector_table_name, dissector_handle_t main_handle, gboolean tcp); #endif /* store master secret into session data cache */ extern void ssl_save_session(SslDecryptSession* ssl, GHashTable *session_hash); extern void ssl_finalize_decryption(SslDecryptSession *ssl, ssl_master_key_map_t *mk_map); extern gboolean tls13_generate_keys(SslDecryptSession *ssl_session, const StringInfo *secret, gboolean is_from_server); extern StringInfo * tls13_load_secret(SslDecryptSession *ssl, ssl_master_key_map_t *mk_map, gboolean is_from_server, TLSRecordType type); extern void tls13_change_key(SslDecryptSession *ssl, ssl_master_key_map_t *mk_map, gboolean is_from_server, TLSRecordType type); extern void tls13_key_update(SslDecryptSession *ssl, gboolean is_from_server); extern gboolean ssl_is_valid_content_type(guint8 type); extern gboolean ssl_is_valid_handshake_type(guint8 hs_type, gboolean is_dtls); extern void tls_scan_server_hello(tvbuff_t *tvb, guint32 offset, guint32 offset_end, guint16 *server_version, gboolean *is_hrr); extern void ssl_try_set_version(SslSession *session, SslDecryptSession *ssl, guint8 content_type, guint8 handshake_type, gboolean is_dtls, guint16 version); extern void ssl_calculate_handshake_hash(SslDecryptSession *ssl_session, tvbuff_t *tvb, guint32 offset, guint32 length); /* common header fields, subtrees and expert info for SSL and DTLS dissectors */ typedef struct ssl_common_dissect { struct { gint change_cipher_spec; gint hs_exts_len; gint hs_ext_alpn_len; gint hs_ext_alpn_list; gint hs_ext_alpn_str; gint hs_ext_alpn_str_len; gint hs_ext_cert_url_item; gint hs_ext_cert_url_padding; gint hs_ext_cert_url_sha1; gint hs_ext_cert_url_type; gint hs_ext_cert_url_url; gint hs_ext_cert_url_url_hash_list_len; gint hs_ext_cert_url_url_len; gint hs_ext_cert_status_type; gint hs_ext_cert_status_request_len; gint hs_ext_cert_status_responder_id_list_len; gint hs_ext_cert_status_request_extensions_len; gint hs_ext_cert_status_request_list_len; gint hs_ocsp_response_list_len; gint hs_ocsp_response_len; gint hs_ext_cert_type; gint hs_ext_cert_types; gint hs_ext_cert_types_len; gint hs_ext_data; gint hs_ext_ec_point_format; gint hs_ext_ec_point_formats; gint hs_ext_ec_point_formats_len; gint hs_ext_supported_group; gint hs_ext_supported_groups; gint hs_ext_supported_groups_len; gint hs_ext_heartbeat_mode; gint hs_ext_len; gint hs_ext_npn_str; gint hs_ext_npn_str_len; gint hs_ext_reneg_info_len; gint hs_ext_reneg_info; gint hs_ext_key_share_client_length; gint hs_ext_key_share_group; gint hs_ext_key_share_key_exchange_length; gint hs_ext_key_share_key_exchange; gint hs_ext_key_share_selected_group; gint hs_ext_psk_identities_length; gint hs_ext_psk_identity_identity_length; gint hs_ext_psk_identity_identity; gint hs_ext_psk_identity_obfuscated_ticket_age; gint hs_ext_psk_binders_length; gint hs_ext_psk_binders; gint hs_ext_psk_identity_selected; gint hs_ext_supported_versions_len; gint hs_ext_supported_version; gint hs_ext_cookie_len; gint hs_ext_cookie; gint hs_ext_server_name; gint hs_ext_server_name_len; gint hs_ext_server_name_list_len; gint hs_ext_server_name_type; gint hs_ext_padding_data; gint hs_ext_type; gint hs_sig_hash_alg; gint hs_sig_hash_alg_len; gint hs_sig_hash_algs; gint hs_sig_hash_hash; gint hs_sig_hash_sig; gint hs_client_keyex_epms_len; gint hs_client_keyex_epms; gint hs_server_keyex_modulus_len; gint hs_server_keyex_exponent_len; gint hs_server_keyex_sig_len; gint hs_server_keyex_p_len; gint hs_server_keyex_g_len; gint hs_server_keyex_ys_len; gint hs_client_keyex_yc_len; gint hs_client_keyex_point_len; gint hs_server_keyex_point_len; gint hs_server_keyex_p; gint hs_server_keyex_g; gint hs_server_keyex_curve_type; gint hs_server_keyex_named_curve; gint hs_server_keyex_ys; gint hs_client_keyex_yc; gint hs_server_keyex_point; gint hs_client_keyex_point; gint hs_server_keyex_modulus; gint hs_server_keyex_exponent; gint hs_server_keyex_sig; gint hs_server_keyex_hint_len; gint hs_server_keyex_hint; gint hs_client_keyex_identity_len; gint hs_client_keyex_identity; gint hs_certificates_len; gint hs_certificates; gint hs_certificate_len; gint hs_certificate; gint hs_cert_types_count; gint hs_cert_types; gint hs_cert_type; gint hs_dnames_len; gint hs_dnames; gint hs_dname_len; gint hs_dname; gint hs_random; gint hs_random_time; gint hs_random_bytes; gint hs_session_id; gint hs_session_id_len; gint hs_client_version; gint hs_server_version; gint hs_cipher_suites_len; gint hs_cipher_suites; gint hs_cipher_suite; gint hs_comp_methods_len; gint hs_comp_methods; gint hs_comp_method; gint hs_session_ticket_lifetime_hint; gint hs_session_ticket_age_add; gint hs_session_ticket_nonce_len; gint hs_session_ticket_nonce; gint hs_session_ticket_len; gint hs_session_ticket; gint hs_finished; gint hs_client_cert_vrfy_sig_len; gint hs_client_cert_vrfy_sig; /* TLS 1.3 */ gint hs_ext_psk_ke_modes_length; gint hs_ext_psk_ke_mode; gint hs_certificate_request_context_length; gint hs_certificate_request_context; gint hs_key_update_request_update; gint sct_scts_length; gint sct_sct_length; gint sct_sct_version; gint sct_sct_logid; gint sct_sct_timestamp; gint sct_sct_extensions_length; gint sct_sct_extensions; gint sct_sct_signature; gint sct_sct_signature_length; gint hs_ext_max_early_data_size; gint hs_ext_oid_filters_length; gint hs_ext_oid_filters_oid_length; gint hs_ext_oid_filters_oid; gint hs_ext_oid_filters_values_length; /* compress_certificate */ gint hs_ext_compress_certificate_algorithms_length; gint hs_ext_compress_certificate_algorithm; gint hs_ext_compress_certificate_uncompressed_length; gint hs_ext_compress_certificate_compressed_certificate_message_length; gint hs_ext_compress_certificate_compressed_certificate_message; gint hs_ext_record_size_limit; /* QUIC Transport Parameters */ gint hs_ext_quictp_negotiated_version; gint hs_ext_quictp_initial_version; gint hs_ext_quictp_supported_versions_len; gint hs_ext_quictp_supported_versions; gint hs_ext_quictp_len; gint hs_ext_quictp_parameter; gint hs_ext_quictp_parameter_type; gint hs_ext_quictp_parameter_len; gint hs_ext_quictp_parameter_value; gint hs_ext_quictp_parameter_ocid; gint hs_ext_quictp_parameter_idle_timeout; gint hs_ext_quictp_parameter_stateless_reset_token; gint hs_ext_quictp_parameter_initial_max_data; gint hs_ext_quictp_parameter_initial_max_stream_data_bidi_local; gint hs_ext_quictp_parameter_initial_max_stream_data_bidi_remote; gint hs_ext_quictp_parameter_initial_max_stream_data_uni; gint hs_ext_quictp_parameter_initial_max_streams_bidi; gint hs_ext_quictp_parameter_initial_max_streams_uni; gint hs_ext_quictp_parameter_ack_delay_exponent; gint hs_ext_quictp_parameter_max_ack_delay; gint hs_ext_quictp_parameter_max_packet_size; gint hs_ext_quictp_parameter_pa_ipversion; // Remove in draft -18 gint hs_ext_quictp_parameter_pa_ipaddress_length; // Remove in draft -18 gint hs_ext_quictp_parameter_pa_ipv4address; gint hs_ext_quictp_parameter_pa_ipv6address; gint hs_ext_quictp_parameter_pa_ipv4port; gint hs_ext_quictp_parameter_pa_ipv6port; gint hs_ext_quictp_parameter_pa_connectionid_length; gint hs_ext_quictp_parameter_pa_connectionid; gint hs_ext_quictp_parameter_pa_statelessresettoken; gint esni_suite; gint esni_record_digest_length; gint esni_record_digest; gint esni_encrypted_sni_length; gint esni_encrypted_sni; gint esni_nonce; /* do not forget to update SSL_COMMON_LIST_T and SSL_COMMON_HF_LIST! */ } hf; struct { gint hs_ext; gint hs_ext_alpn; gint hs_ext_cert_types; gint hs_ext_groups; gint hs_ext_curves_point_formats; gint hs_ext_npn; gint hs_ext_reneg_info; gint hs_ext_key_share; gint hs_ext_key_share_ks; gint hs_ext_pre_shared_key; gint hs_ext_psk_identity; gint hs_ext_server_name; gint hs_ext_oid_filter; gint hs_ext_quictp_parameter; gint hs_sig_hash_alg; gint hs_sig_hash_algs; gint urlhash; gint keyex_params; gint certificates; gint cert_types; gint dnames; gint hs_random; gint cipher_suites; gint comp_methods; gint session_ticket; gint sct; gint cert_status; gint ocsp_response; /* do not forget to update SSL_COMMON_LIST_T and SSL_COMMON_ETT_LIST! */ } ett; struct { /* Generic expert info for malformed packets. */ expert_field malformed_vector_length; expert_field malformed_buffer_too_small; expert_field malformed_trailing_data; expert_field hs_ext_cert_status_undecoded; expert_field resumed; expert_field record_length_invalid; /* do not forget to update SSL_COMMON_LIST_T and SSL_COMMON_EI_LIST! */ } ei; } ssl_common_dissect_t; /* Header fields specific to DTLS. See packet-dtls.c */ typedef struct { gint hf_dtls_handshake_cookie_len; gint hf_dtls_handshake_cookie; /* Do not forget to initialize dtls_hfs to -1 in packet-dtls.c! */ } dtls_hfs_t; /* Header fields specific to SSL. See packet-tls.c */ typedef struct { gint hs_md5_hash; gint hs_sha_hash; /* Do not forget to initialize ssl_hfs to -1 in packet-tls.c! */ } ssl_hfs_t; /* Helpers for dissecting Variable-Length Vectors. {{{ */ /* Largest value that fits in a 24-bit number (2^24-1). */ #define G_MAXUINT24 ((1U << 24) - 1) /** * Helper for dissection of variable-length vectors (RFC 5246, section 4.3). It * adds a length field to the tree and writes the validated length value into * "ret_length" (which is truncated if it exceeds "offset_end"). * * The size of the field is derived from "max_value" (for example, 8 and 255 * require one byte while 400 needs two bytes). Expert info is added if the * length field from the tvb is outside the (min_value, max_value) range. * * Returns TRUE if there is enough space for the length field and data elements * and FALSE otherwise. */ extern gboolean ssl_add_vector(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint offset_end, guint32 *ret_length, int hf_length, guint32 min_value, guint32 max_value); /** * Helper to check whether the data in a vector with multiple elements is * correctly dissected. If the current "offset" (normally the value after * adding all kinds of fields) does not match "offset_end" (the end of the * vector), expert info is added. * * Returns TRUE if the offset matches the end of the vector and FALSE otherwise. */ extern gboolean ssl_end_vector(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, guint offset_end); /* }}} */ extern void ssl_check_record_length(ssl_common_dissect_t *hf, packet_info *pinfo, guint record_length, proto_item *length_pi, guint16 version, tvbuff_t *decrypted_tvb); void ssl_dissect_change_cipher_spec(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, SslSession *session, gboolean is_from_server, const SslDecryptSession *ssl); extern void ssl_dissect_hnd_cli_hello(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, SslDecryptSession *ssl, dtls_hfs_t *dtls_hfs); extern void ssl_dissect_hnd_srv_hello(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, SslDecryptSession *ssl, gboolean is_dtls, gboolean is_hrr); extern void ssl_dissect_hnd_hello_retry_request(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, SslDecryptSession *ssl, gboolean is_dtls); extern void ssl_dissect_hnd_encrypted_extensions(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, SslDecryptSession *ssl, gboolean is_dtls); extern void ssl_dissect_hnd_new_ses_ticket(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, SslDecryptSession *ssl, gboolean is_dtls, GHashTable *session_hash); extern void ssl_dissect_hnd_cert(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset, guint32 offset_end, packet_info *pinfo, SslSession *session, SslDecryptSession *ssl, gboolean is_from_server, gboolean is_dtls); extern void ssl_dissect_hnd_cert_req(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, SslSession *session, gboolean is_dtls); extern void ssl_dissect_hnd_cli_cert_verify(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, guint16 version); extern void ssl_dissect_hnd_finished(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset, guint32 offset_end, const SslSession *session, ssl_hfs_t *ssl_hfs); extern void ssl_dissect_hnd_cert_url(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset); extern guint32 tls_dissect_hnd_certificate_status(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end); extern void ssl_dissect_hnd_cli_keyex(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset, guint32 length, const SslSession *session); extern void ssl_dissect_hnd_srv_keyex(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, const SslSession *session); extern void tls13_dissect_hnd_key_update(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset); extern guint32 tls_dissect_sct_list(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint32 offset_end, guint16 version); extern gboolean tls13_hkdf_expand_label_context(int md, const StringInfo *secret, const char *label_prefix, const char *label, const guint8 *context, guint8 context_length, guint16 out_len, guchar **out); extern gboolean tls13_hkdf_expand_label(int md, const StringInfo *secret, const char *label_prefix, const char *label, guint16 out_len, guchar **out); extern void ssl_dissect_hnd_compress_certificate(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset, guint32 offset_end, packet_info *pinfo, SslSession *session _U_, SslDecryptSession *ssl _U_, gboolean is_from_server _U_, gboolean is_dtls _U_); /* {{{ */ #define SSL_COMMON_LIST_T(name) \ ssl_common_dissect_t name = { \ /* hf */ { \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, \ }, \ /* ett */ { \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, \ }, \ /* ei */ { \ EI_INIT, EI_INIT, EI_INIT, EI_INIT, EI_INIT, EI_INIT, \ }, \ } /* }}} */ /* {{{ */ #define SSL_COMMON_HF_LIST(name, prefix) \ { & name .hf.change_cipher_spec, \ { "Change Cipher Spec Message", prefix ".change_cipher_spec", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "Signals a change in cipher specifications", HFILL } \ }, \ { & name .hf.hs_exts_len, \ { "Extensions Length", prefix ".handshake.extensions_length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of hello extensions", HFILL } \ }, \ { & name .hf.hs_ext_type, \ { "Type", prefix ".handshake.extension.type", \ FT_UINT16, BASE_DEC, VALS(tls_hello_extension_types), 0x0, \ "Hello extension type", HFILL } \ }, \ { & name .hf.hs_ext_len, \ { "Length", prefix ".handshake.extension.len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of a hello extension", HFILL } \ }, \ { & name .hf.hs_ext_data, \ { "Data", prefix ".handshake.extension.data", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Hello Extension data", HFILL } \ }, \ { & name .hf.hs_ext_supported_groups_len, \ { "Supported Groups List Length", prefix ".handshake.extensions_supported_groups_length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_supported_groups, \ { "Supported Groups List", prefix ".handshake.extensions_supported_groups", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of supported groups (formerly Supported Elliptic Curves)", HFILL } \ }, \ { & name .hf.hs_ext_supported_group, \ { "Supported Group", prefix ".handshake.extensions_supported_group", \ FT_UINT16, BASE_HEX, VALS(ssl_extension_curves), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_ec_point_formats_len, \ { "EC point formats Length", prefix ".handshake.extensions_ec_point_formats_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of elliptic curves point formats field", HFILL } \ }, \ { & name .hf.hs_ext_ec_point_formats, \ { "EC point formats", prefix ".handshake.extensions_ec_point_formats", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of elliptic curves point format", HFILL } \ }, \ { & name .hf.hs_ext_ec_point_format, \ { "EC point format", prefix ".handshake.extensions_ec_point_format", \ FT_UINT8, BASE_DEC, VALS(ssl_extension_ec_point_formats), 0x0, \ "Elliptic curves point format", HFILL } \ }, \ { & name .hf.hs_ext_alpn_len, \ { "ALPN Extension Length", prefix ".handshake.extensions_alpn_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of the ALPN Extension", HFILL } \ }, \ { & name .hf.hs_ext_alpn_list, \ { "ALPN Protocol", prefix ".handshake.extensions_alpn_list", \ FT_NONE, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_alpn_str_len, \ { "ALPN string length", prefix ".handshake.extensions_alpn_str_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of ALPN string", HFILL } \ }, \ { & name .hf.hs_ext_alpn_str, \ { "ALPN Next Protocol", prefix ".handshake.extensions_alpn_str", \ FT_STRING, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_npn_str_len, \ { "Protocol string length", prefix ".handshake.extensions_npn_str_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of next protocol string", HFILL } \ }, \ { & name .hf.hs_ext_npn_str, \ { "Next Protocol", prefix ".handshake.extensions_npn", \ FT_STRING, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_reneg_info_len, \ { "Renegotiation info extension length", prefix ".handshake.extensions_reneg_info_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_reneg_info, \ { "Renegotiation info", prefix ".handshake.extensions_reneg_info",\ FT_BYTES, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_key_share_client_length, \ { "Client Key Share Length", prefix ".handshake.extensions_key_share_client_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_key_share_group, \ { "Group", prefix ".handshake.extensions_key_share_group", \ FT_UINT16, BASE_DEC, VALS(ssl_extension_curves), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_key_share_key_exchange_length, \ { "Key Exchange Length", prefix ".handshake.extensions_key_share_key_exchange_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_key_share_key_exchange, \ { "Key Exchange", prefix ".handshake.extensions_key_share_key_exchange", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_key_share_selected_group, \ { "Selected Group", prefix ".handshake.extensions_key_share_selected_group", \ FT_UINT16, BASE_DEC, VALS(ssl_extension_curves), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_identities_length, \ { "Identities Length", prefix ".handshake.extensions.psk.identities.length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_identity_identity_length, \ { "Identity Length", prefix ".handshake.extensions.psk.identity.identity_length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_identity_identity, \ { "Identity", prefix ".handshake.extensions.psk.identity.identity", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_identity_obfuscated_ticket_age, \ { "Obfuscated Ticket Age", prefix ".handshake.extensions.psk.identity.obfuscated_ticket_age", \ FT_UINT32, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_binders_length, \ { "PSK Binders length", prefix ".handshake.extensions.psk.binders_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_binders, \ { "PSK Binders", prefix ".handshake.extensions.psk.binders", \ FT_NONE, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_identity_selected, \ { "Selected Identity", prefix ".handshake.extensions.psk.identity.selected", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_supported_versions_len, \ { "Supported Versions length", prefix ".handshake.extensions.supported_versions_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_supported_version, \ { "Supported Version", prefix ".handshake.extensions.supported_version", \ FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cookie_len, \ { "Cookie length", prefix ".handshake.extensions.cookie_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cookie, \ { "Cookie", prefix ".handshake.extensions.cookie", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_server_name_list_len, \ { "Server Name list length", prefix ".handshake.extensions_server_name_list_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of server name list", HFILL } \ }, \ { & name .hf.hs_ext_server_name_len, \ { "Server Name length", prefix ".handshake.extensions_server_name_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of server name string", HFILL } \ }, \ { & name .hf.hs_ext_server_name_type, \ { "Server Name Type", prefix ".handshake.extensions_server_name_type", \ FT_UINT8, BASE_DEC, VALS(tls_hello_ext_server_name_type_vs), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_server_name, \ { "Server Name", prefix ".handshake.extensions_server_name", \ FT_STRING, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_padding_data, \ { "Padding Data", prefix ".handshake.extensions_padding_data", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Must be zero", HFILL } \ }, \ { & name .hf.hs_ext_cert_url_type, \ { "Certificate Chain Type", prefix ".handshake.cert_url_type", \ FT_UINT8, BASE_DEC, VALS(tls_cert_chain_type), 0x0, \ "Certificate Chain Type for Client Certificate URL", HFILL } \ }, \ { & name .hf.hs_ext_cert_url_url_hash_list_len, \ { "URL and Hash list Length", prefix ".handshake.cert_url.url_hash_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_url_item, \ { "URL and Hash", prefix ".handshake.cert_url.url_hash", \ FT_NONE, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_url_url_len, \ { "URL Length", prefix ".handshake.cert_url.url_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_type, \ { "Certificate Type", prefix ".handshake.cert_type.type", \ FT_UINT8, BASE_HEX, VALS(tls_certificate_type), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_types, \ { "Certificate Type List", prefix ".handshake.cert_type.types", \ FT_NONE, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_types_len, \ { "Certificate Type List Length", prefix ".handshake.cert_type.types_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_url_url, \ { "URL", prefix ".handshake.cert_url.url", \ FT_STRING, BASE_NONE, NULL, 0x0, \ "URL used to fetch the certificate(s)", HFILL } \ }, \ { & name .hf.hs_ext_cert_url_padding, \ { "Padding", prefix ".handshake.cert_url.padding", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "Padding that MUST be 0x01 for backwards compatibility", HFILL } \ }, \ { & name .hf.hs_ext_cert_url_sha1, \ { "SHA1 Hash", prefix ".handshake.cert_url.sha1", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "SHA1 Hash of the certificate", HFILL } \ }, \ { & name .hf.hs_ext_cert_status_type, \ { "Certificate Status Type", prefix ".handshake.extensions_status_request_type", \ FT_UINT8, BASE_DEC, VALS(tls_cert_status_type), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_status_request_len, \ { "Certificate Status Length", prefix ".handshake.extensions_status_request_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_status_responder_id_list_len, \ { "Responder ID list Length", prefix ".handshake.extensions_status_request_responder_ids_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_status_request_extensions_len, \ { "Request Extensions Length", prefix ".handshake.extensions_status_request_exts_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_cert_status_request_list_len, \ { "Certificate Status List Length", prefix ".handshake.extensions_status_request_list_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "CertificateStatusRequestItemV2 list length", HFILL } \ }, \ { & name .hf.hs_ocsp_response_list_len, \ { "OCSP Response List Length", prefix ".handshake.ocsp_response_list_len", \ FT_UINT24, BASE_DEC, NULL, 0x0, \ "OCSPResponseList length", HFILL } \ }, \ { & name .hf.hs_ocsp_response_len, \ { "OCSP Response Length", prefix ".handshake.ocsp_response_len", \ FT_UINT24, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_sig_hash_alg_len, \ { "Signature Hash Algorithms Length", prefix ".handshake.sig_hash_alg_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of Signature Hash Algorithms", HFILL } \ }, \ { & name .hf.hs_sig_hash_algs, \ { "Signature Algorithms", prefix ".handshake.sig_hash_algs", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of supported Signature Algorithms", HFILL } \ }, \ { & name .hf.hs_sig_hash_alg, \ { "Signature Algorithm", prefix ".handshake.sig_hash_alg", \ FT_UINT16, BASE_HEX, VALS(tls13_signature_algorithm), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_sig_hash_hash, \ { "Signature Hash Algorithm Hash", prefix ".handshake.sig_hash_hash", \ FT_UINT8, BASE_DEC, VALS(tls_hash_algorithm), 0x0, \ "Hash algorithm (TLS 1.2)", HFILL } \ }, \ { & name .hf.hs_sig_hash_sig, \ { "Signature Hash Algorithm Signature", prefix ".handshake.sig_hash_sig", \ FT_UINT8, BASE_DEC, VALS(tls_signature_algorithm), 0x0, \ "Signature algorithm (TLS 1.2)", HFILL } \ }, \ { & name .hf.hs_client_keyex_epms_len, \ { "Encrypted PreMaster length", prefix ".handshake.epms_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of encrypted PreMaster secret", HFILL } \ }, \ { & name .hf.hs_client_keyex_epms, \ { "Encrypted PreMaster", prefix ".handshake.epms", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Encrypted PreMaster secret", HFILL } \ }, \ { & name .hf.hs_server_keyex_modulus_len, \ { "Modulus Length", prefix ".handshake.modulus_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of RSA-EXPORT modulus", HFILL } \ }, \ { & name .hf.hs_server_keyex_exponent_len, \ { "Exponent Length", prefix ".handshake.exponent_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of RSA-EXPORT exponent", HFILL } \ }, \ { & name .hf.hs_server_keyex_sig_len, \ { "Signature Length", prefix ".handshake.sig_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of Signature", HFILL } \ }, \ { & name .hf.hs_server_keyex_p_len, \ { "p Length", prefix ".handshake.p_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of p", HFILL } \ }, \ { & name .hf.hs_server_keyex_g_len, \ { "g Length", prefix ".handshake.g_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of g", HFILL } \ }, \ { & name .hf.hs_server_keyex_ys_len, \ { "Pubkey Length", prefix ".handshake.ys_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of server's Diffie-Hellman public key", HFILL } \ }, \ { & name .hf.hs_client_keyex_yc_len, \ { "Pubkey Length", prefix ".handshake.yc_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of client's Diffie-Hellman public key", HFILL } \ }, \ { & name .hf.hs_client_keyex_point_len, \ { "Pubkey Length", prefix ".handshake.client_point_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of client's EC Diffie-Hellman public key", HFILL } \ }, \ { & name .hf.hs_server_keyex_point_len, \ { "Pubkey Length", prefix ".handshake.server_point_len", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of server's EC Diffie-Hellman public key", HFILL } \ }, \ { & name .hf.hs_server_keyex_p, \ { "p", prefix ".handshake.p", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Diffie-Hellman p", HFILL } \ }, \ { & name .hf.hs_server_keyex_g, \ { "g", prefix ".handshake.g", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Diffie-Hellman g", HFILL } \ }, \ { & name .hf.hs_server_keyex_curve_type, \ { "Curve Type", prefix ".handshake.server_curve_type", \ FT_UINT8, BASE_HEX, VALS(ssl_curve_types), 0x0, \ "Server curve_type", HFILL } \ }, \ { & name .hf.hs_server_keyex_named_curve, \ { "Named Curve", prefix ".handshake.server_named_curve", \ FT_UINT16, BASE_HEX, VALS(ssl_extension_curves), 0x0, \ "Server named_curve", HFILL } \ }, \ { & name .hf.hs_server_keyex_ys, \ { "Pubkey", prefix ".handshake.ys", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Diffie-Hellman server pubkey", HFILL } \ }, \ { & name .hf.hs_client_keyex_yc, \ { "Pubkey", prefix ".handshake.yc", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Diffie-Hellman client pubkey", HFILL } \ }, \ { & name .hf.hs_server_keyex_point, \ { "Pubkey", prefix ".handshake.server_point", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "EC Diffie-Hellman server pubkey", HFILL } \ }, \ { & name .hf.hs_client_keyex_point, \ { "Pubkey", prefix ".handshake.client_point", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "EC Diffie-Hellman client pubkey", HFILL } \ }, \ { & name .hf.hs_server_keyex_modulus, \ { "Modulus", prefix ".handshake.modulus", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "RSA-EXPORT modulus", HFILL } \ }, \ { & name .hf.hs_server_keyex_exponent, \ { "Exponent", prefix ".handshake.exponent", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "RSA-EXPORT exponent", HFILL } \ }, \ { & name .hf.hs_server_keyex_sig, \ { "Signature", prefix ".handshake.sig", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Diffie-Hellman server signature", HFILL } \ }, \ { & name .hf.hs_server_keyex_hint_len, \ { "Hint Length", prefix ".handshake.hint_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of PSK Hint", HFILL } \ }, \ { & name .hf.hs_server_keyex_hint, \ { "Hint", prefix ".handshake.hint", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "PSK Hint", HFILL } \ }, \ { & name .hf.hs_client_keyex_identity_len, \ { "Identity Length", prefix ".handshake.identity_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of PSK Identity", HFILL } \ }, \ { & name .hf.hs_client_keyex_identity, \ { "Identity", prefix ".handshake.identity", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "PSK Identity", HFILL } \ }, \ { & name .hf.hs_ext_heartbeat_mode, \ { "Mode", prefix ".handshake.extension.heartbeat.mode", \ FT_UINT8, BASE_DEC, VALS(tls_heartbeat_mode), 0x0, \ "Heartbeat extension mode", HFILL } \ }, \ { & name .hf.hs_certificates_len, \ { "Certificates Length", prefix ".handshake.certificates_length", \ FT_UINT24, BASE_DEC, NULL, 0x0, \ "Length of certificates field", HFILL } \ }, \ { & name .hf.hs_certificates, \ { "Certificates", prefix ".handshake.certificates", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of certificates", HFILL } \ }, \ { & name .hf.hs_certificate, \ { "Certificate", prefix ".handshake.certificate", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_certificate_len, \ { "Certificate Length", prefix ".handshake.certificate_length", \ FT_UINT24, BASE_DEC, NULL, 0x0, \ "Length of certificate", HFILL } \ }, \ { & name .hf.hs_cert_types_count, \ { "Certificate types count", prefix ".handshake.cert_types_count",\ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Count of certificate types", HFILL } \ }, \ { & name .hf.hs_cert_types, \ { "Certificate types", prefix ".handshake.cert_types", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of certificate types", HFILL } \ }, \ { & name .hf.hs_cert_type, \ { "Certificate type", prefix ".handshake.cert_type", \ FT_UINT8, BASE_DEC, VALS(ssl_31_client_certificate_type), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_dnames_len, \ { "Distinguished Names Length", prefix ".handshake.dnames_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of list of CAs that server trusts", HFILL } \ }, \ { & name .hf.hs_dnames, \ { "Distinguished Names", prefix ".handshake.dnames", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of CAs that server trusts", HFILL } \ }, \ { & name .hf.hs_dname_len, \ { "Distinguished Name Length", prefix ".handshake.dname_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of distinguished name", HFILL } \ }, \ { & name .hf.hs_dname, \ { "Distinguished Name", prefix ".handshake.dname", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "Distinguished name of a CA that server trusts", HFILL } \ }, \ { & name .hf.hs_random, \ { "Random", prefix ".handshake.random", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Random values used for deriving keys", HFILL } \ }, \ { & name .hf.hs_random_time, \ { "GMT Unix Time", prefix ".handshake.random_time", \ FT_ABSOLUTE_TIME, ABSOLUTE_TIME_LOCAL, NULL, 0x0, \ "Unix time field of random structure", HFILL } \ }, \ { & name .hf.hs_random_bytes, \ { "Random Bytes", prefix ".handshake.random_bytes", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Random values used for deriving keys", HFILL } \ }, \ { & name .hf.hs_session_id, \ { "Session ID", prefix ".handshake.session_id", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Identifies the SSL session, allowing later resumption", HFILL }\ }, \ { & name .hf.hs_session_id_len, \ { "Session ID Length", prefix ".handshake.session_id_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of Session ID field", HFILL } \ }, \ { & name .hf.hs_client_version, \ { "Version", prefix ".handshake.version", \ FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0, \ "Maximum version supported by client", HFILL } \ }, \ { & name .hf.hs_server_version, \ { "Version", prefix ".handshake.version", \ FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0, \ "Version selected by server", HFILL } \ }, \ { & name .hf.hs_cipher_suites_len, \ { "Cipher Suites Length", prefix ".handshake.cipher_suites_length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of cipher suites field", HFILL } \ }, \ { & name .hf.hs_cipher_suites, \ { "Cipher Suites", prefix ".handshake.ciphersuites", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of cipher suites supported by client", HFILL } \ }, \ { & name .hf.hs_cipher_suite, \ { "Cipher Suite", prefix ".handshake.ciphersuite", \ FT_UINT16, BASE_HEX|BASE_EXT_STRING, &ssl_31_ciphersuite_ext, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_comp_methods_len, \ { "Compression Methods Length", prefix ".handshake.comp_methods_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ "Length of compression methods field", HFILL } \ }, \ { & name .hf.hs_comp_methods, \ { "Compression Methods", prefix ".handshake.comp_methods", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "List of compression methods supported by client", HFILL } \ }, \ { & name .hf.hs_comp_method, \ { "Compression Method", prefix ".handshake.comp_method", \ FT_UINT8, BASE_DEC, VALS(ssl_31_compression_method), 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_session_ticket_lifetime_hint, \ { "Session Ticket Lifetime Hint", \ prefix ".handshake.session_ticket_lifetime_hint", \ FT_UINT32, BASE_DEC|BASE_UNIT_STRING, &units_second_seconds, 0x0, \ "New Session Ticket Lifetime Hint", HFILL } \ }, \ { & name .hf.hs_session_ticket_age_add, \ { "Session Ticket Age Add", \ prefix ".handshake.session_ticket_age_add", \ FT_UINT32, BASE_DEC, NULL, 0x0, \ "Random 32-bit value to obscure age of ticket", HFILL } \ }, \ { & name .hf.hs_session_ticket_nonce_len, \ { "Session Ticket Nonce Length", prefix ".handshake.session_ticket_nonce_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_session_ticket_nonce, \ { "Session Ticket Nonce", prefix ".handshake.session_ticket_nonce", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "A unique per-ticket value", HFILL } \ }, \ { & name .hf.hs_session_ticket_len, \ { "Session Ticket Length", prefix ".handshake.session_ticket_length", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "New Session Ticket Length", HFILL } \ }, \ { & name .hf.hs_session_ticket, \ { "Session Ticket", prefix ".handshake.session_ticket", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "New Session Ticket", HFILL } \ }, \ { & name .hf.hs_finished, \ { "Verify Data", prefix ".handshake.verify_data", \ FT_NONE, BASE_NONE, NULL, 0x0, \ "Opaque verification data", HFILL } \ }, \ { & name .hf.hs_client_cert_vrfy_sig_len, \ { "Signature length", prefix ".handshake.client_cert_vrfy.sig_len", \ FT_UINT16, BASE_DEC, NULL, 0x0, \ "Length of CertificateVerify's signature", HFILL } \ }, \ { & name .hf.hs_client_cert_vrfy_sig, \ { "Signature", prefix ".handshake.client_cert_vrfy.sig", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "CertificateVerify's signature", HFILL } \ }, \ { & name .hf.hs_ext_psk_ke_modes_length, \ { "PSK Key Exchange Modes Length", prefix ".extension.psk_ke_modes_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_psk_ke_mode, \ { "PSK Key Exchange Mode", prefix ".extension.psk_ke_mode", \ FT_UINT8, BASE_DEC, VALS(tls_hello_ext_psk_ke_mode), 0x0, \ "Key exchange modes where the client supports use of PSKs", HFILL } \ }, \ { & name .hf.hs_certificate_request_context_length, \ { "Certificate Request Context Length", prefix ".handshake.certificate_request_context_length", \ FT_UINT8, BASE_DEC, NULL, 0x0, \ NULL, HFILL } \ }, \ { & name .hf.hs_certificate_request_context, \ { "Certificate Request Context", prefix ".handshake.certificate_request_context", \ FT_BYTES, BASE_NONE, NULL, 0x0, \ "Value from CertificateRequest or empty for server auth", HFILL } \ }, \ { & name .hf.hs_key_update_request_update, \ { "Key Update Request", prefix ".handshake.key_update.request_update", \ FT_UINT8, BASE_DEC, VALS(tls13_key_update_request), 0x00, \ "Whether the receiver should also update its keys", HFILL } \ }, \ { & name .hf.sct_scts_length, \ { "Serialized SCT List Length", prefix ".sct.scts_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.sct_sct_length, \ { "Serialized SCT Length", prefix ".sct.sct_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.sct_sct_version, \ { "SCT Version", prefix ".sct.sct_version", \ FT_UINT8, BASE_DEC, NULL, 0x00, \ "SCT Protocol version (v1 (0) is defined in RFC 6962)", HFILL } \ }, \ { & name .hf.sct_sct_logid, \ { "Log ID", prefix ".sct.sct_logid", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "SHA-256 hash of log's public key", HFILL } \ }, \ { & name .hf.sct_sct_timestamp, \ { "Timestamp", prefix ".sct.sct_timestamp", \ FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0x00, \ "Timestamp of issuance", HFILL } \ }, \ { & name .hf.sct_sct_extensions_length, \ { "Extensions length", prefix ".sct.sct_extensions_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ "Length of future extensions to this protocol (currently none)", HFILL } \ }, \ { & name .hf.sct_sct_extensions, \ { "Extensions", prefix ".sct.sct_extensions", \ FT_NONE, BASE_NONE, NULL, 0x00, \ "Future extensions to this protocol (currently none)", HFILL } \ }, \ { & name .hf.sct_sct_signature_length, \ { "Signature Length", prefix ".sct.sct_signature_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.sct_sct_signature, \ { "Signature", prefix ".sct.sct_signature", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_max_early_data_size, \ { "Maximum Early Data Size", prefix ".early_data.max_early_data_size", \ FT_UINT32, BASE_DEC, NULL, 0x00, \ "Maximum amount of 0-RTT data that the client may send", HFILL } \ }, \ { & name .hf.hs_ext_oid_filters_length, \ { "OID Filters Length", prefix ".extension.oid_filters_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_oid_filters_oid_length, \ { "Certificate Extension OID Length", prefix ".extension.oid_filters.oid_length", \ FT_UINT8, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_oid_filters_oid, \ { "Certificate Extension OID", prefix ".extension.oid_filters.oid", \ FT_OID, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_oid_filters_values_length, \ { "Certificate Extension Values Length", prefix ".extension.oid_filters.values_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_compress_certificate_algorithms_length, \ { "Algorithms Length", prefix ".compress_certificate.algorithms_length", \ FT_UINT8, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_compress_certificate_algorithm, \ { "Algorithm", prefix ".compress_certificate.algorithm", \ FT_UINT16, BASE_DEC, VALS(compress_certificate_algorithm_vals), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_compress_certificate_uncompressed_length, \ { "Uncompressed Length", prefix ".compress_certificate.uncompressed_length", \ FT_UINT24, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_compress_certificate_compressed_certificate_message_length, \ { "Length", prefix ".compress_certificate.compressed_certificate_message.length", \ FT_UINT24, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_compress_certificate_compressed_certificate_message, \ { "Compressed Certificate Message", prefix ".compress_certificate.compressed_certificate_message", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_record_size_limit, \ { "Record Size Limit", prefix ".record_size_limit", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ "Maximum record size that an endpoint is willing to receive", HFILL } \ }, \ { & name .hf.hs_ext_quictp_negotiated_version, \ { "Negotiated Version", prefix ".quic.negotiated_version", \ FT_UINT32, BASE_HEX, VALS(quic_version_vals), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_initial_version, \ { "Initial Version", prefix ".quic.initial_version", \ FT_UINT32, BASE_HEX, VALS(quic_version_vals), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_supported_versions_len, \ { "Supported Versions Length", prefix ".quic.supported_versions.len", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_supported_versions, \ { "Supported Versions", prefix ".quic.supported_versions", \ FT_UINT32, BASE_HEX, VALS(quic_version_vals), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_len, \ { "Parameters Length", prefix ".quic.len", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter, \ { "Parameter", prefix ".quic.parameter", \ FT_NONE, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_type, \ { "Type", prefix ".quic.parameter.type", \ FT_UINT16, BASE_HEX, VALS(quic_transport_parameter_id), 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_len, \ { "Length", prefix ".quic.parameter.length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_value, \ { "Value", prefix ".quic.parameter.value", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_ocid, \ { "original_connection_id", prefix ".quic.parameter.ocid", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "The value of the Destination Connection ID field from the first Initial packet sent by the client", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_idle_timeout, \ { "idle_timeout", prefix ".quic.parameter.idle_timeout", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "In seconds", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_stateless_reset_token, \ { "stateless_reset_token", prefix ".quic.parameter.stateless_reset_token", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "Used in verifying a stateless reset", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_max_packet_size, \ { "max_packet_size", prefix ".quic.parameter.max_packet_size", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Indicates that packets larger than this limit will be dropped", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_data, \ { "initial_max_data", prefix ".quic.parameter.initial_max_data", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Contains the initial value for the maximum amount of data that can be sent on the connection", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_stream_data_bidi_local, \ { "initial_max_stream_data_bidi_local", prefix ".quic.parameter.initial_max_stream_data_bidi_local", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Initial stream maximum data for bidirectional, locally-initiated streams", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_stream_data_bidi_remote, \ { "initial_max_stream_data_bidi_remote", prefix ".quic.parameter.initial_max_stream_data_bidi_remote", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Initial stream maximum data for bidirectional, peer-initiated streams", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_stream_data_uni, \ { "initial_max_stream_data_uni", prefix ".quic.parameter.initial_max_stream_data_uni", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Initial stream maximum data for unidirectional streams parameter", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_streams_bidi, \ { "initial_max_streams_bidi", prefix ".quic.parameter.initial_max_streams_bidi", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Initial maximum number of application-owned bidirectional streams", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_initial_max_streams_uni, \ { "initial_max_streams_uni", prefix ".quic.parameter.initial_max_streams_uni", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Initial maximum number of application-owned unidirectional streams", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_ack_delay_exponent, \ { "ack_delay_exponent", prefix ".quic.parameter.ack_delay_exponent", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Indicating an exponent used to decode the ACK Delay field in the ACK frame,", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_max_ack_delay, \ { "max_ack_delay", prefix ".quic.parameter.max_ack_delay", \ FT_UINT64, BASE_DEC, NULL, 0x00, \ "Indicating the maximum amount of time in milliseconds by which it will delay sending of acknowledgments", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipversion, \ { "ipVersion", prefix ".quic.parameter.preferred_address.ipversion", \ FT_UINT8, BASE_DEC, VALS(quic_tp_preferred_address_vals), 0x00, \ "IP Version (until draft -17)", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipaddress_length, \ { "Length", prefix ".quic.parameter.preferred_address.ipaddress.length", \ FT_UINT8, BASE_DEC, NULL, 0x00, \ "Length of ipAddress field (until draft -17)", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipv4address, \ { "ipv4Address", prefix ".quic.parameter.preferred_address.ipv4address", \ FT_IPv4, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipv6address, \ { "ipv6Address", prefix ".quic.parameter.preferred_address.ipv6address", \ FT_IPv6, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipv4port, \ { "ipv4Port", prefix ".quic.parameter.preferred_address.ipv4port", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_ipv6port, \ { "ipv6Port", prefix ".quic.parameter.preferred_address.ipv6port", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_connectionid_length, \ { "Length", prefix ".quic.parameter.preferred_address.connectionid.length", \ FT_UINT8, BASE_DEC, NULL, 0x00, \ "Length of connectionId Field", HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_connectionid, \ { "connectionId", prefix ".quic.parameter.preferred_address.connectionid", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.hs_ext_quictp_parameter_pa_statelessresettoken, \ { "statelessResetToken", prefix ".quic.parameter.preferred_address.statelessresettoken", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.esni_suite, \ { "Cipher Suite", prefix ".esni.suite", \ FT_UINT16, BASE_HEX|BASE_EXT_STRING, &ssl_31_ciphersuite_ext, 0x0, \ "Cipher suite used to encrypt the SNI", HFILL } \ }, \ { & name .hf.esni_record_digest_length, \ { "Record Digest Length", prefix ".esni.record_digest_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.esni_record_digest, \ { "Record Digest", prefix ".esni.record_digest", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "Cryptographic hash of the ESNIKeys from which the ESNI key was obtained", HFILL } \ }, \ { & name .hf.esni_encrypted_sni_length, \ { "Encrypted SNI Length", prefix ".esni.encrypted_sni_length", \ FT_UINT16, BASE_DEC, NULL, 0x00, \ NULL, HFILL } \ }, \ { & name .hf.esni_encrypted_sni, \ { "Encrypted SNI", prefix ".esni.encrypted_sni", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "The encrypted ClientESNIInner structure", HFILL } \ }, \ { & name .hf.esni_nonce, \ { "Nonce", prefix ".esni.nonce", \ FT_BYTES, BASE_NONE, NULL, 0x00, \ "Contents of ClientESNIInner.nonce", HFILL } \ } /* }}} */ /* {{{ */ #define SSL_COMMON_ETT_LIST(name) \ & name .ett.hs_ext, \ & name .ett.hs_ext_alpn, \ & name .ett.hs_ext_cert_types, \ & name .ett.hs_ext_groups, \ & name .ett.hs_ext_curves_point_formats, \ & name .ett.hs_ext_npn, \ & name .ett.hs_ext_reneg_info, \ & name .ett.hs_ext_key_share, \ & name .ett.hs_ext_key_share_ks, \ & name .ett.hs_ext_pre_shared_key, \ & name .ett.hs_ext_psk_identity, \ & name .ett.hs_ext_server_name, \ & name .ett.hs_ext_oid_filter, \ & name .ett.hs_ext_quictp_parameter, \ & name .ett.hs_sig_hash_alg, \ & name .ett.hs_sig_hash_algs, \ & name .ett.urlhash, \ & name .ett.keyex_params, \ & name .ett.certificates, \ & name .ett.cert_types, \ & name .ett.dnames, \ & name .ett.hs_random, \ & name .ett.cipher_suites, \ & name .ett.comp_methods, \ & name .ett.session_ticket, \ & name .ett.sct, \ & name .ett.cert_status, \ & name .ett.ocsp_response, \ /* }}} */ /* {{{ */ #define SSL_COMMON_EI_LIST(name, prefix) \ { & name .ei.malformed_vector_length, \ { prefix ".malformed.vector_length", PI_PROTOCOL, PI_WARN, \ "Variable vector length is outside the permitted range", EXPFILL } \ }, \ { & name .ei.malformed_buffer_too_small, \ { prefix ".malformed.buffer_too_small", PI_MALFORMED, PI_ERROR, \ "Malformed message, not enough data is available", EXPFILL } \ }, \ { & name .ei.malformed_trailing_data, \ { prefix ".malformed.trailing_data", PI_PROTOCOL, PI_WARN, \ "Undecoded trailing data is present", EXPFILL } \ }, \ { & name .ei.hs_ext_cert_status_undecoded, \ { prefix ".handshake.status_request.undecoded", PI_UNDECODED, PI_NOTE, \ "Responder ID list or Request Extensions are not implemented, contact Wireshark developers if you want this to be supported", EXPFILL } \ }, \ { & name .ei.resumed, \ { prefix ".resumed", PI_SEQUENCE, PI_NOTE, \ "This session reuses previously negotiated keys (Session resumption)", EXPFILL } \ }, \ { & name .ei.record_length_invalid, \ { prefix ".record.length.invalid", PI_PROTOCOL, PI_ERROR, \ "Record fragment length is too large", EXPFILL } \ } /* }}} */ extern void ssl_common_register_ssl_alpn_dissector_table(const char *name, const char *ui_name, const int proto); extern void ssl_common_register_dtls_alpn_dissector_table(const char *name, const char *ui_name, const int proto); extern void ssl_common_register_options(module_t *module, ssl_common_options_t *options, gboolean is_dtls); #ifdef SSL_DECRYPT_DEBUG extern void ssl_debug_printf(const gchar* fmt,...) G_GNUC_PRINTF(1,2); extern void ssl_print_data(const gchar* name, const guchar* data, size_t len); extern void ssl_print_string(const gchar* name, const StringInfo* data); extern void ssl_set_debug(const gchar* name); extern void ssl_debug_flush(void); #else /* No debug: nullify debug operation*/ static inline void G_GNUC_PRINTF(1,2) ssl_debug_printf(const gchar* fmt _U_,...) { } #define ssl_print_data(a, b, c) #define ssl_print_string(a, b) #define ssl_set_debug(name) #define ssl_debug_flush() #endif /* SSL_DECRYPT_DEBUG */ #endif /* __PACKET_TLS_UTILS_H__ */ /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
55.133673
177
0.487647
[ "vector" ]
1b401fe9a4a6bcfc2908636ec00c08c9876460f0
2,010
h
C
Sources/Elastos/Runtime/Core/reflection/CAnnotationInfo.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Runtime/Core/reflection/CAnnotationInfo.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Runtime/Core/reflection/CAnnotationInfo.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #ifndef __CANNOTATIONINFO_H__ #define __CANNOTATIONINFO_H__ #include "CEntryList.h" class CAnnotationInfo : public ElLightRefBase , public IAnnotationInfo { public: CAnnotationInfo( /* [in] */ CClsModule* clsModule, /* [in] */ AnnotationDescriptor* annoDesc); virtual ~CAnnotationInfo(); CARAPI_(PInterface) Probe( /* [in] */ REIID riid); CARAPI_(UInt32) AddRef(); CARAPI_(UInt32) Release(); CARAPI GetInterfaceID( /* [in] */ IInterface* object, /* [out] */ InterfaceID* iid); CARAPI GetName( /* [out] */ String* name); CARAPI GetNamespace( /* [out] */ String* ns); CARAPI GetSize( /* [out] */ Int32* size); CARAPI GetKeys( /* [out, callee] */ ArrayOf<String>** keys); CARAPI GetValue( /* [in] */ const String& key, /* [out] */ String* value); CARAPI GetValues( /* [out, callee] */ ArrayOf<String>** values); private: CARAPI_(void) AcquireKeys(); CARAPI_(void) AcquireValues(); private: AnnotationDescriptor* mAnnotationDescriptor; AutoPtr< ArrayOf<String> > mKeys; AutoPtr< ArrayOf<String> > mValues; Int32 mBase; }; #endif // __CANNOTATIONINFO_H__
26.103896
75
0.6
[ "object" ]
1b4c9c0919c315521d425772318c9e0ccba1215a
568
h
C
examples/database/Database.h
Som1Lse/rapidcheck
2efe367a852a66dd2220c231775d018f7f4d4c24
[ "BSD-2-Clause" ]
876
2015-01-29T00:48:46.000Z
2022-03-23T00:24:34.000Z
examples/database/Database.h
wuerges/rapidcheck
d2e0481b28b77fcd0c7ead9af1e8227ee9982739
[ "BSD-2-Clause" ]
199
2015-05-18T07:04:40.000Z
2022-03-23T02:37:15.000Z
examples/database/Database.h
wuerges/rapidcheck
d2e0481b28b77fcd0c7ead9af1e8227ee9982739
[ "BSD-2-Clause" ]
162
2015-03-12T20:19:31.000Z
2022-03-14T08:42:52.000Z
#pragma once #include <string> #include <vector> #include <map> #include <memory> #include "User.h" class IDatabaseConnection; class Database { public: explicit Database(std::unique_ptr<IDatabaseConnection> connection); void open(); void close(); void beginWrite(); void executeWrite(); void put(User user); bool get(const std::string &username, User &user); private: bool m_open; std::unique_ptr<IDatabaseConnection> m_connection; std::map<std::string, User> m_cache; bool m_hasBlock; std::vector<User> m_queue; std::size_t m_hash; };
18.322581
69
0.716549
[ "vector" ]
1b4e45cda7b8a3b2be128248f1dea37316be47e3
3,655
c
C
d/islands/common/obj/flameguards.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
9
2021-07-05T15:24:54.000Z
2022-02-25T19:44:15.000Z
d/islands/common/obj/flameguards.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/islands/common/obj/flameguards.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
10
2021-03-13T00:18:03.000Z
2022-03-29T15:02:42.000Z
//Added Psion and cleaned up code a bit - Cythera 5/06 //Runs from inherit properly now. Nienne, 08/07 #include <std.h> inherit "/d/common/obj/armour/bracers.c"; void create(){ ::create(); set_name("bracers"); set_id(({ "flame guards", "guards", "bracers" })); set_short("%^RESET%^%^RED%^F%^BOLD%^l%^YELLOW%^a%^RESET%^%^ORANGE%^"+ "m%^RED%^e %^BOLD%^G%^YELLOW%^u%^RESET%^%^ORANGE%^a%^RED%^r"+ "%^BOLD%^d%^YELLOW%^s%^RESET%^"); set_obvious_short("%^RESET%^%^RED%^A pair of %^BOLD%^reddish%^RESET%^%^RED%^ bracers%^RESET%^"); set_long("%^RESET%^%^ORANGE%^These bracers are made of an odd metal"+ " with a faint %^BOLD%^%^RED%^reddish%^RESET%^%^ORANGE%^ tint."+ " The hue changes with the light seemingly like the "+ "dancing of a flickering %^RED%^f%^BOLD%^l%^RESET%^%^ORANGE%^"+ "a%^YELLOW%^m%^RESET%^%^RED%^e%^ORANGE%^."+" Small %^BOLD%^"+ "%^RED%^f%^YELLOW%^i%^RED%^re op%^YELLOW%^a%^RED%^ls%^RESET%^"+ "%^ORANGE%^ and %^RED%^f%^BOLD%^i%^RESET%^%^RED%^r%^BOLD%^e "+ "agates%^RESET%^%^ORANGE%^ line the front ends of the bracers "+ "and they sparkle softly with a faint %^RED%^red%^ORANGE%^ glow."+ " On top of each bracer there is a twisting tendrils of %^BOLD%^"+ "%^RED%^fire%^RESET%^%^ORANGE%^ motif.%^RESET%^"); set_value(30000); while((int)TO->query_property("enchantment") != 5) { TO->remove_property("enchantment"); TO->set_property("enchantment",5); } set_item_bonus("magic resistance",1); set_item_bonus("damage bonus",4); set_item_bonus("endurance",5); set_wear((:TO,"wear_func":)); set_remove((:TO,"remove_func":)); set_struck((:TO,"strike_func":)); set_lore("This set of bracers was made by the mage only known as Tornado,"+ " a follower of Akadi. Facinated with the power and grace of the elements"+ " for everday and combat use, he thought he would honor them with bracers."+ " He made a set of each element he thought worthy, it is no accident no "+ "guards of the earth were never made."); } int wear_func(){ ::check(); if(member_array("%^BOLD%^%^RED%^Defeated the great red wyrm Klauth!%^RESET%^",ETO->query_mini_quests())== -1) { tell_object(ETO,"You have not earned the right to make use of this item."); return 0; } if((int)ETO->query_level() < 35) { tell_object(ETO,"The bracers don't seem to fit you."); return 0; } tell_room(EETO,"%^RED%^%^BOLD%^Waves of heat rise up off "+ETO->QCN+" bracers"+ " as "+ETO->QS+" secures them in place.%^RESET%^",ETO); tell_object(ETO,"%^RED%^%^BOLD%^You feel a comforting heat as you "+ "secure the bracers on.%^RESET%^"); return 1; } int remove_func(){ tell_room(EETO,"%^RED%^%^BOLD%^"+ETO->QCN+"%^RED%^%^BOLD%^ reluctantly "+ "removes "+ETO->QP+" bracers.%^RESET%^",ETO); tell_object(ETO,"%^RED%^%^BOLD%^You reluctantly remove the bracers and feel"+ " a bond lessen.%^RESET%^"); return 1; } int strike_func(int damage, object what, object who){ if(!random(3)){ tell_room(environment(query_worn()),"%^RED%^%^BOLD%^"+ETO->QCN+" moves "+ "with the speed of an inferno to parry "+who->QCN+"'s attack.%^RESET%^",({ETO,who})); tell_object(ETO,"%^RED%^%^BOLD%^You feel a swift heat burn in you as you "+ "parry "+who->QCN+"'s attack.%^RESET%^"); tell_object(who,"%^RED%^%^BOLD%^"+ETOQCN+" moves with the speed of an inferno"+ " to parry your attack with "+ETO->QP+" bracers.%^RESET%^"); return 0 } return damage; }
45.6875
114
0.593434
[ "object" ]
1b4ec7fe0145a5b9d7b85899ed918f02a11ce4a8
309
c
C
testdata/K-and-R-exercises-and-examples/01.07-functions/e-1.15-fahrenheit.c
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
testdata/K-and-R-exercises-and-examples/01.07-functions/e-1.15-fahrenheit.c
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
testdata/K-and-R-exercises-and-examples/01.07-functions/e-1.15-fahrenheit.c
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
/* Rewrite the temperature conversion program of Section 1.2 to use a function. */ #include <stdio.h> float fahrenheit(int c); int main(void) { int i; for (i = 0; i <= 300; i+=20) printf("%3d %6.1f\n", i, fahrenheit(i)); return 0; } float fahrenheit(int c) { return ((5.0/9.0)*(c-32)); }
14.714286
64
0.598706
[ "3d" ]
1b50b1542615bba9ef511c7c63d8e822d1cf6451
4,023
h
C
mp2p_icp/include/mp2p_icp/Matcher_Points_Base.h
MOLAorg/mp2p_icp
04bf92da32ea54176171b5dc589219d932787c54
[ "BSD-3-Clause" ]
82
2019-06-09T15:33:07.000Z
2022-03-22T11:04:09.000Z
mp2p_icp/include/mp2p_icp/Matcher_Points_Base.h
MOLAorg/mp2p_icp
04bf92da32ea54176171b5dc589219d932787c54
[ "BSD-3-Clause" ]
null
null
null
mp2p_icp/include/mp2p_icp/Matcher_Points_Base.h
MOLAorg/mp2p_icp
04bf92da32ea54176171b5dc589219d932787c54
[ "BSD-3-Clause" ]
19
2019-06-19T10:05:08.000Z
2021-07-28T08:37:34.000Z
/* ------------------------------------------------------------------------- * A repertory of multi primitive-to-primitive (MP2P) ICP algorithms in C++ * Copyright (C) 2018-2021 Jose Luis Blanco, University of Almeria * See LICENSE for license information. * ------------------------------------------------------------------------- */ /** * @file Matcher_Points_Base.h * @brief Pointcloud matcher auxiliary class for iterating over point layers. * @author Jose Luis Blanco Claraco * @date June 25, 2020 */ #pragma once #include <mp2p_icp/Matcher.h> #include <mrpt/math/TPoint3D.h> #include <cstdlib> #include <limits> // std::numeric_limits #include <optional> #include <vector> namespace mp2p_icp { /** Pointcloud matcher auxiliary class for iterating over point layers. * * \ingroup mp2p_icp_grp */ class Matcher_Points_Base : public Matcher { public: Matcher_Points_Base() = default; /** Weights for each potential Local->Global point layer matching. * If empty, the output Pairings::point_weights * will left empty (=all points have equal weight). * \note Note: this field can be loaded from a configuration file via * initializeLayerWeights(). * * \note Map is: w["globalLayer"]["localLayer"]=weight; * */ std::map<std::string, std::map<std::string, double>> weight_pt2pt_layers; uint64_t maxLocalPointsPerLayer_ = 0; uint64_t localPointsSampleSeed_ = 0; /** Whether to allow matching points that have been already matched by a * former Matcher instance in the pipeline. */ bool allowMatchAlreadyMatchedPoints_ = false; /** Common parameters to all derived classes: * * - `maxLocalPointsPerLayer`: Maximum number of local points to consider * for the "local" point cloud, per point layer. "0" means "all" (no * decimation) [Default=0]. * * - `localPointsSampleSeed`: Only if `maxLocalPointsPerLayer`!=0, and the * number of points in the local map is larger than that number, a seed for * the RNG used to pick random point indices. `0` (default) means to use a * time-based seed. * * - `pointLayerMatches`: Optional map of layer names to relative weights. * Refer to example YAML files. * * - `allowMatchAlreadyMatchedPoints`: Optional (Default=false). Whether to * find matches for local points which were already paired by other matcher * in an earlier stage in the matchers pipeline. */ void initialize(const mrpt::containers::yaml& params) override; /** the output of transform_local_to_global() */ struct TransformedLocalPointCloud { public: mrpt::math::TPoint3Df localMin{fMax, fMax, fMax}; mrpt::math::TPoint3Df localMax{-fMax, -fMax, -fMax}; /** Reordering indexes, used only if we had to pick random indexes */ std::optional<std::vector<std::size_t>> idxs; /** Transformed local points: all, or a random subset */ mrpt::aligned_std_vector<float> x_locals, y_locals, z_locals; private: static constexpr auto fMax = std::numeric_limits<float>::max(); }; static TransformedLocalPointCloud transform_local_to_global( const mrpt::maps::CPointsMap& pcLocal, const mrpt::poses::CPose3D& localPose, const std::size_t maxLocalPoints = 0, const uint64_t localPointsSampleSeed = 0); protected: void impl_match( const metric_map_t& pcGlobal, const metric_map_t& pcLocal, const mrpt::poses::CPose3D& localPose, const MatchContext& mc, MatchState& ms, Pairings& out) const override final; private: virtual void implMatchOneLayer( const mrpt::maps::CMetricMap& pcGlobal, const mrpt::maps::CPointsMap& pcLocal, const mrpt::poses::CPose3D& localPose, MatchState& ms, const layer_name_t& globalName, const layer_name_t& localName, Pairings& out) const = 0; }; } // namespace mp2p_icp
36.572727
79
0.650012
[ "vector" ]
1b5439d39249625fe30eb72b89a1409b2a0564b8
6,004
h
C
zstd_v04.h
managata/zstd
ce3af1ce2bcf73e4848c364e7b52f468de9920f5
[ "BSD-3-Clause" ]
232
2017-09-11T14:28:41.000Z
2022-01-19T10:26:07.000Z
zstd_v04.h
managata/zstd
ce3af1ce2bcf73e4848c364e7b52f468de9920f5
[ "BSD-3-Clause" ]
302
2017-09-13T04:46:25.000Z
2018-09-06T22:14:06.000Z
zstd_v04.h
managata/zstd
ce3af1ce2bcf73e4848c364e7b52f468de9920f5
[ "BSD-3-Clause" ]
151
2017-09-11T21:03:07.000Z
2020-11-28T04:58:55.000Z
/** * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef ZSTD_V04_H_91868324769238 #define ZSTD_V04_H_91868324769238 #if defined (__cplusplus) extern "C" { #endif /* ************************************* * Includes ***************************************/ #include <stddef.h> /* size_t */ /* ************************************* * Simple one-step function ***************************************/ /** ZSTDv04_decompress() : decompress ZSTD frames compliant with v0.4.x format compressedSize : is the exact source size maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. It must be equal or larger than originalSize, otherwise decompression will fail. return : the number of bytes decompressed into destination buffer (originalSize) or an errorCode if it fails (which can be tested using ZSTDv01_isError()) */ size_t ZSTDv04_decompress( void* dst, size_t maxOriginalSize, const void* src, size_t compressedSize); /** ZSTDv04_getFrameSrcSize() : get the source length of a ZSTD frame compliant with v0.4.x format compressedSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' return : the number of bytes that would be read to decompress this frame or an errorCode if it fails (which can be tested using ZSTDv04_isError()) */ size_t ZSTDv04_findFrameCompressedSize(const void* src, size_t compressedSize); /** ZSTDv04_isError() : tells if the result of ZSTDv04_decompress() is an error */ unsigned ZSTDv04_isError(size_t code); /* ************************************* * Advanced functions ***************************************/ typedef struct ZSTDv04_Dctx_s ZSTDv04_Dctx; ZSTDv04_Dctx* ZSTDv04_createDCtx(void); size_t ZSTDv04_freeDCtx(ZSTDv04_Dctx* dctx); size_t ZSTDv04_decompressDCtx(ZSTDv04_Dctx* dctx, void* dst, size_t maxOriginalSize, const void* src, size_t compressedSize); /* ************************************* * Direct Streaming ***************************************/ size_t ZSTDv04_resetDCtx(ZSTDv04_Dctx* dctx); size_t ZSTDv04_nextSrcSizeToDecompress(ZSTDv04_Dctx* dctx); size_t ZSTDv04_decompressContinue(ZSTDv04_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); /** Use above functions alternatively. ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. Result is the number of bytes regenerated within 'dst'. It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. */ /* ************************************* * Buffered Streaming ***************************************/ typedef struct ZBUFFv04_DCtx_s ZBUFFv04_DCtx; ZBUFFv04_DCtx* ZBUFFv04_createDCtx(void); size_t ZBUFFv04_freeDCtx(ZBUFFv04_DCtx* dctx); size_t ZBUFFv04_decompressInit(ZBUFFv04_DCtx* dctx); size_t ZBUFFv04_decompressWithDictionary(ZBUFFv04_DCtx* dctx, const void* dict, size_t dictSize); size_t ZBUFFv04_decompressContinue(ZBUFFv04_DCtx* dctx, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr); /** ************************************************ * Streaming decompression * * A ZBUFF_DCtx object is required to track streaming operation. * Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources. * Use ZBUFF_decompressInit() to start a new decompression operation. * ZBUFF_DCtx objects can be reused multiple times. * * Optionally, a reference to a static dictionary can be set, using ZBUFF_decompressWithDictionary() * It must be the same content as the one set during compression phase. * Dictionary content must remain accessible during the decompression process. * * Use ZBUFF_decompressContinue() repetitively to consume your input. * *srcSizePtr and *maxDstSizePtr can be any size. * The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr. * Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. * The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst. * @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency) * or 0 when a frame is completely decoded * or an error code, which can be tested using ZBUFF_isError(). * * Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize / ZBUFF_recommendedDOutSize * output : ZBUFF_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded. * input : ZBUFF_recommendedDInSize==128Kb+3; just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . * **************************************************/ unsigned ZBUFFv04_isError(size_t errorCode); const char* ZBUFFv04_getErrorName(size_t errorCode); /** The below functions provide recommended buffer sizes for Compression or Decompression operations. * These sizes are not compulsory, they just tend to offer better latency */ size_t ZBUFFv04_recommendedDInSize(void); size_t ZBUFFv04_recommendedDOutSize(void); /* ************************************* * Prefix - version detection ***************************************/ #define ZSTDv04_magicNumber 0xFD2FB524 /* v0.4 */ #if defined (__cplusplus) } #endif #endif /* ZSTD_V04_H_91868324769238 */
43.824818
158
0.686209
[ "object" ]
1b561fbe262a945754305ac2b76412857b00ccab
709
c
C
sdk/lib/zxio/tests/c-compilation-test.c
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
sdk/lib/zxio/tests/c-compilation-test.c
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
sdk/lib/zxio/tests/c-compilation-test.c
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // To test C compilation, import every single public header from C: #include <lib/zxio/extensions.h> #include <lib/zxio/null.h> #include <lib/zxio/ops.h> #include <lib/zxio/types.h> #include <lib/zxio/zxio.h> #include <zxtest/zxtest.h> // Tests that the zxio headers can be used from C. zx_status_t test_close(zxio_t* io) { return ZX_OK; } TEST(Zxio, UseFromC) { zxio_storage_t object; zxio_ops_t ops = {}; memset(&ops, 0, sizeof(ops)); ops.close = test_close; zxio_init(&object.io, &ops); ASSERT_OK(zxio_close(&object.io)); }
26.259259
73
0.715092
[ "object" ]
1b669afe5a23c46b6d72c2b6739b89c724b42076
4,178
h
C
cq/CQParameters.h
ag4015/constant-q-cpp
8bd538cf52b12884f2119d168bfe18f63656c60c
[ "BSD-4-Clause-UC" ]
null
null
null
cq/CQParameters.h
ag4015/constant-q-cpp
8bd538cf52b12884f2119d168bfe18f63656c60c
[ "BSD-4-Clause-UC" ]
null
null
null
cq/CQParameters.h
ag4015/constant-q-cpp
8bd538cf52b12884f2119d168bfe18f63656c60c
[ "BSD-4-Clause-UC" ]
null
null
null
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Constant-Q library Copyright (c) 2013-2014 Queen Mary, University of London 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 AUTHOR 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. Except as contained in this notice, the names of the Centre for Digital Music; Queen Mary, University of London; and Chris Cannam shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. */ #ifndef CQ_PARAMETERS_H #define CQ_PARAMETERS_H #include "ConstantQConfig.h" /** * Common parameters for constructing Constant-Q implementation * objects (both forward and inverse transforms). */ class CQParameters { public: enum class WindowType { SqrtBlackmanHarris, SqrtBlackman, SqrtHann, BlackmanHarris, Blackman, Hann, }; enum class DecimatorType { BetterDecimator, FasterDecimator }; /** * Construct a set of parameters with the given input signal * sample rate, frequency range, and number of bins per * octave. The remaining parameters will take their usual * defaults; if you want to change them, just assign the * respective data members after construction. */ CQParameters(cq_float _sampleRate, cq_float _minFrequency, cq_float _maxFrequency, int _binsPerOctave) : sampleRate(_sampleRate), minFrequency(_minFrequency), maxFrequency(_maxFrequency), binsPerOctave(_binsPerOctave), q(1.0f), // Q scaling factor atomHopFactor(0.25f), // hop size of shortest temporal atom threshold(0.0005f), // sparsity threshold for resulting kernel window(CQParameters::WindowType::SqrtBlackmanHarris), // window shape decimator(CQParameters::DecimatorType::BetterDecimator) // decimator quality setting { } /** * Sampling rate of input signal. */ cq_float sampleRate; /** * Minimum frequency desired to include in Constant-Q output. The * actual minimum will normally be calculated as a round number of * octaves below the maximum frequency, and may differ from this. */ cq_float minFrequency; /** * Maximum frequency to include in Constant-Q output. */ cq_float maxFrequency; /** * Number of output frequency bins per octave. */ int binsPerOctave; /** * Spectral atom bandwidth scaling factor. q == 1 is optimal for * reconstruction, q < 1 increases redundancy (smearing) in the * frequency domain but improves time resolution. */ cq_float q; /** * Hop size between temporal atoms, where 1 == no overlap and * smaller values indicate overlapping atoms. */ cq_float atomHopFactor; /** * Sparsity threshold for Constant-Q kernel: values with magnitude * smaller than this are truncated to zero. */ cq_float threshold; /** * Window shape to use for the Constant-Q kernel atoms. */ WindowType window; /** * Quality setting for the sample rate decimator. */ DecimatorType decimator; }; #endif
31.179104
93
0.695548
[ "shape" ]
1b6d66d0a29e413aaa50296846116c55b5d9bfc2
821
h
C
PWG/muon/AliAnalysisTaskOnTheFlyAliAODDimuon.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWG/muon/AliAnalysisTaskOnTheFlyAliAODDimuon.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWG/muon/AliAnalysisTaskOnTheFlyAliAODDimuon.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
#ifndef ALIANALYSISTASKONTHEFLYALIAODDIMUON_H #define ALIANALYSISTASKONTHEFLYALIAODDIMUON_H #include "AliAnalysisTaskSE.h" /// /// Task to create (on-the-fly) from AODs the now deprecated AliAODDimuon object /// /// It is only intended to ease the transition to the direct usage of muon tracks /// instead of relying on this pre-computed object. /// /// \author L. Aphecetche /// class TClonesArray; class AliAnalysisTaskOnTheFlyAliAODDimuon : public AliAnalysisTaskSE { public: AliAnalysisTaskOnTheFlyAliAODDimuon(); virtual ~AliAnalysisTaskOnTheFlyAliAODDimuon(); virtual void UserExec(Option_t* opt); private: TClonesArray* fDimuons; //!<! (transient) storage for AliAODDimuon objects ClassDef(AliAnalysisTaskOnTheFlyAliAODDimuon,1) /// on the fly creation of (deprecated) dimuon object }; #endif
26.483871
103
0.778319
[ "object" ]
1b7698cc5b89f110e5ebd7460d8bec1712b610cd
105,420
h
C
src/gallium/drivers/swr/rasterizer/memory/StoreTile.h
pundiramit/external-mesa3d
c342483c57fa185ff67bd5ab7d82cb884e42684e
[ "MIT" ]
null
null
null
src/gallium/drivers/swr/rasterizer/memory/StoreTile.h
pundiramit/external-mesa3d
c342483c57fa185ff67bd5ab7d82cb884e42684e
[ "MIT" ]
null
null
null
src/gallium/drivers/swr/rasterizer/memory/StoreTile.h
pundiramit/external-mesa3d
c342483c57fa185ff67bd5ab7d82cb884e42684e
[ "MIT" ]
null
null
null
/**************************************************************************** * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE 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. * * @file StoreTile.h * * @brief Functionality for Store. * ******************************************************************************/ #pragma once #include "common/os.h" #include "common/formats.h" #include "core/context.h" #include "core/rdtsc_core.h" #include "core/format_conversion.h" #include "memory/TilingFunctions.h" #include "memory/Convert.h" #include "memory/SurfaceState.h" #include "core/multisample.h" #include <array> #include <sstream> #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) // Function pointer to different storing functions for color, depth, and stencil based on incoming formats. typedef void(*PFN_STORE_TILES)(uint8_t*, SWR_SURFACE_STATE*, uint32_t, uint32_t, uint32_t); ////////////////////////////////////////////////////////////////////////// /// Store Raster Tile Function Tables. ////////////////////////////////////////////////////////////////////////// extern PFN_STORE_TILES sStoreTilesTableColor[SWR_TILE_MODE_COUNT][NUM_SWR_FORMATS]; extern PFN_STORE_TILES sStoreTilesTableDepth[SWR_TILE_MODE_COUNT][NUM_SWR_FORMATS]; extern PFN_STORE_TILES sStoreTilesTableStencil[SWR_TILE_MODE_COUNT][NUM_SWR_FORMATS]; void InitStoreTilesTable_Linear_1(); void InitStoreTilesTable_Linear_2(); void InitStoreTilesTable_TileX_1(); void InitStoreTilesTable_TileX_2(); void InitStoreTilesTable_TileY_1(); void InitStoreTilesTable_TileY_2(); void InitStoreTilesTable_TileW(); void InitStoreTilesTable(); ////////////////////////////////////////////////////////////////////////// /// StorePixels /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <size_t PixelSize, size_t NumDests> struct StorePixels { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) = delete; }; ////////////////////////////////////////////////////////////////////////// /// StorePixels (32-bit pixel specialization) /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <> struct StorePixels<8, 2> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[2]) { // Each 4-pixel row is 4 bytes. const uint16_t* pPixSrc = (const uint16_t*)pSrc; // Unswizzle from SWR-Z order uint16_t* pRow = (uint16_t*)ppDsts[0]; pRow[0] = pPixSrc[0]; pRow[1] = pPixSrc[2]; pRow = (uint16_t*)ppDsts[1]; pRow[0] = pPixSrc[1]; pRow[1] = pPixSrc[3]; } }; template <> struct StorePixels<8, 4> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[4]) { // 8 x 2 bytes = 16 bytes, 16 pixels const uint16_t *pSrc16 = reinterpret_cast<const uint16_t *>(pSrc); uint16_t **ppDsts16 = reinterpret_cast<uint16_t **>(ppDsts); // Unswizzle from SWR-Z order ppDsts16[0][0] = pSrc16[0]; // 0 1 ppDsts16[0][1] = pSrc16[2]; // 4 5 ppDsts16[1][0] = pSrc16[1]; // 2 3 ppDsts16[1][1] = pSrc16[3]; // 6 7 ppDsts16[2][0] = pSrc16[4]; // 8 9 ppDsts16[2][1] = pSrc16[6]; // C D ppDsts16[3][0] = pSrc16[5]; // A B ppDsts16[3][1] = pSrc16[7]; // E F } }; ////////////////////////////////////////////////////////////////////////// /// StorePixels (32-bit pixel specialization) /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <> struct StorePixels<16, 2> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[2]) { // Each 4-pixel row is 8 bytes. const uint32_t* pPixSrc = (const uint32_t*)pSrc; // Unswizzle from SWR-Z order uint32_t* pRow = (uint32_t*)ppDsts[0]; pRow[0] = pPixSrc[0]; pRow[1] = pPixSrc[2]; pRow = (uint32_t*)ppDsts[1]; pRow[0] = pPixSrc[1]; pRow[1] = pPixSrc[3]; } }; template <> struct StorePixels<16, 4> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[4]) { // 8 x 4 bytes = 32 bytes, 16 pixels const uint32_t *pSrc32 = reinterpret_cast<const uint32_t *>(pSrc); uint32_t **ppDsts32 = reinterpret_cast<uint32_t **>(ppDsts); // Unswizzle from SWR-Z order ppDsts32[0][0] = pSrc32[0]; // 0 1 ppDsts32[0][1] = pSrc32[2]; // 4 5 ppDsts32[1][0] = pSrc32[1]; // 2 3 ppDsts32[1][1] = pSrc32[3]; // 6 7 ppDsts32[2][0] = pSrc32[4]; // 8 9 ppDsts32[2][1] = pSrc32[6]; // C D ppDsts32[3][0] = pSrc32[5]; // A B ppDsts32[3][1] = pSrc32[7]; // E F } }; ////////////////////////////////////////////////////////////////////////// /// StorePixels (32-bit pixel specialization) /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <> struct StorePixels<32, 2> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[2]) { // Each 4-pixel row is 16-bytes simd4scalari *pZRow01 = (simd4scalari*)pSrc; simd4scalari vQuad00 = SIMD128::load_si(pZRow01); simd4scalari vQuad01 = SIMD128::load_si(pZRow01 + 1); simd4scalari vRow00 = SIMD128::unpacklo_epi64(vQuad00, vQuad01); simd4scalari vRow10 = SIMD128::unpackhi_epi64(vQuad00, vQuad01); SIMD128::storeu_si((simd4scalari*)ppDsts[0], vRow00); SIMD128::storeu_si((simd4scalari*)ppDsts[1], vRow10); } }; template <> struct StorePixels<32, 4> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[4]) { // 4 x 16 bytes = 64 bytes, 16 pixels const simd4scalari *pSrc128 = reinterpret_cast<const simd4scalari *>(pSrc); simd4scalari **ppDsts128 = reinterpret_cast<simd4scalari **>(ppDsts); // Unswizzle from SWR-Z order simd4scalari quad0 = SIMD128::load_si(&pSrc128[0]); // 0 1 2 3 simd4scalari quad1 = SIMD128::load_si(&pSrc128[1]); // 4 5 6 7 simd4scalari quad2 = SIMD128::load_si(&pSrc128[2]); // 8 9 A B simd4scalari quad3 = SIMD128::load_si(&pSrc128[3]); // C D E F SIMD128::storeu_si(ppDsts128[0], SIMD128::unpacklo_epi64(quad0, quad1)); // 0 1 4 5 SIMD128::storeu_si(ppDsts128[1], SIMD128::unpackhi_epi64(quad0, quad1)); // 2 3 6 7 SIMD128::storeu_si(ppDsts128[2], SIMD128::unpacklo_epi64(quad2, quad3)); // 8 9 C D SIMD128::storeu_si(ppDsts128[3], SIMD128::unpackhi_epi64(quad2, quad3)); // A B E F } }; ////////////////////////////////////////////////////////////////////////// /// StorePixels (32-bit pixel specialization) /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <> struct StorePixels<64, 4> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[4]) { // Each 4-pixel row is 32 bytes. const simd4scalari* pPixSrc = (const simd4scalari*)pSrc; // order of pointers match SWR-Z layout simd4scalari** pvDsts = (simd4scalari**)&ppDsts[0]; *pvDsts[0] = pPixSrc[0]; *pvDsts[1] = pPixSrc[1]; *pvDsts[2] = pPixSrc[2]; *pvDsts[3] = pPixSrc[3]; } }; template <> struct StorePixels<64, 8> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[8]) { // 8 x 16 bytes = 128 bytes, 16 pixels const simd4scalari *pSrc128 = reinterpret_cast<const simd4scalari *>(pSrc); simd4scalari **ppDsts128 = reinterpret_cast<simd4scalari **>(ppDsts); // order of pointers match SWR-Z layout *ppDsts128[0] = pSrc128[0]; // 0 1 *ppDsts128[1] = pSrc128[1]; // 2 3 *ppDsts128[2] = pSrc128[2]; // 4 5 *ppDsts128[3] = pSrc128[3]; // 6 7 *ppDsts128[4] = pSrc128[4]; // 8 9 *ppDsts128[5] = pSrc128[5]; // A B *ppDsts128[6] = pSrc128[6]; // C D *ppDsts128[7] = pSrc128[7]; // E F } }; ////////////////////////////////////////////////////////////////////////// /// StorePixels (32-bit pixel specialization) /// @brief Stores a 4x2 (AVX) raster-tile to two rows. /// @param pSrc - Pointer to source raster tile in SWRZ pixel order /// @param ppDsts - Array of destination pointers. Each pointer is /// to a single row of at most 16B. /// @tparam NumDests - Number of destination pointers. Each pair of /// pointers is for a 16-byte column of two rows. ////////////////////////////////////////////////////////////////////////// template <> struct StorePixels<128, 8> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[8]) { // Each 4-pixel row is 64 bytes. const simd4scalari* pPixSrc = (const simd4scalari*)pSrc; // Unswizzle from SWR-Z order simd4scalari** pvDsts = (simd4scalari**)&ppDsts[0]; *pvDsts[0] = pPixSrc[0]; *pvDsts[1] = pPixSrc[2]; *pvDsts[2] = pPixSrc[1]; *pvDsts[3] = pPixSrc[3]; *pvDsts[4] = pPixSrc[4]; *pvDsts[5] = pPixSrc[6]; *pvDsts[6] = pPixSrc[5]; *pvDsts[7] = pPixSrc[7]; } }; template <> struct StorePixels<128, 16> { static void Store(const uint8_t* pSrc, uint8_t* (&ppDsts)[16]) { // 16 x 16 bytes = 256 bytes, 16 pixels const simd4scalari *pSrc128 = reinterpret_cast<const simd4scalari *>(pSrc); simd4scalari **ppDsts128 = reinterpret_cast<simd4scalari **>(ppDsts); for (uint32_t i = 0; i < 16; i += 4) { *ppDsts128[i + 0] = pSrc128[i + 0]; *ppDsts128[i + 1] = pSrc128[i + 2]; *ppDsts128[i + 2] = pSrc128[i + 1]; *ppDsts128[i + 3] = pSrc128[i + 3]; } } }; ////////////////////////////////////////////////////////////////////////// /// ConvertPixelsSOAtoAOS - Conversion for SIMD pixel (4x2 or 2x2) ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct ConvertPixelsSOAtoAOS { ////////////////////////////////////////////////////////////////////////// /// @brief Converts a SIMD from the Hot Tile to the destination format /// and converts from SOA to AOS. /// @param pSrc - Pointer to raster tile. /// @param pDst - Pointer to destination surface or deswizzling buffer. template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { static const uint32_t MAX_RASTER_TILE_BYTES = 16 * 16; // 16 pixels * 16 bytes per pixel OSALIGNSIMD16(uint8_t) soaTile[MAX_RASTER_TILE_BYTES] = {0}; OSALIGNSIMD16(uint8_t) aosTile[MAX_RASTER_TILE_BYTES] = {0}; // Convert from SrcFormat --> DstFormat simd16vector src; LoadSOA<SrcFormat>(pSrc, src); StoreSOA<DstFormat>(src, soaTile); // Convert from SOA --> AOS FormatTraits<DstFormat>::TransposeT::Transpose_simd16(soaTile, aosTile); // Store data into destination StorePixels<FormatTraits<DstFormat>::bpp, NumDests>::Store(aosTile, ppDsts); } }; ////////////////////////////////////////////////////////////////////////// /// ConvertPixelsSOAtoAOS - Conversion for SIMD pixel (4x2 or 2x2) /// Specialization for no format conversion ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT Format> struct ConvertPixelsSOAtoAOS<Format, Format> { ////////////////////////////////////////////////////////////////////////// /// @brief Converts a SIMD from the Hot Tile to the destination format /// and converts from SOA to AOS. /// @param pSrc - Pointer to raster tile. /// @param pDst - Pointer to destination surface or deswizzling buffer. template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { static const uint32_t MAX_RASTER_TILE_BYTES = 16 * 16; // 16 pixels * 16 bytes per pixel OSALIGNSIMD16(uint8_t) aosTile[MAX_RASTER_TILE_BYTES]; // Convert from SOA --> AOS FormatTraits<Format>::TransposeT::Transpose_simd16(pSrc, aosTile); // Store data into destination StorePixels<FormatTraits<Format>::bpp, NumDests>::Store(aosTile, ppDsts); } }; ////////////////////////////////////////////////////////////////////////// /// ConvertPixelsSOAtoAOS - Specialization conversion for B5G6R6_UNORM ////////////////////////////////////////////////////////////////////////// template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, B5G6R5_UNORM > { ////////////////////////////////////////////////////////////////////////// /// @brief Converts a SIMD from the Hot Tile to the destination format /// and converts from SOA to AOS. /// @param pSrc - Pointer to raster tile. /// @param pDst - Pointer to destination surface or deswizzling buffer. template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { static const SWR_FORMAT SrcFormat = R32G32B32A32_FLOAT; static const SWR_FORMAT DstFormat = B5G6R5_UNORM; static const uint32_t MAX_RASTER_TILE_BYTES = 16 * 16; // 16 pixels * 16 bytes per pixel OSALIGNSIMD16(uint8_t) aosTile[MAX_RASTER_TILE_BYTES]; // Load hot-tile simd16vector src, dst; LoadSOA<SrcFormat>(pSrc, src); // deswizzle dst.x = src[FormatTraits<DstFormat>::swizzle(0)]; dst.y = src[FormatTraits<DstFormat>::swizzle(1)]; dst.z = src[FormatTraits<DstFormat>::swizzle(2)]; // clamp dst.x = Clamp<DstFormat>(dst.x, 0); dst.y = Clamp<DstFormat>(dst.y, 1); dst.z = Clamp<DstFormat>(dst.z, 2); // normalize dst.x = Normalize<DstFormat>(dst.x, 0); dst.y = Normalize<DstFormat>(dst.y, 1); dst.z = Normalize<DstFormat>(dst.z, 2); // pack simd16scalari packed = _simd16_castps_si(dst.x); SWR_ASSERT(FormatTraits<DstFormat>::GetBPC(0) == 5); SWR_ASSERT(FormatTraits<DstFormat>::GetBPC(1) == 6); packed = _simd16_or_si(packed, _simd16_slli_epi32(_simd16_castps_si(dst.y), 5)); packed = _simd16_or_si(packed, _simd16_slli_epi32(_simd16_castps_si(dst.z), 5 + 6)); // pack low 16 bits of each 32 bit lane to low 128 bits of dst uint32_t *pPacked = (uint32_t*)&packed; uint16_t *pAosTile = (uint16_t*)&aosTile[0]; for (uint32_t t = 0; t < KNOB_SIMD16_WIDTH; ++t) { *pAosTile++ = *pPacked++; } // Store data into destination StorePixels<FormatTraits<DstFormat>::bpp, NumDests>::Store(aosTile, ppDsts); } }; ////////////////////////////////////////////////////////////////////////// /// ConvertPixelsSOAtoAOS - Conversion for SIMD pixel (4x2 or 2x2) ////////////////////////////////////////////////////////////////////////// template<> struct ConvertPixelsSOAtoAOS<R32_FLOAT, R24_UNORM_X8_TYPELESS> { static const SWR_FORMAT SrcFormat = R32_FLOAT; static const SWR_FORMAT DstFormat = R24_UNORM_X8_TYPELESS; ////////////////////////////////////////////////////////////////////////// /// @brief Converts a SIMD from the Hot Tile to the destination format /// and converts from SOA to AOS. /// @param pSrc - Pointer to raster tile. /// @param pDst - Pointer to destination surface or deswizzling buffer. template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { simd16scalar comp = _simd16_load_ps(reinterpret_cast<const float *>(pSrc)); // clamp const simd16scalar zero = _simd16_setzero_ps(); const simd16scalar ones = _simd16_set1_ps(1.0f); comp = _simd16_max_ps(comp, zero); comp = _simd16_min_ps(comp, ones); // normalize comp = _simd16_mul_ps(comp, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(0))); simd16scalari temp = _simd16_cvtps_epi32(comp); // swizzle temp = _simd16_permute_epi32(temp, _simd16_set_epi32(15, 14, 11, 10, 13, 12, 9, 8, 7, 6, 3, 2, 5, 4, 1, 0)); // merge/store data into destination but don't overwrite the X8 bits simdscalari destlo = _simd_loadu2_si(reinterpret_cast<simd4scalari *>(ppDsts[1]), reinterpret_cast<simd4scalari *>(ppDsts[0])); simdscalari desthi = _simd_loadu2_si(reinterpret_cast<simd4scalari *>(ppDsts[3]), reinterpret_cast<simd4scalari *>(ppDsts[2])); simd16scalari dest = _simd16_setzero_si(); dest = _simd16_insert_si(dest, destlo, 0); dest = _simd16_insert_si(dest, desthi, 1); simd16scalari mask = _simd16_set1_epi32(0x00FFFFFF); dest = _simd16_or_si(_simd16_andnot_si(mask, dest), _simd16_and_si(mask, temp)); _simd_storeu2_si(reinterpret_cast<simd4scalari *>(ppDsts[1]), reinterpret_cast<simd4scalari *>(ppDsts[0]), _simd16_extract_si(dest, 0)); _simd_storeu2_si(reinterpret_cast<simd4scalari *>(ppDsts[3]), reinterpret_cast<simd4scalari *>(ppDsts[2]), _simd16_extract_si(dest, 1)); } }; template<SWR_FORMAT DstFormat> INLINE static void FlatConvert(const uint8_t* pSrc, uint8_t* pDst0, uint8_t* pDst1, uint8_t* pDst2, uint8_t* pDst3) { // swizzle rgba -> bgra while we load simd16scalar comp0 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(0) * sizeof(simd16scalar))); // float32 rrrrrrrrrrrrrrrr simd16scalar comp1 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(1) * sizeof(simd16scalar))); // float32 gggggggggggggggg simd16scalar comp2 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(2) * sizeof(simd16scalar))); // float32 bbbbbbbbbbbbbbbb simd16scalar comp3 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(3) * sizeof(simd16scalar))); // float32 aaaaaaaaaaaaaaaa // clamp const simd16scalar zero = _simd16_setzero_ps(); const simd16scalar ones = _simd16_set1_ps(1.0f); comp0 = _simd16_max_ps(comp0, zero); comp0 = _simd16_min_ps(comp0, ones); comp1 = _simd16_max_ps(comp1, zero); comp1 = _simd16_min_ps(comp1, ones); comp2 = _simd16_max_ps(comp2, zero); comp2 = _simd16_min_ps(comp2, ones); comp3 = _simd16_max_ps(comp3, zero); comp3 = _simd16_min_ps(comp3, ones); // gamma-correct only rgb if (FormatTraits<DstFormat>::isSRGB) { comp0 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(0, comp0); comp1 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(1, comp1); comp2 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(2, comp2); } // convert float components from 0.0f..1.0f to correct scale for 0..255 dest format comp0 = _simd16_mul_ps(comp0, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(0))); comp1 = _simd16_mul_ps(comp1, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(1))); comp2 = _simd16_mul_ps(comp2, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(2))); comp3 = _simd16_mul_ps(comp3, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(3))); // moving to 16 wide integer vector types simd16scalari src0 = _simd16_cvtps_epi32(comp0); // padded byte rrrrrrrrrrrrrrrr simd16scalari src1 = _simd16_cvtps_epi32(comp1); // padded byte gggggggggggggggg simd16scalari src2 = _simd16_cvtps_epi32(comp2); // padded byte bbbbbbbbbbbbbbbb simd16scalari src3 = _simd16_cvtps_epi32(comp3); // padded byte aaaaaaaaaaaaaaaa // SOA to AOS conversion src1 = _simd16_slli_epi32(src1, 8); src2 = _simd16_slli_epi32(src2, 16); src3 = _simd16_slli_epi32(src3, 24); simd16scalari final = _simd16_or_si(_simd16_or_si(src0, src1), _simd16_or_si(src2, src3)); // 0 1 2 3 4 5 6 7 8 9 A B C D E F // de-swizzle conversion #if 1 simd16scalari final0 = _simd16_permute2f128_si(final, final, 0xA0); // (2, 2, 0, 0) // 0 1 2 3 0 1 2 3 8 9 A B 8 9 A B simd16scalari final1 = _simd16_permute2f128_si(final, final, 0xF5); // (3, 3, 1, 1) // 4 5 6 7 4 5 6 7 C D E F C D E F final = _simd16_shuffle_epi64(final0, final1, 0xCC); // (1 1 0 0 1 1 0 0) // 0 1 4 5 2 3 6 7 8 9 C D A B E F #else final = _simd16_permute_epi32(final, _simd16_set_epi32(15, 14, 11, 10, 13, 12, 9, 8, 7, 6, 3, 2, 5, 4, 1, 0)); #endif // store 8x2 memory order: // row0: [ pDst0, pDst2 ] = { 0 1 4 5 }, { 8 9 C D } // row1: [ pDst1, pDst3 ] = { 2 3 6 7 }, { A B E F } _simd_storeu2_si(reinterpret_cast<simd4scalari *>(pDst1), reinterpret_cast<simd4scalari *>(pDst0), _simd16_extract_si(final, 0)); _simd_storeu2_si(reinterpret_cast<simd4scalari *>(pDst3), reinterpret_cast<simd4scalari *>(pDst2), _simd16_extract_si(final, 1)); } template<SWR_FORMAT DstFormat> INLINE static void FlatConvert(const uint8_t* pSrc, uint8_t* pDst, uint8_t* pDst1) { static const uint32_t offset = sizeof(simdscalar); // swizzle rgba -> bgra while we load simdscalar vComp0 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(0))*offset)); // float32 rrrrrrrr simdscalar vComp1 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(1))*offset)); // float32 gggggggg simdscalar vComp2 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(2))*offset)); // float32 bbbbbbbb simdscalar vComp3 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(3))*offset)); // float32 aaaaaaaa // clamp vComp0 = _simd_max_ps(vComp0, _simd_setzero_ps()); vComp0 = _simd_min_ps(vComp0, _simd_set1_ps(1.0f)); vComp1 = _simd_max_ps(vComp1, _simd_setzero_ps()); vComp1 = _simd_min_ps(vComp1, _simd_set1_ps(1.0f)); vComp2 = _simd_max_ps(vComp2, _simd_setzero_ps()); vComp2 = _simd_min_ps(vComp2, _simd_set1_ps(1.0f)); vComp3 = _simd_max_ps(vComp3, _simd_setzero_ps()); vComp3 = _simd_min_ps(vComp3, _simd_set1_ps(1.0f)); if (FormatTraits<DstFormat>::isSRGB) { // Gamma-correct only rgb vComp0 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(0, vComp0); vComp1 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(1, vComp1); vComp2 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(2, vComp2); } // convert float components from 0.0f .. 1.0f to correct scale for 0 .. 255 dest format vComp0 = _simd_mul_ps(vComp0, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(0))); vComp1 = _simd_mul_ps(vComp1, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(1))); vComp2 = _simd_mul_ps(vComp2, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(2))); vComp3 = _simd_mul_ps(vComp3, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(3))); // moving to 8 wide integer vector types simdscalari src0 = _simd_cvtps_epi32(vComp0); // padded byte rrrrrrrr simdscalari src1 = _simd_cvtps_epi32(vComp1); // padded byte gggggggg simdscalari src2 = _simd_cvtps_epi32(vComp2); // padded byte bbbbbbbb simdscalari src3 = _simd_cvtps_epi32(vComp3); // padded byte aaaaaaaa #if KNOB_ARCH <= KNOB_ARCH_AVX // splitting into two sets of 4 wide integer vector types // because AVX doesn't have instructions to support this operation at 8 wide simd4scalari srcLo0 = _mm256_castsi256_si128(src0); // 000r000r000r000r simd4scalari srcLo1 = _mm256_castsi256_si128(src1); // 000g000g000g000g simd4scalari srcLo2 = _mm256_castsi256_si128(src2); // 000b000b000b000b simd4scalari srcLo3 = _mm256_castsi256_si128(src3); // 000a000a000a000a simd4scalari srcHi0 = _mm256_extractf128_si256(src0, 1); // 000r000r000r000r simd4scalari srcHi1 = _mm256_extractf128_si256(src1, 1); // 000g000g000g000g simd4scalari srcHi2 = _mm256_extractf128_si256(src2, 1); // 000b000b000b000b simd4scalari srcHi3 = _mm256_extractf128_si256(src3, 1); // 000a000a000a000a srcLo1 = _mm_slli_si128(srcLo1, 1); // 00g000g000g000g0 srcHi1 = _mm_slli_si128(srcHi1, 1); // 00g000g000g000g0 srcLo2 = _mm_slli_si128(srcLo2, 2); // 0b000b000b000b00 srcHi2 = _mm_slli_si128(srcHi2, 2); // 0b000b000b000b00 srcLo3 = _mm_slli_si128(srcLo3, 3); // a000a000a000a000 srcHi3 = _mm_slli_si128(srcHi3, 3); // a000a000a000a000 srcLo0 = SIMD128::or_si(srcLo0, srcLo1); // 00gr00gr00gr00gr srcLo2 = SIMD128::or_si(srcLo2, srcLo3); // ab00ab00ab00ab00 srcHi0 = SIMD128::or_si(srcHi0, srcHi1); // 00gr00gr00gr00gr srcHi2 = SIMD128::or_si(srcHi2, srcHi3); // ab00ab00ab00ab00 srcLo0 = SIMD128::or_si(srcLo0, srcLo2); // abgrabgrabgrabgr srcHi0 = SIMD128::or_si(srcHi0, srcHi2); // abgrabgrabgrabgr // unpack into rows that get the tiling order correct simd4scalari vRow00 = SIMD128::unpacklo_epi64(srcLo0, srcHi0); // abgrabgrabgrabgrabgrabgrabgrabgr simd4scalari vRow10 = SIMD128::unpackhi_epi64(srcLo0, srcHi0); simdscalari final = _mm256_castsi128_si256(vRow00); final = _mm256_insertf128_si256(final, vRow10, 1); #else // logic is as above, only wider src1 = _mm256_slli_si256(src1, 1); src2 = _mm256_slli_si256(src2, 2); src3 = _mm256_slli_si256(src3, 3); src0 = _mm256_or_si256(src0, src1); src2 = _mm256_or_si256(src2, src3); simdscalari final = _mm256_or_si256(src0, src2); // adjust the data to get the tiling order correct 0 1 2 3 -> 0 2 1 3 final = _mm256_permute4x64_epi64(final, 0xD8); #endif _simd_storeu2_si((simd4scalari*)pDst1, (simd4scalari*)pDst, final); } template<SWR_FORMAT DstFormat> INLINE static void FlatConvertNoAlpha(const uint8_t* pSrc, uint8_t* pDst0, uint8_t* pDst1, uint8_t* pDst2, uint8_t* pDst3) { // swizzle rgba -> bgra while we load simd16scalar comp0 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(0) * sizeof(simd16scalar))); // float32 rrrrrrrrrrrrrrrr simd16scalar comp1 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(1) * sizeof(simd16scalar))); // float32 gggggggggggggggg simd16scalar comp2 = _simd16_load_ps(reinterpret_cast<const float*>(pSrc + FormatTraits<DstFormat>::swizzle(2) * sizeof(simd16scalar))); // float32 bbbbbbbbbbbbbbbb // clamp const simd16scalar zero = _simd16_setzero_ps(); const simd16scalar ones = _simd16_set1_ps(1.0f); comp0 = _simd16_max_ps(comp0, zero); comp0 = _simd16_min_ps(comp0, ones); comp1 = _simd16_max_ps(comp1, zero); comp1 = _simd16_min_ps(comp1, ones); comp2 = _simd16_max_ps(comp2, zero); comp2 = _simd16_min_ps(comp2, ones); // gamma-correct only rgb if (FormatTraits<DstFormat>::isSRGB) { comp0 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(0, comp0); comp1 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(1, comp1); comp2 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(2, comp2); } // convert float components from 0.0f..1.0f to correct scale for 0..255 dest format comp0 = _simd16_mul_ps(comp0, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(0))); comp1 = _simd16_mul_ps(comp1, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(1))); comp2 = _simd16_mul_ps(comp2, _simd16_set1_ps(FormatTraits<DstFormat>::fromFloat(2))); // moving to 16 wide integer vector types simd16scalari src0 = _simd16_cvtps_epi32(comp0); // padded byte rrrrrrrrrrrrrrrr simd16scalari src1 = _simd16_cvtps_epi32(comp1); // padded byte gggggggggggggggg simd16scalari src2 = _simd16_cvtps_epi32(comp2); // padded byte bbbbbbbbbbbbbbbb // SOA to AOS conversion src1 = _simd16_slli_epi32(src1, 8); src2 = _simd16_slli_epi32(src2, 16); simd16scalari final = _simd16_or_si(_simd16_or_si(src0, src1), src2); // 0 1 2 3 4 5 6 7 8 9 A B C D E F // de-swizzle conversion #if 1 simd16scalari final0 = _simd16_permute2f128_si(final, final, 0xA0); // (2, 2, 0, 0) // 0 1 2 3 0 1 2 3 8 9 A B 8 9 A B simd16scalari final1 = _simd16_permute2f128_si(final, final, 0xF5); // (3, 3, 1, 1) // 4 5 6 7 4 5 6 7 C D E F C D E F final = _simd16_shuffle_epi64(final0, final1, 0xCC); // (1 1 0 0 1 1 0 0) // 0 1 4 5 2 3 6 7 8 9 C D A B E F #else final = _simd16_permute_epi32(final, _simd16_set_epi32(15, 14, 11, 10, 13, 12, 9, 8, 7, 6, 3, 2, 5, 4, 1, 0)); #endif // store 8x2 memory order: // row0: [ pDst0, pDst2 ] = { 0 1 4 5 }, { 8 9 C D } // row1: [ pDst1, pDst3 ] = { 2 3 6 7 }, { A B E F } _simd_storeu2_si(reinterpret_cast<simd4scalari *>(pDst1), reinterpret_cast<simd4scalari *>(pDst0), _simd16_extract_si(final, 0)); _simd_storeu2_si(reinterpret_cast<simd4scalari *>(pDst3), reinterpret_cast<simd4scalari *>(pDst2), _simd16_extract_si(final, 1)); } template<SWR_FORMAT DstFormat> INLINE static void FlatConvertNoAlpha(const uint8_t* pSrc, uint8_t* pDst, uint8_t* pDst1) { static const uint32_t offset = sizeof(simdscalar); // swizzle rgba -> bgra while we load simdscalar vComp0 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(0))*offset)); // float32 rrrrrrrr simdscalar vComp1 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(1))*offset)); // float32 gggggggg simdscalar vComp2 = _simd_load_ps((const float*)(pSrc + (FormatTraits<DstFormat>::swizzle(2))*offset)); // float32 bbbbbbbb // clamp vComp0 = _simd_max_ps(vComp0, _simd_setzero_ps()); vComp0 = _simd_min_ps(vComp0, _simd_set1_ps(1.0f)); vComp1 = _simd_max_ps(vComp1, _simd_setzero_ps()); vComp1 = _simd_min_ps(vComp1, _simd_set1_ps(1.0f)); vComp2 = _simd_max_ps(vComp2, _simd_setzero_ps()); vComp2 = _simd_min_ps(vComp2, _simd_set1_ps(1.0f)); if (FormatTraits<DstFormat>::isSRGB) { // Gamma-correct only rgb vComp0 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(0, vComp0); vComp1 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(1, vComp1); vComp2 = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(2, vComp2); } // convert float components from 0.0f .. 1.0f to correct scale for 0 .. 255 dest format vComp0 = _simd_mul_ps(vComp0, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(0))); vComp1 = _simd_mul_ps(vComp1, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(1))); vComp2 = _simd_mul_ps(vComp2, _simd_set1_ps(FormatTraits<DstFormat>::fromFloat(2))); // moving to 8 wide integer vector types simdscalari src0 = _simd_cvtps_epi32(vComp0); // padded byte rrrrrrrr simdscalari src1 = _simd_cvtps_epi32(vComp1); // padded byte gggggggg simdscalari src2 = _simd_cvtps_epi32(vComp2); // padded byte bbbbbbbb #if KNOB_ARCH <= KNOB_ARCH_AVX // splitting into two sets of 4 wide integer vector types // because AVX doesn't have instructions to support this operation at 8 wide simd4scalari srcLo0 = _mm256_castsi256_si128(src0); // 000r000r000r000r simd4scalari srcLo1 = _mm256_castsi256_si128(src1); // 000g000g000g000g simd4scalari srcLo2 = _mm256_castsi256_si128(src2); // 000b000b000b000b simd4scalari srcHi0 = _mm256_extractf128_si256(src0, 1); // 000r000r000r000r simd4scalari srcHi1 = _mm256_extractf128_si256(src1, 1); // 000g000g000g000g simd4scalari srcHi2 = _mm256_extractf128_si256(src2, 1); // 000b000b000b000b srcLo1 = _mm_slli_si128(srcLo1, 1); // 00g000g000g000g0 srcHi1 = _mm_slli_si128(srcHi1, 1); // 00g000g000g000g0 srcLo2 = _mm_slli_si128(srcLo2, 2); // 0b000b000b000b00 srcHi2 = _mm_slli_si128(srcHi2, 2); // 0b000b000b000b00 srcLo0 = SIMD128::or_si(srcLo0, srcLo1); // 00gr00gr00gr00gr srcHi0 = SIMD128::or_si(srcHi0, srcHi1); // 00gr00gr00gr00gr srcLo0 = SIMD128::or_si(srcLo0, srcLo2); // 0bgr0bgr0bgr0bgr srcHi0 = SIMD128::or_si(srcHi0, srcHi2); // 0bgr0bgr0bgr0bgr // unpack into rows that get the tiling order correct simd4scalari vRow00 = SIMD128::unpacklo_epi64(srcLo0, srcHi0); // 0bgr0bgr0bgr0bgr0bgr0bgr0bgr0bgr simd4scalari vRow10 = SIMD128::unpackhi_epi64(srcLo0, srcHi0); simdscalari final = _mm256_castsi128_si256(vRow00); final = _mm256_insertf128_si256(final, vRow10, 1); #else // logic is as above, only wider src1 = _mm256_slli_si256(src1, 1); src2 = _mm256_slli_si256(src2, 2); src0 = _mm256_or_si256(src0, src1); simdscalari final = _mm256_or_si256(src0, src2); // adjust the data to get the tiling order correct 0 1 2 3 -> 0 2 1 3 final = _mm256_permute4x64_epi64(final, 0xD8); #endif _simd_storeu2_si((simd4scalari*)pDst1, (simd4scalari*)pDst, final); } template<> struct ConvertPixelsSOAtoAOS<R32G32B32A32_FLOAT, B8G8R8A8_UNORM> { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvert<B8G8R8A8_UNORM>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS<R32G32B32A32_FLOAT, B8G8R8X8_UNORM> { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvertNoAlpha<B8G8R8X8_UNORM>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, B8G8R8A8_UNORM_SRGB > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvert<B8G8R8A8_UNORM_SRGB>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, B8G8R8X8_UNORM_SRGB > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvertNoAlpha<B8G8R8X8_UNORM_SRGB>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, R8G8B8A8_UNORM > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvert<R8G8B8A8_UNORM>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, R8G8B8X8_UNORM > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvertNoAlpha<R8G8B8X8_UNORM>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, R8G8B8A8_UNORM_SRGB > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvert<R8G8B8A8_UNORM_SRGB>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; template<> struct ConvertPixelsSOAtoAOS < R32G32B32A32_FLOAT, R8G8B8X8_UNORM_SRGB > { template <size_t NumDests> INLINE static void Convert(const uint8_t* pSrc, uint8_t* (&ppDsts)[NumDests]) { FlatConvertNoAlpha<R8G8B8X8_UNORM_SRGB>(pSrc, ppDsts[0], ppDsts[1], ppDsts[2], ppDsts[3]); } }; ////////////////////////////////////////////////////////////////////////// /// StoreRasterTile ////////////////////////////////////////////////////////////////////////// template<typename TTraits, SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct StoreRasterTile { ////////////////////////////////////////////////////////////////////////// /// @brief Retrieve color from hot tile source which is always float. /// @param pSrc - Pointer to raster tile. /// @param x, y - Coordinates to raster tile. /// @param output - output color INLINE static void GetSwizzledSrcColor( uint8_t* pSrc, uint32_t x, uint32_t y, float outputColor[4]) { typedef SimdTile_16<SrcFormat, DstFormat> SimdT; SimdT *pSrcSimdTiles = reinterpret_cast<SimdT *>(pSrc); // Compute which simd tile we're accessing within 8x8 tile. // i.e. Compute linear simd tile coordinate given (x, y) in pixel coordinates. uint32_t simdIndex = (y / SIMD16_TILE_Y_DIM) * (KNOB_TILE_X_DIM / SIMD16_TILE_X_DIM) + (x / SIMD16_TILE_X_DIM); SimdT *pSimdTile = &pSrcSimdTiles[simdIndex]; uint32_t simdOffset = (y % SIMD16_TILE_Y_DIM) * SIMD16_TILE_X_DIM + (x % SIMD16_TILE_X_DIM); pSimdTile->GetSwizzledColor(simdOffset, outputColor); } ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) // (x, y) pixel coordinate to start of raster tile. { uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); // For each raster tile pixel (rx, ry) for (uint32_t ry = 0; ry < KNOB_TILE_Y_DIM; ++ry) { for (uint32_t rx = 0; rx < KNOB_TILE_X_DIM; ++rx) { // Perform bounds checking. if (((x + rx) < lodWidth) && ((y + ry) < lodHeight)) { float srcColor[4]; GetSwizzledSrcColor(pSrc, rx, ry, srcColor); uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>((x + rx), (y + ry), pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); { ConvertPixelFromFloat<DstFormat>(pDst, srcColor); } } } } } ////////////////////////////////////////////////////////////////////////// /// @brief Resolves an 8x8 raster tile to the resolve destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. /// @param sampleOffset - Offset between adjacent multisamples INLINE static void Resolve( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleOffset, uint32_t renderTargetArrayIndex) // (x, y) pixel coordinate to start of raster tile. { uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); float oneOverNumSamples = 1.0f / pDstSurface->numSamples; // For each raster tile pixel (rx, ry) for (uint32_t ry = 0; ry < KNOB_TILE_Y_DIM; ++ry) { for (uint32_t rx = 0; rx < KNOB_TILE_X_DIM; ++rx) { // Perform bounds checking. if (((x + rx) < lodWidth) && ((y + ry) < lodHeight)) { // Sum across samples float resolveColor[4] = {0}; for (uint32_t sampleNum = 0; sampleNum < pDstSurface->numSamples; sampleNum++) { float sampleColor[4] = {0}; uint8_t *pSampleSrc = pSrc + sampleOffset * sampleNum; GetSwizzledSrcColor(pSampleSrc, rx, ry, sampleColor); resolveColor[0] += sampleColor[0]; resolveColor[1] += sampleColor[1]; resolveColor[2] += sampleColor[2]; resolveColor[3] += sampleColor[3]; } // Divide by numSamples to average resolveColor[0] *= oneOverNumSamples; resolveColor[1] *= oneOverNumSamples; resolveColor[2] *= oneOverNumSamples; resolveColor[3] *= oneOverNumSamples; // Use the resolve surface state SWR_SURFACE_STATE* pResolveSurface = (SWR_SURFACE_STATE*)pDstSurface->xpAuxBaseAddress; uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>((x + rx), (y + ry), pResolveSurface->arrayIndex + renderTargetArrayIndex, pResolveSurface->arrayIndex + renderTargetArrayIndex, 0, pResolveSurface->lod, pResolveSurface); { ConvertPixelFromFloat<DstFormat>(pDst, resolveColor); } } } } } }; template<typename TTraits, SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile : StoreRasterTile<TTraits, SrcFormat, DstFormat> {}; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_NONE specialization for 8bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_NONE, 8>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_NONE, 8>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * pDstSurface->pitch - KNOB_TILE_X_DIM * DST_BYTES_PER_PIXEL; uint8_t* ppDsts[] = { pDst, // row 0, col 0 pDst + pDstSurface->pitch, // row 1, col 0 pDst + dx / 2, // row 0, col 1 pDst + pDstSurface->pitch + dx / 2 // row 1, col 1 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { for (uint32_t xx = 0; xx < KNOB_TILE_X_DIM; xx += SIMD16_TILE_X_DIM) { ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dx; ppDsts[1] += dx; ppDsts[2] += dx; ppDsts[3] += dx; } ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_NONE specialization for 16bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_NONE, 16>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_NONE, 16>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * pDstSurface->pitch - KNOB_TILE_X_DIM * DST_BYTES_PER_PIXEL; uint8_t* ppDsts[] = { pDst, // row 0, col 0 pDst + pDstSurface->pitch, // row 1, col 0 pDst + dx / 2, // row 0, col 1 pDst + pDstSurface->pitch + dx / 2 // row 1, col 1 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { for (uint32_t xx = 0; xx < KNOB_TILE_X_DIM; xx += SIMD16_TILE_X_DIM) { ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dx; ppDsts[1] += dx; ppDsts[2] += dx; ppDsts[3] += dx; } ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_NONE specialization for 32bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_NONE, 32>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_NONE, 32>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * pDstSurface->pitch - KNOB_TILE_X_DIM * DST_BYTES_PER_PIXEL; uint8_t* ppDsts[] = { pDst, // row 0, col 0 pDst + pDstSurface->pitch, // row 1, col 0 pDst + dx / 2, // row 0, col 1 pDst + pDstSurface->pitch + dx / 2 // row 1, col 1 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { for (uint32_t xx = 0; xx < KNOB_TILE_X_DIM; xx += SIMD16_TILE_X_DIM) { ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dx; ppDsts[1] += dx; ppDsts[2] += dx; ppDsts[3] += dx; } ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_NONE specialization for 64bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_NONE, 64>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_NONE, 64>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; static const size_t MAX_DST_COLUMN_BYTES = 16; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * pDstSurface->pitch; // we have to break these large spans up, since ConvertPixelsSOAtoAOS() can only work on max 16B spans (a TileY limitation) static_assert(dx == MAX_DST_COLUMN_BYTES * 4, "Invalid column offsets"); uint8_t *ppDsts[] = { pDst, // row 0, col 0 pDst + pDstSurface->pitch, // row 1, col 0 pDst + MAX_DST_COLUMN_BYTES, // row 0, col 1 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES, // row 1, col 1 pDst + MAX_DST_COLUMN_BYTES * 2, // row 0, col 2 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 2, // row 1, col 2 pDst + MAX_DST_COLUMN_BYTES * 3, // row 0, col 3 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 3 // row 1, col 3 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; for (uint32_t i = 0; i < ARRAY_SIZE(ppDsts); i += 1) { ppDsts[i] += dy; } } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_NONE specialization for 128bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_NONE, 128>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_NONE, 128>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; static const size_t MAX_DST_COLUMN_BYTES = 16; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * pDstSurface->pitch; // we have to break these large spans up, since ConvertPixelsSOAtoAOS() can only work on max 16B spans (a TileY limitation) static_assert(dx == MAX_DST_COLUMN_BYTES * 8, "Invalid column offsets"); uint8_t* ppDsts[] = { pDst, // row 0, col 0 pDst + pDstSurface->pitch, // row 1, col 0 pDst + MAX_DST_COLUMN_BYTES, // row 0, col 1 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES, // row 1, col 1 pDst + MAX_DST_COLUMN_BYTES * 2, // row 0, col 2 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 2, // row 1, col 2 pDst + MAX_DST_COLUMN_BYTES * 3, // row 0, col 3 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 3, // row 1, col 3 pDst + MAX_DST_COLUMN_BYTES * 4, // row 0, col 4 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 4, // row 1, col 4 pDst + MAX_DST_COLUMN_BYTES * 5, // row 0, col 5 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 5, // row 1, col 5 pDst + MAX_DST_COLUMN_BYTES * 6, // row 0, col 6 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 6, // row 1, col 6 pDst + MAX_DST_COLUMN_BYTES * 7, // row 0, col 7 pDst + pDstSurface->pitch + MAX_DST_COLUMN_BYTES * 7, // row 1, col 7 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; for (uint32_t i = 0; i < ARRAY_SIZE(ppDsts); i += 1) { ppDsts[i] += dy; } } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - TILE_MODE_YMAJOR specialization for 8bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_YMAJOR, 8>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_YMAJOR, 8>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 16; // 16B rows // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileY is a column-major tiling mode where each 4KB tile consist of 8 columns of 32 x 16B rows. // We can compute the offsets to each column within the raster tile once and increment from these. // There will be 4 8x2 simd tiles in an 8x8 raster tile. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes; // The Hot Tile uses a row-major tiling mode and has a larger memory footprint. So we iterate in a row-major pattern. uint8_t *ppDsts[] = { pDst, pDst + DestRowWidthBytes, pDst + DestRowWidthBytes / 4, pDst + DestRowWidthBytes + DestRowWidthBytes / 4 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - TILE_MODE_YMAJOR specialization for 16bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_YMAJOR, 16>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_YMAJOR, 16>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 16; // 16B rows // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileY is a column-major tiling mode where each 4KB tile consist of 8 columns of 32 x 16B rows. // We can compute the offsets to each column within the raster tile once and increment from these. // There will be 4 8x2 simd tiles in an 8x8 raster tile. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes; // The Hot Tile uses a row-major tiling mode and has a larger memory footprint. So we iterate in a row-major pattern. uint8_t *ppDsts[] = { pDst, pDst + DestRowWidthBytes, pDst + DestRowWidthBytes / 2, pDst + DestRowWidthBytes + DestRowWidthBytes / 2 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - TILE_MODE_XMAJOR specialization for 32bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_XMAJOR, 32>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_XMAJOR, 32>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; static const size_t DST_BYTES_PER_PIXEL = FormatTraits<DstFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 512; // 512B rows // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileX is a row-major tiling mode where each 4KB tile consist of 8 x 512B rows. // We can compute the offsets to each column within the raster tile once and increment from these. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); const uint32_t dx = SIMD16_TILE_X_DIM * DST_BYTES_PER_PIXEL; const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes - KNOB_TILE_X_DIM * DST_BYTES_PER_PIXEL; uint8_t* ppDsts[] = { pDst, // row 0, col 0 pDst + DestRowWidthBytes, // row 1, col 0 pDst + dx / 2, // row 0, col 1 pDst + DestRowWidthBytes + dx / 2 // row 1, col 1 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { for (uint32_t xx = 0; xx < KNOB_TILE_X_DIM; xx += SIMD16_TILE_X_DIM) { ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dx; ppDsts[1] += dx; ppDsts[2] += dx; ppDsts[3] += dx; } ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - TILE_MODE_YMAJOR specialization for 32bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_YMAJOR, 32>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_YMAJOR, 32>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 16; // 16B rows static const uint32_t DestColumnBytes = DestRowWidthBytes * 32; // 16B x 32 rows. // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileY is a column-major tiling mode where each 4KB tile consist of 8 columns of 32 x 16B rows. // We can compute the offsets to each column within the raster tile once and increment from these. // There will be 4 8x2 simd tiles in an 8x8 raster tile. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); // we have to break these large spans up, since ConvertPixelsSOAtoAOS() can only work on max 16B spans (a TileY limitation) const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes; // The Hot Tile uses a row-major tiling mode and has a larger memory footprint. So we iterate in a row-major pattern. uint8_t *ppDsts[] = { pDst, // row 0, col 0 pDst + DestRowWidthBytes, // row 1, col 0 pDst + DestColumnBytes, // row 0, col 1 pDst + DestRowWidthBytes + DestColumnBytes // row 1, col 1 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; ppDsts[0] += dy; ppDsts[1] += dy; ppDsts[2] += dy; ppDsts[3] += dy; } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - TILE_MODE_YMAJOR specialization for 64bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_YMAJOR, 64>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_YMAJOR, 64>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 16; // 16B rows static const uint32_t DestColumnBytes = DestRowWidthBytes * 32; // 16B x 32 rows. // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileY is a column-major tiling mode where each 4KB tile consist of 8 columns of 32 x 16B rows. // We can compute the offsets to each column within the raster tile once and increment from these. // There will be 4 8x2 simd tiles in an 8x8 raster tile. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); // we have to break these large spans up, since ConvertPixelsSOAtoAOS() can only work on max 16B spans (a TileY limitation) const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes; // The Hot Tile uses a row-major tiling mode and has a larger memory footprint. So we iterate in a row-major pattern. uint8_t *ppDsts[] = { pDst, // row 0, col 0 pDst + DestRowWidthBytes, // row 1, col 0 pDst + DestColumnBytes, // row 0, col 1 pDst + DestRowWidthBytes + DestColumnBytes, // row 1, col 1 pDst + DestColumnBytes * 2, // row 0, col 2 pDst + DestRowWidthBytes + DestColumnBytes * 2, // row 1, col 2 pDst + DestColumnBytes * 3, // row 0, col 3 pDst + DestRowWidthBytes + DestColumnBytes * 3 // row 1, col 3 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; for (uint32_t i = 0; i < ARRAY_SIZE(ppDsts); i += 1) { ppDsts[i] += dy; } } } }; ////////////////////////////////////////////////////////////////////////// /// OptStoreRasterTile - SWR_TILE_MODE_YMAJOR specialization for 128bpp ////////////////////////////////////////////////////////////////////////// template<SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct OptStoreRasterTile< TilingTraits<SWR_TILE_MODE_YMAJOR, 128>, SrcFormat, DstFormat> { typedef StoreRasterTile<TilingTraits<SWR_TILE_MODE_YMAJOR, 128>, SrcFormat, DstFormat> GenericStoreTile; static const size_t SRC_BYTES_PER_PIXEL = FormatTraits<SrcFormat>::bpp / 8; ////////////////////////////////////////////////////////////////////////// /// @brief Stores an 8x8 raster tile to the destination surface. /// @param pSrc - Pointer to raster tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to raster tile. INLINE static void Store( uint8_t *pSrc, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t sampleNum, uint32_t renderTargetArrayIndex) { static const uint32_t DestRowWidthBytes = 16; // 16B rows static const uint32_t DestColumnBytes = DestRowWidthBytes * 32; // 16B x 32 rows. // Punt non-full tiles to generic store uint32_t lodWidth = std::max(pDstSurface->width >> pDstSurface->lod, 1U); uint32_t lodHeight = std::max(pDstSurface->height >> pDstSurface->lod, 1U); if (x + KNOB_TILE_X_DIM > lodWidth || y + KNOB_TILE_Y_DIM > lodHeight) { return GenericStoreTile::Store(pSrc, pDstSurface, x, y, sampleNum, renderTargetArrayIndex); } // TileY is a column-major tiling mode where each 4KB tile consist of 8 columns of 32 x 16B rows. // We can compute the offsets to each column within the raster tile once and increment from these. // There will be 4 8x2 simd tiles in an 8x8 raster tile. uint8_t *pDst = (uint8_t*)ComputeSurfaceAddress<false, false>(x, y, pDstSurface->arrayIndex + renderTargetArrayIndex, pDstSurface->arrayIndex + renderTargetArrayIndex, sampleNum, pDstSurface->lod, pDstSurface); // we have to break these large spans up, since ConvertPixelsSOAtoAOS() can only work on max 16B spans (a TileY limitation) const uint32_t dy = SIMD16_TILE_Y_DIM * DestRowWidthBytes; // The Hot Tile uses a row-major tiling mode and has a larger memory footprint. So we iterate in a row-major pattern. uint8_t *ppDsts[] = { pDst, // row 0, col 0 pDst + DestRowWidthBytes, // row 1, col 0 pDst + DestColumnBytes, // row 0, col 1 pDst + DestRowWidthBytes + DestColumnBytes, // row 1, col 1 pDst + DestColumnBytes * 2, // row 0, col 2 pDst + DestRowWidthBytes + DestColumnBytes * 2, // row 1, col 2 pDst + DestColumnBytes * 3, // row 0, col 3 pDst + DestRowWidthBytes + DestColumnBytes * 3, // row 1, col 3 pDst + DestColumnBytes * 4, // row 0, col 4 pDst + DestRowWidthBytes + DestColumnBytes * 4, // row 1, col 4 pDst + DestColumnBytes * 5, // row 0, col 5 pDst + DestRowWidthBytes + DestColumnBytes * 5, // row 1, col 5 pDst + DestColumnBytes * 6, // row 0, col 6 pDst + DestRowWidthBytes + DestColumnBytes * 6, // row 1, col 6 pDst + DestColumnBytes * 7, // row 0, col 7 pDst + DestRowWidthBytes + DestColumnBytes * 7 // row 1, col 7 }; for (uint32_t yy = 0; yy < KNOB_TILE_Y_DIM; yy += SIMD16_TILE_Y_DIM) { // Raster tile width is same as simd16 tile width static_assert(KNOB_TILE_X_DIM == SIMD16_TILE_X_DIM, "Invalid tile x dim"); ConvertPixelsSOAtoAOS<SrcFormat, DstFormat>::Convert(pSrc, ppDsts); pSrc += KNOB_SIMD16_WIDTH * SRC_BYTES_PER_PIXEL; for (uint32_t i = 0; i < ARRAY_SIZE(ppDsts); i += 1) { ppDsts[i] += dy; } } } }; ////////////////////////////////////////////////////////////////////////// /// StoreMacroTile - Stores a macro tile which consists of raster tiles. ////////////////////////////////////////////////////////////////////////// template<typename TTraits, SWR_FORMAT SrcFormat, SWR_FORMAT DstFormat> struct StoreMacroTile { ////////////////////////////////////////////////////////////////////////// /// @brief Stores a macrotile to the destination surface using safe implementation. /// @param pSrc - Pointer to macro tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to macro tile static void StoreGeneric( uint8_t *pSrcHotTile, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t renderTargetArrayIndex) { PFN_STORE_TILES_INTERNAL pfnStore; pfnStore = StoreRasterTile<TTraits, SrcFormat, DstFormat>::Store; // Store each raster tile from the hot tile to the destination surface. for (uint32_t row = 0; row < KNOB_MACROTILE_Y_DIM; row += KNOB_TILE_Y_DIM) { for (uint32_t col = 0; col < KNOB_MACROTILE_X_DIM; col += KNOB_TILE_X_DIM) { for (uint32_t sampleNum = 0; sampleNum < pDstSurface->numSamples; sampleNum++) { pfnStore(pSrcHotTile, pDstSurface, (x + col), (y + row), sampleNum, renderTargetArrayIndex); pSrcHotTile += KNOB_TILE_X_DIM * KNOB_TILE_Y_DIM * (FormatTraits<SrcFormat>::bpp / 8); } } } } typedef void(*PFN_STORE_TILES_INTERNAL)(uint8_t*, SWR_SURFACE_STATE*, uint32_t, uint32_t, uint32_t, uint32_t); ////////////////////////////////////////////////////////////////////////// /// @brief Stores a macrotile to the destination surface. /// @param pSrc - Pointer to macro tile. /// @param pDstSurface - Destination surface state /// @param x, y - Coordinates to macro tile static void Store( uint8_t *pSrcHotTile, SWR_SURFACE_STATE* pDstSurface, uint32_t x, uint32_t y, uint32_t renderTargetArrayIndex) { PFN_STORE_TILES_INTERNAL pfnStore[SWR_MAX_NUM_MULTISAMPLES]; for (uint32_t sampleNum = 0; sampleNum < pDstSurface->numSamples; sampleNum++) { size_t dstSurfAddress = (size_t)ComputeSurfaceAddress<false, false>( 0, 0, pDstSurface->arrayIndex + renderTargetArrayIndex, // z for 3D surfaces pDstSurface->arrayIndex + renderTargetArrayIndex, // array index for 2D arrays sampleNum, pDstSurface->lod, pDstSurface); // Only support generic store-tile if lod surface doesn't start on a page boundary and is non-linear bool bForceGeneric = ((pDstSurface->tileMode != SWR_TILE_NONE) && (0 != (dstSurfAddress & 0xfff))) || (pDstSurface->bInterleavedSamples); pfnStore[sampleNum] = (bForceGeneric || KNOB_USE_GENERIC_STORETILE) ? StoreRasterTile<TTraits, SrcFormat, DstFormat>::Store : OptStoreRasterTile<TTraits, SrcFormat, DstFormat>::Store; } // Save original for pSrcHotTile resolve. uint8_t *pResolveSrcHotTile = pSrcHotTile; // Store each raster tile from the hot tile to the destination surface. for(uint32_t row = 0; row < KNOB_MACROTILE_Y_DIM; row += KNOB_TILE_Y_DIM) { for(uint32_t col = 0; col < KNOB_MACROTILE_X_DIM; col += KNOB_TILE_X_DIM) { for(uint32_t sampleNum = 0; sampleNum < pDstSurface->numSamples; sampleNum++) { pfnStore[sampleNum](pSrcHotTile, pDstSurface, (x + col), (y + row), sampleNum, renderTargetArrayIndex); pSrcHotTile += KNOB_TILE_X_DIM * KNOB_TILE_Y_DIM * (FormatTraits<SrcFormat>::bpp / 8); } } } if (pDstSurface->xpAuxBaseAddress) { uint32_t sampleOffset = KNOB_TILE_X_DIM * KNOB_TILE_Y_DIM * (FormatTraits<SrcFormat>::bpp / 8); // Store each raster tile from the hot tile to the destination surface. for(uint32_t row = 0; row < KNOB_MACROTILE_Y_DIM; row += KNOB_TILE_Y_DIM) { for(uint32_t col = 0; col < KNOB_MACROTILE_X_DIM; col += KNOB_TILE_X_DIM) { StoreRasterTile<TTraits, SrcFormat, DstFormat>::Resolve(pResolveSrcHotTile, pDstSurface, (x + col), (y + row), sampleOffset, renderTargetArrayIndex); pResolveSrcHotTile += sampleOffset * pDstSurface->numSamples; } } } } }; ////////////////////////////////////////////////////////////////////////// /// InitStoreTilesTable - Helper for setting up the tables. template <SWR_TILE_MODE TTileMode, size_t NumTileModesT, size_t ArraySizeT> void InitStoreTilesTableColor_Half1( PFN_STORE_TILES (&table)[NumTileModesT][ArraySizeT]) { table[TTileMode][R32G32B32A32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32A32_FLOAT>::Store; table[TTileMode][R32G32B32A32_SINT] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32A32_SINT>::Store; table[TTileMode][R32G32B32A32_UINT] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32A32_UINT>::Store; table[TTileMode][R32G32B32X32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32X32_FLOAT>::Store; table[TTileMode][R32G32B32A32_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32A32_SSCALED>::Store; table[TTileMode][R32G32B32A32_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 128>, R32G32B32A32_FLOAT, R32G32B32A32_USCALED>::Store; table[TTileMode][R32G32B32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 96>, R32G32B32A32_FLOAT, R32G32B32_FLOAT>::Store; table[TTileMode][R32G32B32_SINT] = StoreMacroTile<TilingTraits<TTileMode, 96>, R32G32B32A32_FLOAT, R32G32B32_SINT>::Store; table[TTileMode][R32G32B32_UINT] = StoreMacroTile<TilingTraits<TTileMode, 96>, R32G32B32A32_FLOAT, R32G32B32_UINT>::Store; table[TTileMode][R32G32B32_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 96>, R32G32B32A32_FLOAT, R32G32B32_SSCALED>::Store; table[TTileMode][R32G32B32_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 96>, R32G32B32A32_FLOAT, R32G32B32_USCALED>::Store; table[TTileMode][R16G16B16A16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_UNORM>::Store; table[TTileMode][R16G16B16A16_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_SNORM>::Store; table[TTileMode][R16G16B16A16_SINT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_SINT>::Store; table[TTileMode][R16G16B16A16_UINT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_UINT>::Store; table[TTileMode][R16G16B16A16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_FLOAT>::Store; table[TTileMode][R32G32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32G32_FLOAT>::Store; table[TTileMode][R32G32_SINT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32G32_SINT>::Store; table[TTileMode][R32G32_UINT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32G32_UINT>::Store; table[TTileMode][R32_FLOAT_X8X24_TYPELESS] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32_FLOAT_X8X24_TYPELESS>::Store; table[TTileMode][X32_TYPELESS_G8X24_UINT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, X32_TYPELESS_G8X24_UINT>::Store; table[TTileMode][R16G16B16X16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16X16_UNORM>::Store; table[TTileMode][R16G16B16X16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16X16_FLOAT>::Store; table[TTileMode][R16G16B16A16_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_SSCALED>::Store; table[TTileMode][R16G16B16A16_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R16G16B16A16_USCALED>::Store; table[TTileMode][R32G32_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32G32_SSCALED>::Store; table[TTileMode][R32G32_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32G32B32A32_FLOAT, R32G32_USCALED>::Store; table[TTileMode][B8G8R8A8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B8G8R8A8_UNORM>::Store; table[TTileMode][B8G8R8A8_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B8G8R8A8_UNORM_SRGB>::Store; table[TTileMode][R10G10B10A2_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_UNORM>::StoreGeneric; table[TTileMode][R10G10B10A2_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_UNORM_SRGB>::StoreGeneric; table[TTileMode][R10G10B10A2_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_UINT>::StoreGeneric; table[TTileMode][R8G8B8A8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_UNORM>::Store; table[TTileMode][R8G8B8A8_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_UNORM_SRGB>::Store; table[TTileMode][R8G8B8A8_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_SNORM>::Store; table[TTileMode][R8G8B8A8_SINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_SINT>::Store; table[TTileMode][R8G8B8A8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_UINT>::Store; table[TTileMode][R16G16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_UNORM>::Store; table[TTileMode][R16G16_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_SNORM>::Store; table[TTileMode][R16G16_SINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_SINT>::Store; table[TTileMode][R16G16_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_UINT>::Store; table[TTileMode][R16G16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_FLOAT>::Store; table[TTileMode][B10G10R10A2_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_UNORM>::StoreGeneric; table[TTileMode][B10G10R10A2_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_UNORM_SRGB>::StoreGeneric; table[TTileMode][R11G11B10_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R11G11B10_FLOAT>::StoreGeneric; table[TTileMode][R10G10B10_FLOAT_A2_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10_FLOAT_A2_UNORM>::StoreGeneric; table[TTileMode][R32_SINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R32_SINT>::Store; table[TTileMode][R32_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R32_UINT>::Store; table[TTileMode][R32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R32_FLOAT>::Store; table[TTileMode][R24_UNORM_X8_TYPELESS] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R24_UNORM_X8_TYPELESS>::StoreGeneric; table[TTileMode][X24_TYPELESS_G8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, X24_TYPELESS_G8_UINT>::StoreGeneric; table[TTileMode][A32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, A32_FLOAT>::Store; table[TTileMode][B8G8R8X8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B8G8R8X8_UNORM>::Store; table[TTileMode][B8G8R8X8_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B8G8R8X8_UNORM_SRGB>::Store; table[TTileMode][R8G8B8X8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8X8_UNORM>::Store; table[TTileMode][R8G8B8X8_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8X8_UNORM_SRGB>::Store; } template <SWR_TILE_MODE TTileMode, size_t NumTileModesT, size_t ArraySizeT> void InitStoreTilesTableColor_Half2( PFN_STORE_TILES(&table)[NumTileModesT][ArraySizeT]) { table[TTileMode][R9G9B9E5_SHAREDEXP] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R9G9B9E5_SHAREDEXP>::StoreGeneric; table[TTileMode][B10G10R10X2_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10X2_UNORM>::StoreGeneric; table[TTileMode][R10G10B10X2_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10X2_USCALED>::StoreGeneric; table[TTileMode][R8G8B8A8_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_SSCALED>::Store; table[TTileMode][R8G8B8A8_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R8G8B8A8_USCALED>::Store; table[TTileMode][R16G16_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_SSCALED>::Store; table[TTileMode][R16G16_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R16G16_USCALED>::Store; table[TTileMode][R32_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R32_SSCALED>::Store; table[TTileMode][R32_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R32_USCALED>::Store; table[TTileMode][B5G6R5_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G6R5_UNORM>::Store; table[TTileMode][B5G6R5_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G6R5_UNORM_SRGB>::StoreGeneric; table[TTileMode][B5G5R5A1_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G5R5A1_UNORM>::StoreGeneric; table[TTileMode][B5G5R5A1_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G5R5A1_UNORM_SRGB>::StoreGeneric; table[TTileMode][B4G4R4A4_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B4G4R4A4_UNORM>::StoreGeneric; table[TTileMode][B4G4R4A4_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B4G4R4A4_UNORM_SRGB>::StoreGeneric; table[TTileMode][R8G8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_UNORM>::Store; table[TTileMode][R8G8_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_SNORM>::Store; table[TTileMode][R8G8_SINT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_SINT>::Store; table[TTileMode][R8G8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_UINT>::Store; table[TTileMode][R16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_UNORM>::Store; table[TTileMode][R16_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_SNORM>::Store; table[TTileMode][R16_SINT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_SINT>::Store; table[TTileMode][R16_UINT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_UINT>::Store; table[TTileMode][R16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_FLOAT>::Store; table[TTileMode][A16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, A16_UNORM>::Store; table[TTileMode][A16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, A16_FLOAT>::Store; table[TTileMode][B5G5R5X1_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G5R5X1_UNORM>::StoreGeneric; table[TTileMode][B5G5R5X1_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, B5G5R5X1_UNORM_SRGB>::StoreGeneric; table[TTileMode][R8G8_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_SSCALED>::Store; table[TTileMode][R8G8_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R8G8_USCALED>::Store; table[TTileMode][R16_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_SSCALED>::Store; table[TTileMode][R16_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, R16_USCALED>::Store; table[TTileMode][A1B5G5R5_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, A1B5G5R5_UNORM>::StoreGeneric; table[TTileMode][A4B4G4R4_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32G32B32A32_FLOAT, A4B4G4R4_UNORM>::StoreGeneric; table[TTileMode][R8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_UNORM>::Store; table[TTileMode][R8_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_SNORM>::Store; table[TTileMode][R8_SINT] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_SINT>::Store; table[TTileMode][R8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_UINT>::Store; table[TTileMode][A8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, A8_UNORM>::Store; table[TTileMode][R8_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_SSCALED>::Store; table[TTileMode][R8_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 8>, R32G32B32A32_FLOAT, R8_USCALED>::Store; table[TTileMode][R8G8B8_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_UNORM>::Store; table[TTileMode][R8G8B8_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_SNORM>::Store; table[TTileMode][R8G8B8_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_SSCALED>::Store; table[TTileMode][R8G8B8_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_USCALED>::Store; table[TTileMode][R16G16B16_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_FLOAT>::Store; table[TTileMode][R16G16B16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_UNORM>::Store; table[TTileMode][R16G16B16_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_SNORM>::Store; table[TTileMode][R16G16B16_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_SSCALED>::Store; table[TTileMode][R16G16B16_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_USCALED>::Store; table[TTileMode][R8G8B8_UNORM_SRGB] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_UNORM_SRGB>::Store; table[TTileMode][R16G16B16_UINT] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_UINT>::Store; table[TTileMode][R16G16B16_SINT] = StoreMacroTile<TilingTraits<TTileMode, 48>, R32G32B32A32_FLOAT, R16G16B16_SINT>::Store; table[TTileMode][R10G10B10A2_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_SNORM>::StoreGeneric; table[TTileMode][R10G10B10A2_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_USCALED>::StoreGeneric; table[TTileMode][R10G10B10A2_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_SSCALED>::StoreGeneric; table[TTileMode][R10G10B10A2_SINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, R10G10B10A2_SINT>::StoreGeneric; table[TTileMode][B10G10R10A2_SNORM] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_SNORM>::StoreGeneric; table[TTileMode][B10G10R10A2_USCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_USCALED>::StoreGeneric; table[TTileMode][B10G10R10A2_SSCALED] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_SSCALED>::StoreGeneric; table[TTileMode][B10G10R10A2_UINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_UINT>::StoreGeneric; table[TTileMode][B10G10R10A2_SINT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32G32B32A32_FLOAT, B10G10R10A2_SINT>::StoreGeneric; table[TTileMode][R8G8B8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_UINT>::Store; table[TTileMode][R8G8B8_SINT] = StoreMacroTile<TilingTraits<TTileMode, 24>, R32G32B32A32_FLOAT, R8G8B8_SINT>::Store; } ////////////////////////////////////////////////////////////////////////// /// INIT_STORE_TILES_TABLE - Helper macro for setting up the tables. template <SWR_TILE_MODE TTileMode, size_t NumTileModes, size_t ArraySizeT> void InitStoreTilesTableDepth( PFN_STORE_TILES(&table)[NumTileModes][ArraySizeT]) { table[TTileMode][R32_FLOAT] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32_FLOAT, R32_FLOAT>::Store; table[TTileMode][R32_FLOAT_X8X24_TYPELESS] = StoreMacroTile<TilingTraits<TTileMode, 64>, R32_FLOAT, R32_FLOAT_X8X24_TYPELESS>::Store; table[TTileMode][R24_UNORM_X8_TYPELESS] = StoreMacroTile<TilingTraits<TTileMode, 32>, R32_FLOAT, R24_UNORM_X8_TYPELESS>::Store; table[TTileMode][R16_UNORM] = StoreMacroTile<TilingTraits<TTileMode, 16>, R32_FLOAT, R16_UNORM>::Store; } template <SWR_TILE_MODE TTileMode, size_t NumTileModes, size_t ArraySizeT> void InitStoreTilesTableStencil( PFN_STORE_TILES(&table)[NumTileModes][ArraySizeT]) { table[TTileMode][R8_UINT] = StoreMacroTile<TilingTraits<TTileMode, 8>, R8_UINT, R8_UINT>::Store; } ////////////////////////////////////////////////////////////////////////// /// @brief Deswizzles and stores a full hottile to a render surface /// @param hPrivateContext - Handle to private DC /// @param srcFormat - Format for hot tile. /// @param renderTargetIndex - Index to destination render target /// @param x, y - Coordinates to raster tile. /// @param pSrcHotTile - Pointer to Hot Tile void SwrStoreHotTileToSurface( HANDLE hWorkerPrivateData, SWR_SURFACE_STATE *pDstSurface, BucketManager* pBucketMgr, SWR_FORMAT srcFormat, SWR_RENDERTARGET_ATTACHMENT renderTargetIndex, uint32_t x, uint32_t y, uint32_t renderTargetArrayIndex, uint8_t *pSrcHotTile);
51.374269
195
0.619484
[ "render", "vector", "3d" ]
1b796e6d23272f2e592fce597792ea00420ed310
599
h
C
Project/SpriterPlusPlus/SpriterEngine/loading/loader.h
Conny14156/asian-viking
3b8a0acfb4d98ee80be16c7ef646a157f9045650
[ "Zlib", "BSD-3-Clause" ]
1
2015-03-13T22:57:35.000Z
2015-03-13T22:57:35.000Z
Project/SpriterPlusPlus/SpriterEngine/loading/loader.h
Conny14156/asian-viking
3b8a0acfb4d98ee80be16c7ef646a157f9045650
[ "Zlib", "BSD-3-Clause" ]
null
null
null
Project/SpriterPlusPlus/SpriterEngine/loading/loader.h
Conny14156/asian-viking
3b8a0acfb4d98ee80be16c7ef646a157f9045650
[ "Zlib", "BSD-3-Clause" ]
2
2018-10-11T17:49:26.000Z
2018-10-24T06:06:49.000Z
#ifndef LOADER_H #define LOADER_H #include <Core/String.hpp> #include "spriterdocumentloader.h" namespace SpriterEngine { class SpriterFileDocumentWrapper; class SpriterModel; class FileFactory; class Loader { public: Loader(FileFactory *newFileFactory); ~Loader(); void loadFile(SpriterModel *model, const Core::String &fileName); private: enum SpriterFileType { SPRITERFILETYPE_NONE, SPRITERFILETYPE_SCML, SPRITERFILETYPE_SCON }; FileFactory *fileFactory; SpriterFileType extractFileTypeFromFileName(const Core::String &fileName); }; } #endif // LOADER_H
16.189189
76
0.759599
[ "model" ]
1b8502f1d177732844cbd82bb2189d22c87f4ab9
4,074
h
C
lib/include/otslib/action.h
electronshepherds/otslib
ceb704134e8389e8b3f5b39660fef8854031ec20
[ "MIT" ]
null
null
null
lib/include/otslib/action.h
electronshepherds/otslib
ceb704134e8389e8b3f5b39660fef8854031ec20
[ "MIT" ]
4
2022-01-27T02:17:55.000Z
2022-02-25T05:13:01.000Z
lib/include/otslib/action.h
electronshepherds/otslib
ceb704134e8389e8b3f5b39660fef8854031ec20
[ "MIT" ]
null
null
null
/** * @file action.h * @author Abe Kohandel (abe@electronshepherds.com) * @brief The module provides the functionality to perform object actions. * * @copyright Copyright (c) 2022 */ #ifndef __OTSLIB_ACTION_H__ #define __OTSLIB_ACTION_H__ /** * @brief Action * @defgroup otslib_action Object Transfer Service Action * @ingroup otslib * @{ */ #include <gattlib.h> #include <unistd.h> #ifdef __cplusplus extern "C" { #endif /** @brief Truncate Write Mode */ #define OTSLIB_WRITE_MODE_TRUNCATE (1UL << 1) /** * @brief Create Object * * Create an object with allocated size of @p size and type of @p type. * The type is a generic bluetooth UUID type that supports 16-bit, 32-bit, * and 128-bit UUIDs. However, only 16-bit and 128-bit UUIDs are valid for * an OTS object type. * * @note Further to the above limitation, currently only 16-byte UUID * types are supported. * * @param adapter otslib adapter * @param size object size to create * @param type object type to create * @retval -EINVAL if @p adapter or @p type are NULL * if the server does not support the objet type * @retval -ENOTSUP if type is not a 16-bit UUID * if the server does not support object creation * @retval -ENOSPC if the server did not have sufficient resources * @retval 0 when successful * @return other negative values for other errors */ int otslib_create(void *adapter, size_t size, uuid_t *type); /** * @brief Delete Object * * Delete the currently selected object. * * @param adapter otslib adapter * @retval -EINVAL if @p adapter is NULL * @retval -ENOTSUP if the server does not support delete * @retval -ENOENT if no object is currently selected * @retval -EPERM if the current object does not permit deletion * @retval -EBUSY if the object is currently busy * @retval 0 when successful * @return other negative values for other errors */ int otslib_delete(void *adapter); /** * @brief Read Object * * Read @p length at @p offset from the currently selected object. * * @param adapter otslib adapter * @param offset byte offset to read from * @param length number of bytes to read * @param[out] buffer pointer to the buffer containing the read data. * it is the responsibility of the caller to free * this buffer using free(). * @retval -EINVAL if @p adapter or @p buffer are NULL * @retval -ENOMEM if buffer memory could not be allocated * @retval -ENOTSUP if the server does not support read * @retval -ENOENT if no object is currently selected * @retval -EPERM if the current object does not permit read * @retval -EBADR if the offset and length result in an invalid read operation * @retval -EBUSY if the object is currently busy * @retval -EIO if the read was unexpectedly terminated * @return number of bytes read on success * @return other negative values for other errors */ int otslib_read(void *adapter, off_t offset, size_t length, void **buffer); /** * @brief Write Object * * Write @p length at @p offset to the currently selected object. * * @param adapter otslib_adapter * @param offset byte offset to write to * @param length number of bytes to write * @param mode write mode bitmask constructed from @p OTSLIB_WRITE_MODE_* defines * @param[out] buffer pointer to the buffer containing the write data. * @retval -EINVAL if @p adapter or @p buffer are NULL * @retval -ENOTSUP if the server does not support write * @retval -ENOENT if no object is currently selected * @retval -EPERM if the current object does not permit write * if the patching or truncation was attempted but they are not permitted * @retval -EBADR if the offset and length result in an invalid write operation * @retval -EBUSY if the object is currently busy * @return number of bytes read on success * @return other negative values for other errors */ int otslib_write(void *adapter, off_t offset, size_t length, unsigned char mode, void *buffer); #ifdef __cplusplus } #endif /** * @} */ #endif /* __OTSLIB_ACTION_H__ */
32.854839
95
0.715513
[ "object" ]
1b898a03aedbb6efcd3e06a5861d8218b1da6cdc
829
h
C
Kernel/Storage/Partition/PartitionTable.h
EGOTree/pranaOS
3f0a6900e7ca3430c30e84fb51fb0c8fe04b78a5
[ "BSD-2-Clause" ]
11
2021-03-31T08:25:57.000Z
2021-06-09T10:48:07.000Z
Kernel/Storage/Partition/PartitionTable.h
pro-hacker64/prana-os
b16506e674c0fd48beef802e890a6ad57740cfff
[ "BSD-2-Clause" ]
14
2021-06-11T06:07:08.000Z
2021-06-29T05:51:06.000Z
Kernel/Storage/Partition/PartitionTable.h
pro-hacker64/prana-os
b16506e674c0fd48beef802e890a6ad57740cfff
[ "BSD-2-Clause" ]
15
2021-04-13T12:08:24.000Z
2021-06-10T12:02:04.000Z
#pragma once // includes #include <AK/RefPtr.h> #include <AK/Vector.h> #include <Kernel/Storage/Partition/DiskPartition.h> #include <Kernel/Storage/Partition/DiskPartitionMetadata.h> #include <Kernel/Storage/StorageDevice.h> namespace Kernel { class PartitionTable { public: enum class Error { Invalid, MBRProtective, ConatinsEBR, }; public: Optional<DiskPartitionMetadata> partition(unsigned index); size_t partitions_count() const { return m_partitions.size(); } virtual ~PartitionTable() = default; virtual bool is_valid() const = 0; Vector<DiskPartitionMetadata> partitions() const { return m_partitions; } protected: explicit PartitionTable(const StorageDevice&); NonnullRefPtr<StorageDevice> m_device; Vector<DiskPartitionMetadata> m_partitions; }; }
23.027778
77
0.728589
[ "vector" ]
1b8b0227e9ce7eaa67dc9a06d815ea304cc15601
1,907
h
C
src/sequencer_src/interface/views/parameters/EventParameterView.h
pigatron-industries/xen_sequence
0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1
[ "Unlicense" ]
null
null
null
src/sequencer_src/interface/views/parameters/EventParameterView.h
pigatron-industries/xen_sequence
0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1
[ "Unlicense" ]
null
null
null
src/sequencer_src/interface/views/parameters/EventParameterView.h
pigatron-industries/xen_sequence
0deb8d066b1476a7bd72d83efe3534dd0ab9fbf1
[ "Unlicense" ]
null
null
null
#ifndef EventParameterView_h #define EventParameterView_h #include <inttypes.h> #include "AbstractParameterView.h" #include "interface/components/field/EnumParameterField.h" #include "interface/components/field/PitchParameterField.h" #include "interface/components/field/IntegerParameterField.h" #include "interface/components/field/BooleanParameterField.h" #include "interface/components/field/RangeParameterField.h" #include "interface/components/field/ParameterFieldListener.h" #include "interface/components/ListComponent.h" #include "interface/components/LineComponent.h" #include "sequencer/midi/MidiEventHandler.h" #include "model/SequenceTickEvents.h" class EventParameterView : public AbstractParameterView, ParameterFieldListener { public: EventParameterView(); void addFields(ListComponent* fields); void setEvent(SequenceTickEvents* tickEvents, SequenceEvent* event); SequenceEvent* getEvent() { return event; } void handleMidiEvent(MidiMessage message); void updateDataFromField(ParameterField* field); bool containsField(ParameterField* field); virtual void onSelectModeChange(ParameterField* field); virtual void onValueChange(ParameterField* field); private: static const char* EVENT_TYPE_NAMES[]; LineComponent lineComponent = LineComponent(Colour::YELLOW, 1); EnumParameterField eventTypeField = EnumParameterField("TYPE", EVENT_TYPE_NAMES, 2); RangeParameterField noteOnOffField = RangeParameterField("ON/OFF", 0, 24); PitchParameterField eventPitchField = PitchParameterField("PITCH"); IntegerParameterField eventVelocityField = IntegerParameterField("VELOCITY", 0, 127); IntegerParameterField eventControlField = IntegerParameterField("CONTROL", 0, 31); IntegerParameterField eventValueField = IntegerParameterField("VALUE", 0, 127); SequenceTickEvents* tickEvents; SequenceEvent* event; }; #endif
37.392157
89
0.796015
[ "model" ]
1b8efd5afbef6aa0d34646e1c8af913420b6baa3
2,920
h
C
src/main.h
ParthGoyal1508/3D-OpenGL_Game
82daaa25dab0fcdf3b594c587934a285c9ad5826
[ "MIT" ]
null
null
null
src/main.h
ParthGoyal1508/3D-OpenGL_Game
82daaa25dab0fcdf3b594c587934a285c9ad5826
[ "MIT" ]
null
null
null
src/main.h
ParthGoyal1508/3D-OpenGL_Game
82daaa25dab0fcdf3b594c587934a285c9ad5826
[ "MIT" ]
null
null
null
#ifndef MAIN_H #define MAIN_H #include <iostream> #include <stdio.h> #include <cmath> #include <fstream> #include <vector> #include <string.h> #include <signal.h> #include <unistd.h> #include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> struct color_t { int r; int g; int b; }; // nonedit.cpp GLFWwindow *initGLFW(int width, int height); GLuint LoadShaders(const char *vertex_file_path, const char *fragment_file_path); struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const GLfloat *color_buffer_data, GLenum fill_mode = GL_FILL); struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode = GL_FILL); struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const color_t color, GLenum fill_mode = GL_FILL); void draw3DObject(struct VAO *vao); // input.cpp void keyboard(GLFWwindow *window, int key, int scancode, int action, int mods); void keyboardChar(GLFWwindow *window, unsigned int key); void mouseButton(GLFWwindow *window, int button, int action, int mods); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); // other_handlers.cpp void error_callback(int error, const char *description); void quit(GLFWwindow *window); void reshapeWindow(GLFWwindow *window, int width, int height); // Types struct VAO { GLuint VertexArrayID; GLuint VertexBuffer; GLuint ColorBuffer; GLenum PrimitiveMode; GLenum FillMode; int NumVertices; }; typedef struct VAO VAO; struct GLMatrices { glm::mat4 projection; glm::mat4 model; glm::mat4 view; GLuint MatrixID; }; extern GLMatrices Matrices; // ---- Logic ---- enum direction_t { DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT }; struct bounding_box_t { float x; float y; float z; float width; float height; float length; }; bool detect_collision(bounding_box_t a, bounding_box_t b); void heli_camera(float x, float y); void zoom_camera(int type); extern float screen_zoom, screen_center_x, screen_center_y; void reset_screen(); // ---- Colors ---- extern const color_t COLOR_RED; extern const color_t COLOR_BLUE; extern const color_t COLOR_GREEN; extern const color_t COLOR_BLACK; extern const color_t COLOR_BACKGROUND; extern const color_t COLOR_FIRE; extern const color_t COLOR_SILVER; extern const color_t COLOR_DASHBOARD; extern const color_t COLOR_ENEMY; extern const color_t COLOR_DARKBLACK; extern bool sound; extern pid_t pid; // Audio void audio_init(); void audio_play(); void audio_close(); #endif
25.840708
190
0.758219
[ "vector", "model", "transform" ]
1b8f8d5867194687d4bb5c51c449bd0eba4a2721
32,560
h
C
pcommon/pcomn_hash.h
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
6
2015-02-18T17:10:15.000Z
2019-01-01T13:48:05.000Z
pcommon/pcomn_hash.h
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
null
null
null
pcommon/pcomn_hash.h
mmalyutin/libpcomn
22e315e1de5f47254e1080a37ec87759e2fbed55
[ "Zlib" ]
3
2018-06-24T15:59:12.000Z
2021-02-15T09:21:39.000Z
/*-*- mode: c++; tab-width: 3; indent-tabs-mode: nil; c-file-style: "ellemtel"; c-file-offsets:((innamespace . 0)(inclass . ++)) -*-*/ #ifndef __PCOMN_HASH_H #define __PCOMN_HASH_H /******************************************************************************* FILE : pcomn_hash.h COPYRIGHT : Yakov Markovitch, 2000-2020. All rights reserved. Leonid Yuriev <leo@yuriev.ru>, 2010-2019. All rights reserved. See LICENSE for information on usage/redistribution. DESCRIPTION : Hash functions & functors. MD5 hash. CRC32 function(s) CREATION DATE: 10 Jan 2000 *******************************************************************************/ /** @file Hash functions and functors, MD5 hash, CRC32 calculations. *******************************************************************************/ #include <pcommon.h> #include <pcomn_assert.h> #include "t1ha/t1ha.h" #include <wchar.h> #include <stddef.h> #include <string.h> #include <stdio.h> #include <ctype.h> #ifdef __cplusplus extern "C" { #endif _PCOMNEXP uint32_t calc_crc32(uint32_t crc, const void *buf, size_t len) ; #ifdef __cplusplus } #endif #ifdef __cplusplus #include "pcomn_binary128.h" #include "pcomn_meta.h" #include <string> #include <iosfwd> #include <functional> #include <utility> #include <tuple> #include <initializer_list> namespace pcomn { /******************************************************************************* Overloaded generic hash algorithms *******************************************************************************/ inline uint32_t calc_crc32(uint32_t prev_crc, const char *str) { return ::calc_crc32(prev_crc, (const uint8_t *)str, strlen(str)) ; } inline uint32_t calc_crc32(const char *str) { return calc_crc32(0, str) ; } inline uint32_t calc_crc32(uint32_t prev_crc, const void *buf, size_t sz) { return ::calc_crc32(prev_crc, buf, sz) ; } /*******************************************************************************/ /** Fowler/Noll/Vo (FNV) hash. *******************************************************************************/ inline uint32_t hashFNV32(const void *data, size_t size, uint32_t init) { uint32_t result = init ; for (const uint8_t *p = static_cast<const uint8_t *>(data), *end = p + size ; p != end ; ++p) { result ^= uint32_t(*p) ; result *= uint32_t(16777619UL) ; } return result ; } inline uint32_t hashFNV32(const void *data, size_t size) { return hashFNV32(data, size, 2166136261UL) ; } inline uint64_t hashFNV64(const void *data, size_t size, uint64_t init) { uint64_t result = init ; for (const uint8_t *p = static_cast<const uint8_t *>(data), *end = p + size ; p != end ; ++p) { result ^= uint64_t(*p) ; result *= uint64_t(1099511628211ULL) ; } return result ; } inline uint64_t hashFNV64(const void *data, size_t size) { return hashFNV64(data, size, 14695981039346656037ULL) ; } inline uint32_t hashFNV(const void *data, size_t size, std::integral_constant<size_t, 4>) { return hashFNV32(data, size) ; } inline uint32_t hashFNV(const void *data, size_t size, uint32_t init, std::integral_constant<size_t, 4>) { return hashFNV32(data, size, init) ; } inline uint64_t hashFNV(const void *data, size_t size, std::integral_constant<size_t, 8>) { return hashFNV64(data, size) ; } inline uint64_t hashFNV(const void *data, size_t size, uint64_t init, std::integral_constant<size_t, 8>) { return hashFNV64(data, size, init) ; } inline size_t hashFNV(const void *data, size_t size) { return hashFNV(data, size, std::integral_constant<size_t, sizeof(size_t)>()) ; } inline size_t hashFNV(const void *data, size_t size, size_t init) { return hashFNV(data, size, init, std::integral_constant<size_t, sizeof(size_t)>()) ; } /***************************************************************************//** Thomas Wang's hash function for hashing a 64-bit integer to a 64-bit integer *******************************************************************************/ constexpr inline uint64_t wang_hash64to64(uint64_t x) { x = ~x + (x << 21) ; // x = (x << 21) - x - 1 x ^= (x >> 24) ; x += (x << 3) + (x << 8) ; // x * 265 x ^= (x >> 14) ; x += (x << 2) + (x << 4) ; // x * 21 x ^= (x >> 28) ; x += (x << 31) ; return x ; } /***************************************************************************//** Thomas Wang's hash function for hashing a 64-bit integer to a 32-bit integer *******************************************************************************/ constexpr inline uint32_t wang_hash64to32(uint64_t x) { x = ~x + (x << 18) ; // x = (x << 18) - x - 1 x ^= (x >> 31) ; x += (x << 2) + (x << 4) ; // x * 21 x ^= (x >> 11) ; x += (x << 6) ; x ^= (x >> 22) ; return (uint32_t)x ; } /***************************************************************************//** Thomas Mueller's hash function for hashing a 32-bit integer to a 32-bit hash. This is excellent: super-low-bias, ideal avalanche. It is _faster_ than Intel's hardware crc32 instruction for calculating single hash and several times faster when processing an array of values, due to its excellent vectorizability. *******************************************************************************/ constexpr inline uint32_t mueller_hash32(uint32_t x) { x = ((x >> 16) ^ x) * 0x45d9f3bU ; x = ((x >> 16) ^ x) * 0x45d9f3bU ; x = (x >> 16) ^ x ; return x ; } /***************************************************************************//** Hash function for hashing a 64-bit integer to a 64-bit hash by degski, unbeliavably fast. High-quality: super-low-bias, ideal avalanche. Performance of this function is best described if we treat this function as a "CPU pseudo-instruction". Then, on Haswell and GCC or Clang: - its latency is ~3 cycles - its throghput is ~1 cycle per hash (when we e.g. perform a bulk evaluation of hashes of array items in a loop) - due do its excellent vectorizability. *******************************************************************************/ constexpr inline uint64_t degski_hash64(uint64_t x) { x ^= x >> 32 ; x *= 0xd6e8feb86659fd93ull ; x ^= x >> 32 ; x *= 0xd6e8feb86659fd93ull ; x ^= x >> 32 ; return x ; } constexpr inline uint32_t hash_32(uint32_t x, std::integral_constant<size_t, 4>) { return mueller_hash32(x) ; } constexpr inline uint64_t hash_32(uint32_t x, std::integral_constant<size_t, 8>) { return degski_hash64(x) ; } /***************************************************************************//** Hashing 32-bit integer to size_t *******************************************************************************/ constexpr inline size_t hash_32(uint32_t x) { return hash_32(x, std::integral_constant<size_t, sizeof(size_t)>()) ; } /***************************************************************************//** Hashing 64-bit integer to size_t *******************************************************************************/ constexpr inline size_t hash_64(uint64_t x) { return degski_hash64(x) ; } /***************************************************************************//** Hashing byte sequence to size_t. @note Always returns 0 for zero length. *******************************************************************************/ inline size_t hash_bytes(const void *data, size_t length) { return length ? t1ha0(data, length, 0) : 0 ; } /******************************************************************************* Hasher functors ****************************************************************************//** Functor returning its parameter unchanged (but converted to size_t). *******************************************************************************/ struct hash_identity { template<typename T> size_t operator() (const T &val) const { return static_cast<size_t>(val) ; } } ; /******************************************************************************* Forward declarations of hash functor templates *******************************************************************************/ template<typename = void> struct hash_fn ; // "Unwrap" type being hashed from const, volatile, and reference wrappers. template<typename T> struct hash_fn<const T> : hash_fn<T> {} ; template<typename T> struct hash_fn<volatile T> : hash_fn<T> {} ; template<typename T> struct hash_fn<T &> : hash_fn<T> {} ; template<typename T> struct hash_fn<T &&> : hash_fn<T> {} ; template<typename T> struct hash_fn<std::reference_wrapper<T>> : hash_fn<T> {} ; /***************************************************************************//** Universal hashing functor. *******************************************************************************/ template<> struct hash_fn<void> { template<typename T> auto operator()(T &&v) const -> decltype(std::declval<hash_fn<T>>()(std::forward<T>(v))) { hash_fn<T> h ; return h(std::forward<T>(v)) ; } } ; /***************************************************************************//** Universal hashing function. *******************************************************************************/ template<typename T> inline decltype(hash_fn<std::decay_t<T>>()(std::declval<T>())) valhash(T &&data) { return hash_fn<std::decay_t<T>>()(std::forward<T>(data)) ; } /***************************************************************************//** Hash combinator: "reduces" a sequence of hash value to single hash value. Useful for hashing tuples, structures and sequences, i.e. complex objects. Uses a part of 64-bit MurmurHash2 to combine hash values. *******************************************************************************/ struct hash_combinator { constexpr hash_combinator() = default ; explicit hash_combinator(uint64_t initial_hash) { append(initial_hash) ; } template<typename InputIterator> hash_combinator(const InputIterator &b, const InputIterator &e) { append_data(b, e) ; } constexpr uint64_t value() const { return _combined ; } constexpr operator uint64_t() const { return value() ; } hash_combinator &append(uint64_t hash_value) { constexpr const uint64_t mask = 0xc6a4a7935bd1e995ULL ; constexpr const int r = 47 ; hash_value *= mask ; hash_value ^= hash_value >> r ; hash_value *= mask ; _combined ^= hash_value ; _combined *= mask ; return *this ; } template<typename T> hash_combinator &append_data(T &&data) { return append(valhash(std::forward<T>(data))) ; } template<typename InputIterator> hash_combinator &append_data(InputIterator b, InputIterator e) { for (; b != e ; *this += *b, ++b) ; return *this ; } template<typename T> hash_combinator &operator+=(T &&data) { return append_data(std::forward<T>(data)) ; } template<typename...T> hash_combinator &append_as_tuple(const std::tuple<T...> &data) { append_item<sizeof...(T)>::append(*this, data) ; return *this ; } private: uint64_t _combined = 0 ; template<unsigned tuplesz, typename=void> struct append_item { template<typename T> static void append(hash_combinator &accumulator, T &&tuple_data) { accumulator.append_data(std::get<std::tuple_size<valtype_t<T>>::value - tuplesz>(std::forward<T>(tuple_data))) ; append_item<tuplesz-1>::append(accumulator, std::forward<T>(tuple_data)) ; } } ; template<typename D> struct append_item<0, D> { template<typename...Args> static void append(Args &&...) {} } ; } ; /***************************************************************************//** Backward compatibility definition. *******************************************************************************/ typedef hash_combinator Hash ; /***************************************************************************//** Function that hashes its arguments and returns combined hash value. *******************************************************************************/ inline size_t tuplehash() { return 0 ; } template<typename A1> inline size_t tuplehash(A1 &&a1) { return hash_combinator(valhash(std::forward<A1>(a1))) ; } template<typename A1, typename A2> inline size_t tuplehash(A1 &&a1, A2 &&a2) { return hash_combinator(valhash(std::forward<A1>(a1))).append_data(std::forward<A2>(a2)) ; } template<typename A1, typename A2, typename A3, typename... Args> inline size_t tuplehash(A1 &&a1, A2 &&a2, A3 &&a3, Args &&...args) { hash_combinator result (valhash(std::forward<A1>(a1))) ; result.append_data(std::forward<A2>(a2)).append_data(std::forward<A3>(a3)) ; const size_t h[] = { valhash(std::forward<Args>(args))...} ; for (size_t v: h) result.append(v) ; return result ; } /***************************************************************************//** Base class of 128-bit hashes: allows for the "unspecified hash" return/storage type. *******************************************************************************/ struct digest128_t : binary128_t { using binary128_t::binary128_t ; constexpr digest128_t() = default ; explicit constexpr digest128_t(const binary128_t &src) : binary128_t(src) {} constexpr size_t hash() const { return _idata[0] ; } } ; /***************************************************************************//** MD5 hash *******************************************************************************/ struct md5hash_t : digest128_t { constexpr md5hash_t() = default ; explicit constexpr md5hash_t(const binary128_t &src) : digest128_t(src) {} explicit md5hash_t(const char *hexstr) : digest128_t(hexstr) {} } ; /***************************************************************************//** SHA1 hash *******************************************************************************/ struct sha1hash_t { constexpr sha1hash_t() : _idata() {} /// Create a hash from a hex string representation. /// @note @a hexstr need not be null-terminated, the constructor will scan at most /// 40 characters, or until '\0' encountered, whatever comes first. explicit sha1hash_t(const char *hexstr) { if (!hextob(_idata, sizeof _idata, hexstr)) _idata[4] = _idata[3] = _idata[2] = _idata[1] = _idata[0] = 0 ; } /// Check helper. explicit constexpr operator bool() const { return _idata[0] || _idata[1] || _idata[2] || _idata[3] || _idata[4] ; } unsigned char *data() { return reinterpret_cast<unsigned char *>(_idata) ; } const unsigned char *data() const { return reinterpret_cast<const unsigned char *>(_idata) ; } static constexpr size_t size() { return sizeof _idata ; } constexpr size_t hash() const { return ((uint64_t)_idata[3] << 32) | (uint64_t)_idata[4] ; } _PCOMNEXP std::string to_string() const ; /*********************************************************************//** Equality (==), ordering (<) *************************************************************************/ friend bool operator==(const sha1hash_t &l, const sha1hash_t &r) { return !memcmp(l._idata, r._idata, sizeof l._idata) ; } friend bool operator<(const sha1hash_t &l, const sha1hash_t &r) { return memcmp(l._idata, r._idata, sizeof l._idata) < 0 ; } private: uint32_t _idata[5] ; } ; PCOMN_STATIC_CHECK(sizeof(sha1hash_t) == 20) ; // Define !=, >, <=, >= for sha1hash_t PCOMN_DEFINE_RELOP_FUNCTIONS(, sha1hash_t) ; /***************************************************************************//** t1ha2 128-bit hash *******************************************************************************/ struct t1ha2hash_t : digest128_t { constexpr t1ha2hash_t() = default ; explicit constexpr t1ha2hash_t(const binary128_t &src) : digest128_t(src) {} explicit t1ha2hash_t(const char *hexstr) : digest128_t(hexstr) {} } ; /***************************************************************************//** SHA256 hash *******************************************************************************/ struct sha256hash_t : binary256_t { using binary256_t::binary256_t ; constexpr sha256hash_t() = default ; explicit constexpr sha256hash_t(const binary256_t &src) : binary256_t(src) {} sha256hash_t hton() const { return sha256hash_t(*this).hton_inplace() ; } sha256hash_t& hton_inplace() { binary256_t::flip_endianness() ; return *this ; } } ; PCOMN_STATIC_CHECK(sizeof(sha256hash_t) == 32) ; /***************************************************************************//** Backward compatibility typedefs *******************************************************************************/ /**{@*/ typedef md5hash_t md5hash_pod_t ; typedef sha1hash_t sha1hash_pod_t ; /**}@*/ /******************************************************************************* *******************************************************************************/ /// @cond namespace detail { template<size_t n> struct crypthash_state { size_t _size ; uint32_t _statebuf[n] ; bool is_init() const { return *_statebuf || _size ; } } ; } /// @endcond /******************************************************************************/ /** MD5 hash accumulator: calculates MD5 incrementally. *******************************************************************************/ class _PCOMNEXP MD5Hash { public: MD5Hash() { memset(&_state, 0, sizeof _state) ; } md5hash_t value() const ; operator md5hash_t() const { return value() ; } /// Data size appended so far size_t size() const { return _state._size ; } MD5Hash &append_data(const void *buf, size_t size) ; MD5Hash &append_file(const char *filename) ; MD5Hash &append_file(FILE *file) ; private: typedef detail::crypthash_state<24> state ; state _state ; } ; /// Create zero MD5. inline md5hash_t md5hash() { return md5hash_t() ; } /// Compute MD5 for a buffer. /// /// @note There are convenient overloading of this function for any object that provides /// pcomn::buf::cdata() and pcomn::buf::size() and strslice. /// _PCOMNEXP md5hash_t md5hash(const void *buf, size_t size) ; /// Compute MD5 for a file specified by a filename. /// @param filename The name of file to md5. /// @param raise_error Whether to throw pcomn::system_error exception on I/O error /// (e.g., @a filename does not exist), if DONT_RAISE_ERROR then return zero md5. /// @throw std::invalid_argument if @a filename is NULL. _PCOMNEXP md5hash_t md5hash_file(const char *filename, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload _PCOMNEXP md5hash_t md5hash_file(int fd, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload inline md5hash_t md5hash_file(const char *filename, RaiseError raise_error = DONT_RAISE_ERROR) { return md5hash_file(filename, NULL, raise_error) ; } /// @overload inline md5hash_t md5hash_file(int fd, RaiseError raise_error = DONT_RAISE_ERROR) { return md5hash_file(fd, NULL, raise_error) ; } /// Compute MD5 for a file opened for reading. /// @note Doesn't rewind file before starting calculation. inline md5hash_t md5hash_file(FILE *file, size_t *size = NULL) { MD5Hash crypthasher ; crypthasher.append_file(file) ; if (size) *size = crypthasher.size() ; return crypthasher.value() ; } /******************************************************************************/ /** SHA1 hash accumulator: calculates SHA1 incrementally. *******************************************************************************/ class _PCOMNEXP SHA1Hash { public: SHA1Hash() { memset(&_state, 0, sizeof _state) ; } sha1hash_t value() const ; operator sha1hash_t() const { return value() ; } /// Data size appended so far size_t size() const { return _state._size ; } SHA1Hash &append_data(const void *buf, size_t size) ; SHA1Hash &append_file(const char *filename) ; SHA1Hash &append_file(FILE *file) ; private: typedef detail::crypthash_state<24> state ; state _state ; } ; /// Create all-zero SHA1. inline sha1hash_t sha1hash() { return sha1hash_t() ; } /// Compute SHA1 for a buffer. /// /// @note There are convenient overloading of this function for any object that provides /// pcomn::buf::cdata() and pcomn::buf::size(). /// _PCOMNEXP sha1hash_t sha1hash(const void *buf, size_t size) ; /// Compute SHA1 for a file specified by a filename. /// @param filename The name of file to md5. /// @param raise_error Whether to throw pcomn::system_error exception on I/O error /// (e.g., @a filename does not exist), if DONT_RAISE_ERROR then return zero md5. /// @throw std::invalid_argument if @a filename is NULL. _PCOMNEXP sha1hash_t sha1hash_file(const char *filename, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload _PCOMNEXP sha1hash_t sha1hash_file(int fd, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload inline sha1hash_t sha1hash_file(const char *filename, RaiseError raise_error = DONT_RAISE_ERROR) { return sha1hash_file(filename, NULL, raise_error) ; } /// @overload inline sha1hash_t sha1hash_file(int fd, RaiseError raise_error = DONT_RAISE_ERROR) { return sha1hash_file(fd, NULL, raise_error) ; } /// Compute SHA1 for a file opened for reading. /// @note Doesn't rewind file before starting calculation. inline sha1hash_t sha1hash_file(FILE *file, size_t *size = NULL) { SHA1Hash crypthasher ; crypthasher.append_file(file) ; if (size) *size = crypthasher.size() ; return crypthasher.value() ; } /******************************************************************************/ /** SHA256 hash accumulator: calculates SHA256 incrementally. *******************************************************************************/ class _PCOMNEXP SHA256Hash { public: SHA256Hash() { memset(&_state, 0, sizeof _state) ; } sha256hash_t value() const ; operator sha256hash_t() const { return value() ; } /// Data size appended so far size_t size() const { return _state._size ; } SHA256Hash &append_data(const void *buf, size_t size) ; SHA256Hash &append_file(const char *filename) ; SHA256Hash &append_file(FILE *file) ; private: typedef detail::crypthash_state<28> state ; state _state ; } ; /// Create zero SHA256. inline sha256hash_t sha256hash() { return sha256hash_t() ; } /// Compute SHA256 for a buffer. /// /// @note There are convenient overloading of this function for any object that provides /// pcomn::buf::cdata() and pcomn::buf::size() and strslice. /// _PCOMNEXP sha256hash_t sha256hash(const void *buf, size_t size) ; /// Compute SHA256 for a file specified by a filename. /// @param filename The name of file to sha256. /// @param raise_error Whether to throw pcomn::system_error exception on I/O error /// (e.g., @a filename does not exist), if DONT_RAISE_ERROR then return zero sha256. /// @throw std::invalid_argument if @a filename is NULL. _PCOMNEXP sha256hash_t sha256hash_file(const char *filename, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload _PCOMNEXP sha256hash_t sha256hash_file(int fd, size_t *size, RaiseError raise_error = DONT_RAISE_ERROR) ; /// @overload inline sha256hash_t sha256hash_file(const char *filename, RaiseError raise_error = DONT_RAISE_ERROR) { return sha256hash_file(filename, NULL, raise_error) ; } /// @overload inline sha256hash_t sha256hash_file(int fd, RaiseError raise_error = DONT_RAISE_ERROR) { return sha256hash_file(fd, NULL, raise_error) ; } /// Compute SHA256 for a file opened for reading. /// @note Doesn't rewind file before starting calculation. inline sha256hash_t sha256hash_file(FILE *file, size_t *size = NULL) { SHA256Hash crypthasher ; crypthasher.append_file(file) ; if (size) *size = crypthasher.size() ; return crypthasher.value() ; } /******************************************************************************* Leo Yuriev's t1ha2 128-bit hashing *******************************************************************************/ /// Create zero t1ha2. inline t1ha2hash_t t1ha2hash() { return {} ; } /// Compute 128-bit t1ha2 hash for a buffer. /// /// @note There are convenient overloading of this function for any object that provides /// pcomn::buf::cdata() and pcomn::buf::size() and for strslice. /// inline t1ha2hash_t t1ha2hash(const void *data, size_t size, uint64_t seed) { uint64_t hi = 0 ; const uint64_t lo = t1ha2_atonce128(&hi, data, size, seed) ; return t1ha2hash_t(binary128_t(hi, lo)) ; } inline t1ha2hash_t t1ha2hash(const void *data, size_t size) { return t1ha2hash(data, size, 0) ; } /***************************************************************************//** Hashing functor using object's `hash()` member function. *******************************************************************************/ template<typename T> struct hash_fn_member : public std::unary_function<T, size_t> { size_t operator()(const T &instance) const { return instance.hash() ; } } ; template<typename T> struct hash_fn_fundamental { PCOMN_STATIC_CHECK(std::is_fundamental<T>::value) ; constexpr size_t operator()(T value) const { return hash_64((uint64_t)value) ; } } ; template<typename T> struct hash_fn_rawdata { size_t operator()(const T &v) const { using namespace std ; return hash_bytes(data(v), (sizeof *data(v)) * size(v)) ; } } ; /***************************************************************************//** Generic hashing functor. *******************************************************************************/ template<typename T> struct hash_fn : std::conditional_t<std::is_default_constructible<std::hash<T>>::value, std::hash<T>, hash_fn_member<T>> {} ; template<> struct hash_fn<bool> { size_t operator()(bool v) const { return v ; } } ; template<> struct hash_fn<double> { size_t operator()(double value) const { union { double _ ; uint64_t value ; } _ {value} ; return hash_64(_.value) ; } } ; template<> struct hash_fn<void *> { size_t operator()(const void *value) const { union { const void * _ ; uint64_t value ; } _ {value} ; return hash_64(_.value) ; } } ; template<typename T> struct hash_fn<const T *> : hash_fn<T *> {} ; template<typename T> struct hash_fn<T *> : hash_fn<void *> {} ; template<> struct hash_fn<float> : hash_fn<double> {} ; template<> struct hash_fn<long double> : hash_fn<double> {} ; #define PCOMN_HASH_INT_FN(type) template<> struct hash_fn<type> : hash_fn_fundamental<type> {} PCOMN_HASH_INT_FN(char) ; PCOMN_HASH_INT_FN(unsigned char) ; PCOMN_HASH_INT_FN(signed char) ; PCOMN_HASH_INT_FN(short) ; PCOMN_HASH_INT_FN(unsigned short) ; PCOMN_HASH_INT_FN(int) ; PCOMN_HASH_INT_FN(unsigned) ; PCOMN_HASH_INT_FN(long) ; PCOMN_HASH_INT_FN(unsigned long) ; PCOMN_HASH_INT_FN(long long) ; PCOMN_HASH_INT_FN(unsigned long long) ; /***************************************************************************//** hash_combinator C string, return 0 for NULL and empty string *******************************************************************************/ template<> struct hash_fn<char *> { size_t operator()(const char *s) const { return hash_bytes(s, s ? strlen(s) : 0) ; } } ; template<> struct hash_fn<const char *> : hash_fn<char *> {} ; template<> struct hash_fn<std::string> : hash_fn_rawdata<std::string> {} ; template<typename T1, typename T2> struct hash_fn<std::pair<T1, T2>> { size_t operator()(const std::pair<T1, T2> &data) const { return tuplehash(data.first, data.second) ; } } ; template<> struct hash_fn<std::tuple<>> { size_t operator()(const std::tuple<> &) const { return 0 ; } } ; template<typename T1, typename...T> struct hash_fn<std::tuple<T1, T...>> { size_t operator()(const std::tuple<T1, T...> &data) const { return hash_combinator().append_as_tuple(data) ; } } ; /***************************************************************************//** Generic "implicit" hash function: delegates to pcomn::hash_fn<T>(). *******************************************************************************/ template<typename T> inline size_t hash_data(const T &data) { static constexpr hash_fn<T> hasher ; return hasher(data) ; } /***************************************************************************//** Hashing functor for any sequence *******************************************************************************/ template<typename S, typename ItemHasher = hash_fn<decltype(*std::begin(std::declval<S>()))>> struct hash_fn_sequence : private ItemHasher { size_t operator()(const S &sequence) const { hash_combinator accumulator ; for (const auto &v: sequence) accumulator.append(ItemHasher::operator()(v)) ; return accumulator ; } } ; template<typename InputIterator> inline size_t hash_sequence(InputIterator b, InputIterator e) { hash_combinator accumulator ; for (; b != e ; ++b) accumulator.append_data(*b) ; return accumulator ; } template<typename InputIterator, typename ItemHasher> inline size_t hash_sequence(InputIterator b, InputIterator e, ItemHasher &&h) { hash_combinator accumulator ; for (; b != e ; ++b) accumulator.append(std::forward<ItemHasher>(h)(*b)) ; return accumulator ; } template<typename Container> inline size_t hash_sequence(Container &&c) { return hash_fn_sequence<Container>()(std::forward<Container>(c)) ; } template<typename T> inline size_t hash_sequence(std::initializer_list<T> s) { return hash_sequence(s.begin(), s.end()) ; } /******************************************************************************* ostream *******************************************************************************/ std::ostream &operator<<(std::ostream &, const sha1hash_t &) ; } // end of namespace pcomn namespace std { /******************************************************************************* std::hash specializations for cryptohashes *******************************************************************************/ template<> struct hash<pcomn::digest128_t>: pcomn::hash_fn_member<pcomn::digest128_t> {} ; template<> struct hash<pcomn::md5hash_t> : hash<pcomn::digest128_t> {} ; template<> struct hash<pcomn::t1ha2hash_t>: hash<pcomn::digest128_t> {} ; template<> struct hash<pcomn::sha1hash_t> : pcomn::hash_fn_member<pcomn::sha1hash_t> {} ; template<> struct hash<pcomn::sha256hash_t> : pcomn::hash_fn_member<pcomn::sha256hash_t> {} ; } #endif /* __cplusplus */ #endif /* __PCOMN_HASH_H */ /******************************************************************************* Hashing buffers For this to work, include pcomn_buffer.h before pcomn_hash.h *******************************************************************************/ #if defined(__cplusplus) && defined(__PCOMN_BUFFER_H) && !defined(__PCOMN_BUFFER_HASH_H) #define __PCOMN_BUFFER_HASH_H namespace pcomn { template<typename B> inline enable_if_buffer_t<B, uint32_t> calc_crc32(uint32_t crc, const B &buffer) { return calc_crc32(crc, buf::cdata(buffer), buf::size(buffer)) ; } template<typename B> inline enable_if_buffer_t<B, uint32_t> calc_crc32(uint32_t crc, size_t ignore_tail, const B &buffer) { const size_t bufsize = buf::size(buffer) ; return ignore_tail >= bufsize ? crc : calc_crc32(crc, buf::cdata(buffer), bufsize - ignore_tail) ; } template<typename B> inline enable_if_buffer_t<B, md5hash_t> md5hash(const B &b) { return md5hash(buf::cdata(b), buf::size(b)) ; } template<typename B> inline enable_if_buffer_t<B, sha1hash_t> sha1hash(const B &b) { return sha1hash(buf::cdata(b), buf::size(b)) ; } template<typename B> inline enable_if_buffer_t<B, t1ha2hash_t> t1ha2hash(const B &b) { return t1ha2hash(buf::cdata(b), buf::size(b)) ; } } // end of namespace pcomn #endif /* __cplusplus && __PCOMN_BUFFER_H */
34.898178
134
0.550369
[ "object" ]
23ddfe405a3f882f104951bd8417ddcba51cf161
1,211
h
C
include/icp.h
softdream/Slam-Project-Of-MyOwn
6d6db8a5761e8530971b203983ea2215620aa5c2
[ "Apache-2.0" ]
21
2021-07-19T08:15:53.000Z
2022-03-31T07:07:55.000Z
include/icp.h
Forrest-Z/Slam-Project-Of-MyOwn
6d6db8a5761e8530971b203983ea2215620aa5c2
[ "Apache-2.0" ]
3
2022-03-02T12:55:37.000Z
2022-03-07T12:12:57.000Z
include/icp.h
softdream/Slam-Project-Of-MyOwn
6d6db8a5761e8530971b203983ea2215620aa5c2
[ "Apache-2.0" ]
4
2021-08-12T15:11:09.000Z
2022-01-08T14:20:36.000Z
#ifndef __ICP_H_ #define __ICP_H_ #include <Eigen/Dense> #include "scanContainer.h" #include <vector> namespace slam{ class ICP{ public: ICP(); ~ICP(); const float solveICP( ScanContainer& A_src, ScanContainer& B_src ); inline const Eigen::Matrix<float, 2, 2> getRotateMatrix() const { return R_final; } inline const Eigen::Vector2f getTransform() const { return T_final; } private: const float iterateOnce( std::vector<Eigen::Vector2f>& B ); const Eigen::Vector2f getClosestPoint( const Eigen::Vector2f &point, const std::vector<Eigen::Vector2f> &sourcePoints ); const int getClosestPointID( const Eigen::Vector2f &point, const std::vector<Eigen::Vector2f> &sourcePoints ); const float cacuLoss( const std::vector<Eigen::Vector2f> &B ); private: Eigen::Vector2f Acenter; Eigen::Vector2f Bcenter; std::vector<Eigen::Vector2f> A; // std::vector<Eigen::Vector2f> B; std::vector<Eigen::Vector2f> a; std::vector<Eigen::Vector2f> b; Eigen::Matrix<float, 2, 2> R; Eigen::Vector2f T; Eigen::Matrix<float, 2, 2> R_final = Eigen::Matrix<float, 2, 2>::Identity(); Eigen::Vector2f T_final = Eigen::Vector2f( 0.0f, 0.0f ) ; int maxIteration = 100; }; } #endif
20.183333
121
0.698596
[ "vector" ]
23ea8686808e93b2d57c6f5fc3ede551c039869c
10,489
h
C
components/freertos/include/freertos/ringbuf.h
sirvaclav/esp-idf
597ce3b800cc4857e1939bbb937610a9e30c6e72
[ "Apache-2.0" ]
null
null
null
components/freertos/include/freertos/ringbuf.h
sirvaclav/esp-idf
597ce3b800cc4857e1939bbb937610a9e30c6e72
[ "Apache-2.0" ]
null
null
null
components/freertos/include/freertos/ringbuf.h
sirvaclav/esp-idf
597ce3b800cc4857e1939bbb937610a9e30c6e72
[ "Apache-2.0" ]
1
2020-03-06T15:48:33.000Z
2020-03-06T15:48:33.000Z
#ifndef FREERTOS_RINGBUF_H #define FREERTOS_RINGBUF_H #ifndef INC_FREERTOS_H #error "include FreeRTOS.h" must appear in source files before "include ringbuf.h" #endif #ifdef __cplusplus extern "C" { #endif /* Header definitions for a FreeRTOS ringbuffer object A ringbuffer instantiated by these functions essentially acts like a FreeRTOS queue, with the difference that it's strictly FIFO and with the main advantage that you can put in randomly-sized items. The capacity, accordingly, isn't measured in the amount of items, but the amount of memory that is used for storing the items. Dependent on the size of the items, more or less of them will fit in the ring buffer. This ringbuffer tries to be efficient with memory: when inserting an item, the item data will be copied to the ringbuffer memory. When retrieving an item, however, a reference to ringbuffer memory will be returned. The returned memory is guaranteed to be 32-bit aligned and contiguous. The application can use this memory, but as long as it does, ringbuffer writes that would write to this bit of memory will block. The requirement for items to be contiguous is slightly problematic when the only way to place the next item would involve a wraparound from the end to the beginning of the ringbuffer. This can be solved (or not) in a few ways: - type = RINGBUF_TYPE_ALLOWSPLIT: The insertion code will split the item in two items; one which fits in the space left at the end of the ringbuffer, one that contains the remaining data which is placed in the beginning. Two xRingbufferReceive calls will be needed to retrieve the data. - type = RINGBUF_TYPE_NOSPLIT: The insertion code will leave the room at the end of the ringbuffer unused and instead will put the entire item at the start of the ringbuffer, as soon as there is enough free space. - type = RINGBUF_TYPE_BYTEBUF: This is your conventional byte-based ringbuffer. It does have no overhead, but it has no item contiguousness either: a read will just give you the entire written buffer space, or the space up to the end of the buffer, and writes can be broken up in any way possible. Note that this type cannot do a 2nd read before returning the memory of the 1st. The maximum size of an item will be affected by this decision. When split items are allowed, it's acceptable to push items of (buffer_size)-16 bytes into the buffer. When it's not allowed, the maximum size is (buffer_size/2)-8 bytes. The bytebuf can fill the entire buffer with data, it has no overhead. */ #include <freertos/queue.h> //An opaque handle for a ringbuff object. typedef void * RingbufHandle_t; //The various types of buffer typedef enum { RINGBUF_TYPE_NOSPLIT = 0, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF } ringbuf_type_t; /** * @brief Create a ring buffer * * @param buf_length : Length of circular buffer, in bytes. Each entry will take up its own length, plus a header * that at the moment is equal to sizeof(size_t). * @param allow_split_items : pdTRUE if it is acceptable that item data is inserted as two * items instead of one. * * @return A RingbufHandle_t handle to the created ringbuffer, or NULL in case of error. */ RingbufHandle_t xRingbufferCreate(size_t buf_length, ringbuf_type_t type); /** * @brief Delete a ring buffer * * @param ringbuf - Ring buffer to delete * * @return void */ void vRingbufferDelete(RingbufHandle_t ringbuf); /** * @brief Get maximum size of an item that can be placed in the ring buffer * * @param ringbuf - Ring buffer to query * * @return Maximum size, in bytes, of an item that can be placed in a ring buffer. */ size_t xRingbufferGetMaxItemSize(RingbufHandle_t ringbuf); /** * @brief Insert an item into the ring buffer * * @param ringbuf - Ring buffer to insert the item into * @param data - Pointer to data to insert. NULL is allowed if data_size is 0. * @param data_size - Size of data to insert. A value of 0 is allowed. * @param xTicksToWait - Ticks to wait for room in the ringbuffer. * * @return pdTRUE if succeeded, pdFALSE on time-out or when the buffer is larger * than indicated by xRingbufferGetMaxItemSize(ringbuf). */ BaseType_t xRingbufferSend(RingbufHandle_t ringbuf, void *data, size_t data_size, TickType_t ticks_to_wait); /** * @brief Insert an item into the ring buffer from an ISR * * @param ringbuf - Ring buffer to insert the item into * @param data - Pointer to data to insert. NULL is allowed if data_size is 0. * @param data_size - Size of data to insert. A value of 0 is allowed. * @param higher_prio_task_awoken - Value pointed to will be set to pdTRUE if the push woke up a higher * priority task. * * @return pdTRUE if succeeded, pdFALSE when the ring buffer does not have space. */ BaseType_t xRingbufferSendFromISR(RingbufHandle_t ringbuf, void *data, size_t data_size, BaseType_t *higher_prio_task_awoken); /** * @brief Retrieve an item from the ring buffer * * @note A call to vRingbufferReturnItem() is required after this to free up the data received. * * @param ringbuf - Ring buffer to retrieve the item from * @param item_size - Pointer to a variable to which the size of the retrieved item will be written. * @param xTicksToWait - Ticks to wait for items in the ringbuffer. * * @return Pointer to the retrieved item on success; *item_size filled with the length of the * item. NULL on timeout, *item_size is untouched in that case. */ void *xRingbufferReceive(RingbufHandle_t ringbuf, size_t *item_size, TickType_t ticks_to_wait); /** * @brief Retrieve an item from the ring buffer from an ISR * * @note A call to vRingbufferReturnItemFromISR() is required after this to free up the data received * * @param ringbuf - Ring buffer to retrieve the item from * @param item_size - Pointer to a variable to which the size of the retrieved item will be written. * * @return Pointer to the retrieved item on success; *item_size filled with the length of the * item. NULL when the ringbuffer is empty, *item_size is untouched in that case. */ void *xRingbufferReceiveFromISR(RingbufHandle_t ringbuf, size_t *item_size); /** * @brief Retrieve bytes from a ByteBuf type of ring buffer, specifying the maximum amount of bytes * to return * @note A call to vRingbufferReturnItem() is required after this to free up the data received. * * @param ringbuf - Ring buffer to retrieve the item from * @param item_size - Pointer to a variable to which the size of the retrieved item will be written. * @param xTicksToWait - Ticks to wait for items in the ringbuffer. * * @return Pointer to the retrieved item on success; *item_size filled with the length of the * item. NULL on timeout, *item_size is untouched in that case. */ void *xRingbufferReceiveUpTo(RingbufHandle_t ringbuf, size_t *item_size, TickType_t ticks_to_wait, size_t wanted_size); /** * @brief Retrieve bytes from a ByteBuf type of ring buffer, specifying the maximum amount of bytes * to return. Call this from an ISR. * * @note A call to vRingbufferReturnItemFromISR() is required after this to free up the data received * * @param ringbuf - Ring buffer to retrieve the item from * @param item_size - Pointer to a variable to which the size of the retrieved item will be written. * * @return Pointer to the retrieved item on success; *item_size filled with the length of the * item. NULL when the ringbuffer is empty, *item_size is untouched in that case. */ void *xRingbufferReceiveUpToFromISR(RingbufHandle_t ringbuf, size_t *item_size, size_t wanted_size); /** * @brief Return a previously-retrieved item to the ringbuffer * * @param ringbuf - Ring buffer the item was retrieved from * @param item - Item that was received earlier * * @return void */ void vRingbufferReturnItem(RingbufHandle_t ringbuf, void *item); /** * @brief Return a previously-retrieved item to the ringbuffer from an ISR * * @param ringbuf - Ring buffer the item was retrieved from * @param item - Item that was received earlier * @param higher_prio_task_awoken - Value pointed to will be set to pdTRUE if the push woke up a higher * priority task. * * @return void */ void vRingbufferReturnItemFromISR(RingbufHandle_t ringbuf, void *item, BaseType_t *higher_prio_task_awoken); /** * @brief Add the ringbuffer to a queue set. This specifically adds the semaphore that indicates * more space has become available in the ringbuffer. * * @param ringbuf - Ring buffer to add to the queue set * @param xQueueSet - Queue set to add the ringbuffer to * * @return pdTRUE on success, pdFALSE otherwise */ BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); /** * @brief Add the ringbuffer to a queue set. This specifically adds the semaphore that indicates * something has been written into the ringbuffer. * * @param ringbuf - Ring buffer to add to the queue set * @param xQueueSet - Queue set to add the ringbuffer to * * @return pdTRUE on success, pdFALSE otherwise */ BaseType_t xRingbufferAddToQueueSetWrite(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); /** * @brief Remove the ringbuffer from a queue set. This specifically removes the semaphore that indicates * more space has become available in the ringbuffer. * * @param ringbuf - Ring buffer to remove from the queue set * @param xQueueSet - Queue set to remove the ringbuffer from * * @return pdTRUE on success, pdFALSE otherwise */ BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); /** * @brief Remove the ringbuffer from a queue set. This specifically removes the semaphore that indicates * something has been written to the ringbuffer. * * @param ringbuf - Ring buffer to remove from the queue set * @param xQueueSet - Queue set to remove the ringbuffer from * * @return pdTRUE on success, pdFALSE otherwise */ BaseType_t xRingbufferRemoveFromQueueSetWrite(RingbufHandle_t ringbuf, QueueSetHandle_t xQueueSet); /** * @brief Debugging function to print the internal pointers in the ring buffer * * @param ringbuf - Ring buffer to show * * @return void */ void xRingbufferPrintInfo(RingbufHandle_t ringbuf); #ifdef __cplusplus } #endif #endif /* FREERTOS_RINGBUF_H */
38.992565
126
0.745162
[ "object" ]
23f7a918bb6f62fad85c68f0d0e498c73c56d98e
3,135
h
C
android/android_9/frameworks/native/libs/sensor/include/sensor/SensorManager.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/libs/sensor/include/sensor/SensorManager.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/libs/sensor/include/sensor/SensorManager.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_GUI_SENSOR_MANAGER_H #define ANDROID_GUI_SENSOR_MANAGER_H #include <map> #include <unordered_map> #include <stdint.h> #include <sys/types.h> #include <binder/IBinder.h> #include <binder/IPCThreadState.h> #include <binder/IServiceManager.h> #include <utils/Errors.h> #include <utils/StrongPointer.h> #include <utils/Vector.h> #include <utils/String8.h> #include <sensor/SensorEventQueue.h> // ---------------------------------------------------------------------------- // Concrete types for the NDK struct ASensorManager { }; struct native_handle; typedef struct native_handle native_handle_t; // ---------------------------------------------------------------------------- namespace android { // ---------------------------------------------------------------------------- class ISensorServer; class Sensor; class SensorEventQueue; // ---------------------------------------------------------------------------- class SensorManager : public ASensorManager { public: static SensorManager& getInstanceForPackage(const String16& packageName); ~SensorManager(); ssize_t getSensorList(Sensor const* const** list); ssize_t getDynamicSensorList(Vector<Sensor>& list); Sensor const* getDefaultSensor(int type); sp<SensorEventQueue> createEventQueue(String8 packageName = String8(""), int mode = 0); bool isDataInjectionEnabled(); int createDirectChannel(size_t size, int channelType, const native_handle_t *channelData); void destroyDirectChannel(int channelNativeHandle); int configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel); int setOperationParameter(int handle, int type, const Vector<float> &floats, const Vector<int32_t> &ints); private: // DeathRecipient interface void sensorManagerDied(); static status_t waitForSensorService(sp<ISensorServer> *server); SensorManager(const String16& opPackageName); status_t assertStateLocked(); private: static Mutex sLock; static std::map<String16, SensorManager*> sPackageInstances; Mutex mLock; sp<ISensorServer> mSensorServer; Sensor const** mSensorList; Vector<Sensor> mSensors; sp<IBinder::DeathRecipient> mDeathObserver; const String16 mOpPackageName; std::unordered_map<int, sp<ISensorEventConnection>> mDirectConnection; int32_t mDirectConnectionHandle; }; // ---------------------------------------------------------------------------- }; // namespace android #endif // ANDROID_GUI_SENSOR_MANAGER_H
33
110
0.664434
[ "vector" ]
23f82c976366b5be8fa508f17bb71953fc253893
323,116
c
C
net/tapi/server/server.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/tapi/server/server.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/tapi/server/server.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ BUILD Version: 0000 // Increment this if a change has global effects Copyright (c) 1995-1998 Microsoft Corporation Module Name: server.c Abstract: Src module for tapi server Author: Dan Knudson (DanKn) 01-Apr-1995 Revision History: --*/ #include "windows.h" #include "stdio.h" #include "stdlib.h" #include "tchar.h" #include "assert.h" #include "process.h" #include "winsvcp.h" #include "tapi.h" #include "tspi.h" #include "utils.h" #include "client.h" #include "server.h" #define INIT_FUNCTABLE #include "private.h" #undef INIT_FUNCTABLE #include "tapsrv.h" #include "tapiperf.h" #include "winnetwk.h" #include "buffer.h" #include "line.h" #include "tapihndl.h" #include <tchar.h> #include "loc_comn.h" #include "tapimmc.h" #include "resource.h" // // Bit flags to tell ServiceShutdown how much of the service has been initialized // #define SERVICE_INIT_TRACELOG 0x00000001 #define SERVICE_INIT_SCM_REGISTERED 0x00000002 #define SERVICE_INIT_LOCKTABLE 0x00000004 #define SERVICE_INIT_CRITSEC_SAFEMUTEX 0x00000008 #define SERVICE_INIT_CRITSEC_REMOTECLI 0x00000010 #define SERVICE_INIT_CRITSEC_PRILIST 0x00000020 #define SERVICE_INIT_CRITSEC_MGMTDLLS 0x00000040 #define SERVICE_INIT_CRITSEC_DLLLIST 0x00000080 #define SERVICE_INIT_CRITSEC_CLIENTHND 0x00000100 #define SERVICE_INIT_CRITSEC_CNCLIENTMSG 0x00000200 #define SERVICE_INIT_CRITSEC_DGCLIENTMSG 0x00000400 #define SERVICE_INIT_CRITSEC_GLOB_CRITSEC 0x00000800 #define SERVICE_INIT_CRITSEC_GLOB_REMOTESP 0x00001000 #define SERVICE_INIT_CRITSEC_MGMT 0x00002000 #define SERVICE_INIT_SPEVENT_HANDLER 0x00004000 #define SERVICE_INIT_MANAGEMENT_DLL 0x00008000 #define SERVICE_INIT_EVENT_NOTIFICATION 0x00010000 #define SERVICE_INIT_RPC 0x00020000 #define SERVICE_INIT_CRITSEC_SCP 0x00040000 #if DBG BOOL gbBreakOnLeak = FALSE; BOOL gfBreakOnSeriousProblems = FALSE; void DumpHandleList(); #endif extern const DWORD TapiPrimes[]; const TCHAR gszRegTapisrvSCPGuid[] = TEXT("TAPISRVSCPGUID"); // PERF PERFBLOCK PerfBlock; BOOL InitPerf(); TAPIGLOBALS TapiGlobals; HANDLE ghTapisrvHeap = NULL, ghHandleTable = NULL; HANDLE ghEventService; HANDLE ghSCMAutostartEvent = NULL; HANDLE ghProvRegistryMutex = NULL; BOOL gbPriorityListsInitialized; BOOL gbQueueSPEvents; BOOL gfWeHadAtLeastOneClient; BOOL gbSPEventHandlerThreadExit; BOOL gbNTServer; BOOL gbServerInited; BOOL gbAutostartDone = FALSE; BOOL gbHighSecurity = TRUE; HINSTANCE ghInstance; CRITICAL_SECTION gSafeMutexCritSec, gRemoteCliEventBufCritSec, gPriorityListCritSec, gManagementDllsCritSec, gDllListCritSec, gClientHandleCritSec, gCnClientMsgPendingCritSec, gDgClientMsgPendingCritSec, gLockTableCritSecs[2], gSCPCritSec; #define MIN_WAIT_HINT 60000 DWORD gdwServiceState = SERVICE_START_PENDING, gdwWaitHint = MIN_WAIT_HINT, gdwCheckPoint = 0, gdwDllIDs = 0, gdwRpcTimeout = 30000, gdwRpcRetryCount = 5, gdwTotalAsyncThreads = 0, gdwThreadsPerProcessor = 4, guiAlignmentFaultEnabled = FALSE, gdwTapiSCPTTL = 60 * 24; gdwServiceInitFlags = 0; DWORD gdwPointerToLockTableIndexBits; CRITICAL_SECTION *gLockTable; DWORD gdwNumLockTableEntries; BOOL (WINAPI * pfnInitializeCriticalSectionAndSpinCount) (LPCRITICAL_SECTION, DWORD); LIST_ENTRY CnClientMsgPendingListHead; LIST_ENTRY DgClientMsgPendingListHead; SPEVENTHANDLERTHREADINFO gSPEventHandlerThreadInfo; PSPEVENTHANDLERTHREADINFO aSPEventHandlerThreadInfo; DWORD gdwNumSPEventHandlerThreads; LONG glNumActiveSPEventHandlerThreads; #if DBG const TCHAR gszTapisrvDebugLevel[] = TEXT("TapiSrvDebugLevel"); const TCHAR gszBreakOnLeak[] = TEXT("BreakOnLeak"); #endif const TCHAR gszProvider[] = TEXT("Provider"); const TCHAR gszNumLines[] = TEXT("NumLines"); const TCHAR gszUIDllName[] = TEXT("UIDllName"); const TCHAR gszNumPhones[] = TEXT("NumPhones"); const TCHAR gszSyncLevel[] = TEXT("SyncLevel"); const TCHAR gszProductType[] = TEXT("ProductType"); const TCHAR gszProductTypeServer[] = TEXT("ServerNT"); const TCHAR gszProductTypeLanmanNt[] = TEXT("LANMANNT"); const TCHAR gszProviderID[] = TEXT("ProviderID"); const TCHAR gszNumProviders[] = TEXT("NumProviders"); const TCHAR gszNextProviderID[] = TEXT("NextProviderID"); const TCHAR gszRequestMakeCallW[] = TEXT("RequestMakeCall"); const TCHAR gszRequestMediaCallW[] = TEXT("RequestMediaCall"); const TCHAR gszProviderFilename[] = TEXT("ProviderFilename"); const WCHAR gszMapperDll[] = L"MapperDll"; const WCHAR gszManagementDlls[] = L"ManagementDlls"; const WCHAR gszHighSecurity[] = L"HighSecurity"; const TCHAR gszDomainName[] = TEXT("DomainName"); const TCHAR gszRegKeyHandoffPriorities[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Telephony\\HandoffPriorities"); const TCHAR gszRegKeyHandoffPrioritiesMediaModes[] = TEXT("MediaModes"); const TCHAR gszRegKeyTelephony[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Telephony"); const TCHAR gszRegKeyProviders[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Telephony\\Providers"); const TCHAR gszRegKeyServer[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Telephony\\Server"); const TCHAR gszRegKeyNTServer[] = TEXT("System\\CurrentControlSet\\Control\\ProductOptions"); const TCHAR *gaszMediaModes[] = { TEXT(""), TEXT("unknown"), TEXT("interactivevoice"), TEXT("automatedvoice"), TEXT("datamodem"), TEXT("g3fax"), TEXT("tdd"), TEXT("g4fax"), TEXT("digitaldata"), TEXT("teletex"), TEXT("videotex"), TEXT("telex"), TEXT("mixed"), TEXT("adsi"), TEXT("voiceview"), TEXT("video"), NULL }; // used for GetProcAddress calls, remain as ANSI const char *gaszTSPIFuncNames[] = { "TSPI_lineAccept", "TSPI_lineAddToConference", "TSPI_lineAgentSpecific", "TSPI_lineAnswer", "TSPI_lineBlindTransfer", "TSPI_lineClose", "TSPI_lineCloseCall", "TSPI_lineCompleteCall", "TSPI_lineCompleteTransfer", "TSPI_lineConditionalMediaDetection", "TSPI_lineDevSpecific", "TSPI_lineDevSpecificFeature", "TSPI_lineDial", "TSPI_lineDrop", "TSPI_lineForward", "TSPI_lineGatherDigits", "TSPI_lineGenerateDigits", "TSPI_lineGenerateTone", "TSPI_lineGetAddressCaps", "TSPI_lineGetAddressID", "TSPI_lineGetAddressStatus", "TSPI_lineGetAgentActivityList", "TSPI_lineGetAgentCaps", "TSPI_lineGetAgentGroupList", "TSPI_lineGetAgentStatus", "TSPI_lineGetCallAddressID", "TSPI_lineGetCallInfo", "TSPI_lineGetCallStatus", "TSPI_lineGetDevCaps", "TSPI_lineGetDevConfig", "TSPI_lineGetExtensionID", "TSPI_lineGetIcon", "TSPI_lineGetID", "TSPI_lineGetLineDevStatus", "TSPI_lineGetNumAddressIDs", "TSPI_lineHold", "TSPI_lineMakeCall", "TSPI_lineMonitorDigits", "TSPI_lineMonitorMedia", "TSPI_lineMonitorTones", "TSPI_lineNegotiateExtVersion", "TSPI_lineNegotiateTSPIVersion", "TSPI_lineOpen", "TSPI_linePark", "TSPI_linePickup", "TSPI_linePrepareAddToConference", "TSPI_lineRedirect", "TSPI_lineReleaseUserUserInfo", "TSPI_lineRemoveFromConference", "TSPI_lineSecureCall", "TSPI_lineSelectExtVersion", "TSPI_lineSendUserUserInfo", "TSPI_lineSetAgentActivity", "TSPI_lineSetAgentGroup", "TSPI_lineSetAgentState", "TSPI_lineSetAppSpecific", "TSPI_lineSetCallData", "TSPI_lineSetCallParams", "TSPI_lineSetCallQualityOfService", "TSPI_lineSetCallTreatment", "TSPI_lineSetCurrentLocation", "TSPI_lineSetDefaultMediaDetection", "TSPI_lineSetDevConfig", "TSPI_lineSetLineDevStatus", "TSPI_lineSetMediaControl", "TSPI_lineSetMediaMode", "TSPI_lineSetStatusMessages", "TSPI_lineSetTerminal", "TSPI_lineSetupConference", "TSPI_lineSetupTransfer", "TSPI_lineSwapHold", "TSPI_lineUncompleteCall", "TSPI_lineUnhold", "TSPI_lineUnpark", "TSPI_phoneClose", "TSPI_phoneDevSpecific", "TSPI_phoneGetButtonInfo", "TSPI_phoneGetData", "TSPI_phoneGetDevCaps", "TSPI_phoneGetDisplay", "TSPI_phoneGetExtensionID", "TSPI_phoneGetGain", "TSPI_phoneGetHookSwitch", "TSPI_phoneGetIcon", "TSPI_phoneGetID", "TSPI_phoneGetLamp", "TSPI_phoneGetRing", "TSPI_phoneGetStatus", "TSPI_phoneGetVolume", "TSPI_phoneNegotiateExtVersion", "TSPI_phoneNegotiateTSPIVersion", "TSPI_phoneOpen", "TSPI_phoneSelectExtVersion", "TSPI_phoneSetButtonInfo", "TSPI_phoneSetData", "TSPI_phoneSetDisplay", "TSPI_phoneSetGain", "TSPI_phoneSetHookSwitch", "TSPI_phoneSetLamp", "TSPI_phoneSetRing", "TSPI_phoneSetStatusMessages", "TSPI_phoneSetVolume", "TSPI_providerCreateLineDevice", "TSPI_providerCreatePhoneDevice", "TSPI_providerEnumDevices", "TSPI_providerFreeDialogInstance", "TSPI_providerGenericDialogData", "TSPI_providerInit", "TSPI_providerShutdown", "TSPI_providerUIIdentify", "TSPI_lineMSPIdentify", "TSPI_lineReceiveMSPData", "TSPI_providerCheckForNewUser", "TSPI_lineGetCallIDs", "TSPI_lineGetCallHubTracking", "TSPI_lineSetCallHubTracking", "TSPI_providerPrivateFactoryIdentify", "TSPI_lineDevSpecificEx", "TSPI_lineCreateAgent", "TSPI_lineCreateAgentSession", "TSPI_lineGetAgentInfo", "TSPI_lineGetAgentSessionInfo", "TSPI_lineGetAgentSessionList", "TSPI_lineGetQueueInfo", "TSPI_lineGetGroupList", "TSPI_lineGetQueueList", "TSPI_lineSetAgentMeasurementPeriod", "TSPI_lineSetAgentSessionState", "TSPI_lineSetQueueMeasurementPeriod", "TSPI_lineSetAgentStateEx", "TSPI_lineGetProxyStatus", "TSPI_lineCreateMSPInstance", "TSPI_lineCloseMSPInstance", NULL }; // used for GetProcAddress calls, remain as ANSI const char *gaszTCFuncNames[] = { "TAPICLIENT_Load", "TAPICLIENT_Free", "TAPICLIENT_ClientInitialize", "TAPICLIENT_ClientShutdown", "TAPICLIENT_GetDeviceAccess", "TAPICLIENT_LineAddToConference", "TAPICLIENT_LineBlindTransfer", "TAPICLIENT_LineConfigDialog", "TAPICLIENT_LineDial", "TAPICLIENT_LineForward", "TAPICLIENT_LineGenerateDigits", "TAPICLIENT_LineMakeCall", "TAPICLIENT_LineOpen", "TAPICLIENT_LineRedirect", "TAPICLIENT_LineSetCallData", "TAPICLIENT_LineSetCallParams", "TAPICLIENT_LineSetCallPrivilege", "TAPICLIENT_LineSetCallTreatment", "TAPICLIENT_LineSetCurrentLocation", "TAPICLIENT_LineSetDevConfig", "TAPICLIENT_LineSetLineDevStatus", "TAPICLIENT_LineSetMediaControl", "TAPICLIENT_LineSetMediaMode", "TAPICLIENT_LineSetTerminal", "TAPICLIENT_LineSetTollList", "TAPICLIENT_PhoneConfigDialog", "TAPICLIENT_PhoneOpen", NULL }; PTPROVIDER pRemoteSP; extern WCHAR gszTapiAdministrators[]; extern WCHAR gszFileName[]; extern WCHAR gszLines[]; extern WCHAR gszPhones[]; extern WCHAR gszEmptyString[]; extern LPLINECOUNTRYLIST gpCountryList; extern LPDEVICEINFOLIST gpLineInfoList; extern LPDEVICEINFOLIST gpPhoneInfoList; extern LPDWORD gpLineDevFlags; extern DWORD gdwNumFlags; extern FILETIME gftLineLastWrite; extern FILETIME gftPhoneLastWrite; extern CRITICAL_SECTION gMgmtCritSec; extern BOOL gbLockMMCWrite; #define POINTERTOTABLEINDEX(p) \ ((((ULONG_PTR) p) >> 4) & gdwPointerToLockTableIndexBits) #define LOCKTCLIENT(p) \ EnterCriticalSection(&gLockTable[POINTERTOTABLEINDEX(p)]) #define UNLOCKTCLIENT(p) \ LeaveCriticalSection(&gLockTable[POINTERTOTABLEINDEX(p)]) #if DBG DWORD gdwDebugLevel; DWORD gdwQueueDebugLevel = 0; #endif typedef struct { DWORD dwTickCount; PTCLIENT ptClient; } WATCHDOGSTRUCT, *PWATCHDOGSTRUCT; struct { PHANDLE phThreads; DWORD dwNumThreads; PWATCHDOGSTRUCT pWatchDogStruct; HANDLE hEvent; BOOL bExit; } gEventNotificationThreadParams; struct { LONG lCookie; LONG lNumRundowns; BOOL bIgnoreRundowns; } gRundownLock; BOOL VerifyDomainName (HKEY hKey); void EventNotificationThread( LPVOID pParams ); VOID WINAPI ServiceMain ( DWORD dwArgc, PWSTR* lpszArgv ); void PASCAL LineEventProc( HTAPILINE htLine, HTAPICALL htCall, DWORD dwMsg, ULONG_PTR Param1, ULONG_PTR Param2, ULONG_PTR Param3 ); void CALLBACK LineEventProcSP( HTAPILINE htLine, HTAPICALL htCall, DWORD dwMsg, ULONG_PTR Param1, ULONG_PTR Param2, ULONG_PTR Param3 ); void PASCAL PhoneEventProc( HTAPIPHONE htPhone, DWORD dwMsg, ULONG_PTR Param1, ULONG_PTR Param2, ULONG_PTR Param3 ); void CALLBACK PhoneEventProcSP( HTAPIPHONE htPhone, DWORD dwMsg, ULONG_PTR Param1, ULONG_PTR Param2, ULONG_PTR Param3 ); PTLINELOOKUPENTRY GetLineLookupEntry( DWORD dwDeviceID ); PTPHONELOOKUPENTRY GetPhoneLookupEntry( DWORD dwDeviceID ); char * PASCAL MapResultCodeToText( LONG lResult, char *pszResult ); DWORD InitSecurityDescriptor( PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID * ppSid, PACL * ppDacl ); void PASCAL GetMediaModesPriorityLists( HKEY hKeyHandoffPriorities, PRILISTSTRUCT ** ppList ); void PASCAL GetPriorityList( HKEY hKeyHandoffPriorities, const TCHAR *pszListName, WCHAR **ppszPriorityList ); void PASCAL SetMediaModesPriorityList( HKEY hKeyPri, PRILISTSTRUCT * pPriListStruct ); void PASCAL SetPriorityList( HKEY hKeyHandoffPriorities, const TCHAR *pszListName, WCHAR *pszPriorityList ); void SPEventHandlerThread( PSPEVENTHANDLERTHREADINFO pInfo ); PTCLIENT PASCAL WaitForExclusiveClientAccess( PTCLIENT ptClient ); BOOL IsNTServer( void ); void CleanUpManagementMemory( ); #if TELE_SERVER void ReadAndInitMapper(); void ReadAndInitManagementDlls(); void ManagementProc( LONG l ); void GetManageDllListPointer( PTMANAGEDLLLISTHEADER * ppDllList ); void FreeManageDllListPointer( PTMANAGEDLLLISTHEADER pDllList ); BOOL GetTCClient( PTMANAGEDLLINFO pDll, PTCLIENT ptClient, DWORD dwAPI, HMANAGEMENTCLIENT *phClient ); #endif LRESULT UpdateLastWriteTime ( BOOL bLine ); LRESULT BuildDeviceInfoList( BOOL bLine ); BOOL CleanUpClient( PTCLIENT ptClient, BOOL bRundown ); void PASCAL SendReinitMsgToAllXxxApps( void ); LONG AppendNewDeviceInfo ( BOOL bLine, DWORD dwDeviceID ); DWORD PASCAL MyInitializeCriticalSection( LPCRITICAL_SECTION pCriticalSection, DWORD dwSpinCount ) { DWORD dwRet = 0; __try { if (pfnInitializeCriticalSectionAndSpinCount) { (*pfnInitializeCriticalSectionAndSpinCount)( pCriticalSection, dwSpinCount ); } else { InitializeCriticalSection (pCriticalSection); } } __except (EXCEPTION_EXECUTE_HANDLER) { dwRet = GetExceptionCode(); } return dwRet; } BOOL WINAPI DllMain ( HINSTANCE hinst, DWORD dwReason, LPVOID pvReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: { ghInstance = hinst; DisableThreadLibraryCalls (hinst); break; } case DLL_PROCESS_DETACH: { break; } } return TRUE; } BOOL ReportStatusToSCMgr( DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwCheckPoint, DWORD dwWaitHint ) { SERVICE_STATUS ssStatus; if (!TapiGlobals.sshStatusHandle) { LOG((TL_ERROR, "sshStatusHandle is NULL in ReportStatusToSCMgr")); return FALSE; } ssStatus.dwServiceType = SERVICE_WIN32_SHARE_PROCESS; ssStatus.dwCurrentState = dwCurrentState; ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; ssStatus.dwWin32ExitCode = dwWin32ExitCode; ssStatus.dwServiceSpecificExitCode = 0; ssStatus.dwCheckPoint = dwCheckPoint; ssStatus.dwWaitHint = dwWaitHint; SetServiceStatus (TapiGlobals.sshStatusHandle, &ssStatus); return TRUE; } VOID ServiceControl( DWORD dwCtrlCode ) { LOG((TL_INFO, "Service control code=%ld", dwCtrlCode )); if ( SERVICE_CONTROL_STOP == dwCtrlCode || SERVICE_CONTROL_SHUTDOWN == dwCtrlCode ) { // // This service was stopped - alert any active apps, allowing // a little extra time for msg processing // LOG((TL_TRACE, "Somebody did a 'NET STOP TAPISRV'... exiting...")); SendReinitMsgToAllXxxApps(); ReportStatusToSCMgr( gdwServiceState = SERVICE_STOP_PENDING, NO_ERROR, (gdwCheckPoint = 0), 4000 ); Sleep (4000); LOG((TL_TRACE, "ServiceControl: calling RpcServerUnregisterIf")); RpcServerUnregisterIf (tapsrv_ServerIfHandle, NULL, TRUE); if (ghEventService) { SetEvent (ghEventService); } return; } if ( SERVICE_CONTROL_PAUSE == dwCtrlCode ) { LOG((TL_TRACE, "Somebody did a 'NET PAUSE TAPISRV'... not allowing new clients..." )); TapiGlobals.dwFlags |= TAPIGLOBALS_PAUSED; ReportStatusToSCMgr( gdwServiceState = SERVICE_PAUSED, NO_ERROR, (gdwCheckPoint = 0), 0 ); return; } if ( SERVICE_CONTROL_CONTINUE == dwCtrlCode ) { LOG((TL_TRACE, "Somebody did a 'NET CONTINUE TAPISRV'... allowing new clients..." )); TapiGlobals.dwFlags &= ~(TAPIGLOBALS_PAUSED); ReportStatusToSCMgr( gdwServiceState = SERVICE_RUNNING, NO_ERROR, (gdwCheckPoint = 0), 0 ); return; } switch (gdwServiceState) { case SERVICE_START_PENDING: case SERVICE_STOP_PENDING: ReportStatusToSCMgr( gdwServiceState, NO_ERROR, ++gdwCheckPoint, gdwWaitHint ); break; default: ReportStatusToSCMgr( gdwServiceState, NO_ERROR, 0, 0 ); break; } } VOID CALLBACK FreeContextCallback( LPVOID Context, LPVOID Context2 ) { if (Context2) { // // Special case: Context is a "fast" ptCallClient, that is // a TCALLCLIENT embedded within a TCALL structure, so don't // free it // } else { // // The general case, Context is the pointer to free // ServerFree (Context); } } #define DEFAULTRPCMINCALLS 1 #define DEFAULTRPCMAXCALLS 500 #define RPCMAXMAX 20000 #define RPCMINMAX 1000 typedef struct _SERVICE_SHUTDOWN_PARAMS { HANDLE hThreadMgmt; PSID psid; PACL pdacl; } SERVICE_SHUTDOWN_PARAMS; VOID CALLBACK ServiceShutdown ( PVOID lpParam, BOOLEAN fTimeOut ); VOID WINAPI ServiceMain ( DWORD dwArgc, PWSTR* lpszArgv ) { DWORD dwMinCalls, dwMaxCalls, i; HANDLE hThreadMgmt = NULL; BOOL bFatalError = FALSE; assert(gdwServiceInitFlags == 0); gdwServiceInitFlags = 0; TRACELOGREGISTER(_T("tapisrv")); gdwServiceInitFlags |= SERVICE_INIT_TRACELOG ; // // Initialize globals // ZeroMemory (&TapiGlobals, sizeof (TAPIGLOBALS)); TapiGlobals.ulPermMasks = EM_ALL; TapiGlobals.hProcess = GetCurrentProcess(); TapiGlobals.hLineIcon = LoadIcon (ghInstance, MAKEINTRESOURCE(IDI_LINE_ICON)); TapiGlobals.hPhoneIcon = LoadIcon (ghInstance, MAKEINTRESOURCE(IDI_PHONE_ICON)); gbPriorityListsInitialized = FALSE; gbQueueSPEvents = FALSE; gfWeHadAtLeastOneClient = FALSE; CnClientMsgPendingListHead.Flink = CnClientMsgPendingListHead.Blink = &CnClientMsgPendingListHead; DgClientMsgPendingListHead.Flink = DgClientMsgPendingListHead.Blink = &DgClientMsgPendingListHead; gdwNumSPEventHandlerThreads = 0; glNumActiveSPEventHandlerThreads = 0; pRemoteSP = (PTPROVIDER) NULL; gbSPEventHandlerThreadExit = FALSE; gRundownLock.lCookie = 0; gRundownLock.lNumRundowns = 0; gLockTable = NULL; gdwNumLockTableEntries = 0; gpCountryList = NULL; gpLineInfoList = NULL; gpPhoneInfoList = NULL; gpLineDevFlags = NULL; gdwNumFlags = 0; gbLockMMCWrite = FALSE; gdwServiceState = SERVICE_START_PENDING, gdwWaitHint = MIN_WAIT_HINT, gdwCheckPoint = 0, gdwDllIDs = 0, gdwRpcRetryCount = 5, gdwTotalAsyncThreads = 0, gdwThreadsPerProcessor = 4; gbNTServer = IsNTServer(); ghEventService = CreateEvent(NULL, TRUE, FALSE, NULL); gbAutostartDone = FALSE; #if defined(_ALPHA_) guiAlignmentFaultEnabled = SetErrorMode(0); SetErrorMode(guiAlignmentFaultEnabled); guiAlignmentFaultEnabled = !(guiAlignmentFaultEnabled & SEM_NOALIGNMENTFAULTEXCEPT); #else guiAlignmentFaultEnabled = 0; #endif // // Register the service control handler & report status to sc mgr // TapiGlobals.sshStatusHandle = RegisterServiceCtrlHandler( TEXT("tapisrv"), ServiceControl ); if (NULL == TapiGlobals.sshStatusHandle) { LOG((TL_TRACE, "ServiceMain: RegisterServiceCtrlHandler failed, error x%x", GetLastError() )); bFatalError = TRUE; } else { gdwServiceInitFlags |= SERVICE_INIT_SCM_REGISTERED; } if (!bFatalError) { ReportStatusToSCMgr( (gdwServiceState = SERVICE_START_PENDING), // service state NO_ERROR, // exit code (gdwCheckPoint = 0), // checkpoint gdwWaitHint // wait hint ); if (!(ghTapisrvHeap = HeapCreate (0, 0x10000, 0))) { ghTapisrvHeap = GetProcessHeap(); } ghHandleTable = CreateHandleTable( ghTapisrvHeap, FreeContextCallback, 0x10000, 0x7fffffff ); if (NULL == ghHandleTable) { LOG((TL_ERROR, "ServiceMain: CreateHandleTable failed")); bFatalError = TRUE; } else { InitPerf(); (FARPROC) pfnInitializeCriticalSectionAndSpinCount = GetProcAddress( GetModuleHandle (TEXT("kernel32.dll")), "InitializeCriticalSectionAndSpinCount" ); ghSCMAutostartEvent = OpenEvent( SYNCHRONIZE, FALSE, SC_AUTOSTART_EVENT_NAME ); if (NULL == ghSCMAutostartEvent) { LOG((TL_ERROR, "OpenEvent ('%s') failed, err=%d", SC_AUTOSTART_EVENT_NAME, GetLastError() )); } if (gbNTServer && !SecureTsecIni()) { LOG((TL_ERROR, "Failed to set security on the ini file" )); bFatalError = TRUE; } } } // // Grab relevent values from the registry // if (!bFatalError) { HKEY hKey; const TCHAR szRPCMinCalls[] = TEXT("Min"); const TCHAR szRPCMaxCalls[] = TEXT("Max"); const TCHAR szTapisrvWaitHint[] = TEXT("TapisrvWaitHint"); const TCHAR szRPCTimeout[] = TEXT("RPCTimeout"); #if DBG gdwDebugLevel = 0; #endif if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey ) == ERROR_SUCCESS) { DWORD dwDataSize = sizeof (DWORD), dwDataType; #if DBG RegQueryValueEx( hKey, gszTapisrvDebugLevel, 0, &dwDataType, (LPBYTE) &gdwDebugLevel, &dwDataSize ); dwDataSize = sizeof (DWORD); RegQueryValueEx( hKey, gszBreakOnLeak, 0, &dwDataType, (LPBYTE)&gbBreakOnLeak, &dwDataSize ); dwDataSize = sizeof (DWORD); RegQueryValueEx( hKey, TEXT("BreakOnSeriousProblems"), 0, &dwDataType, (LPBYTE) &gfBreakOnSeriousProblems, &dwDataSize ); dwDataSize = sizeof(DWORD); #endif RegQueryValueEx( hKey, szTapisrvWaitHint, 0, &dwDataType, (LPBYTE) &gdwWaitHint, &dwDataSize ); gdwWaitHint = (gdwWaitHint < MIN_WAIT_HINT ? MIN_WAIT_HINT : gdwWaitHint); dwDataSize = sizeof (DWORD); if (RegQueryValueEx( hKey, szRPCMinCalls, NULL, &dwDataType, (LPBYTE) &dwMinCalls, &dwDataSize ) != ERROR_SUCCESS) { dwMinCalls = DEFAULTRPCMINCALLS; } dwDataSize = sizeof (DWORD); if (RegQueryValueEx( hKey, TEXT("TapiScpTTL"), NULL, &dwDataType, (LPBYTE) &gdwTapiSCPTTL, &dwDataSize ) != ERROR_SUCCESS) { gdwTapiSCPTTL = 60 * 24; // default to 24 hours } if (gdwTapiSCPTTL < 60) { gdwTapiSCPTTL = 60; // 60 minute TTL as the minimum } dwDataSize = sizeof (DWORD); if (RegQueryValueEx( hKey, szRPCMaxCalls, NULL, &dwDataType, (LPBYTE) &dwMaxCalls, &dwDataSize ) != ERROR_SUCCESS) { dwMaxCalls = DEFAULTRPCMAXCALLS; } LOG((TL_INFO, "RPC min calls %lu RPC max calls %lu", dwMinCalls, dwMaxCalls )); // check values if (dwMaxCalls == 0) { LOG((TL_INFO, "RPC max at 0. Changed to %lu", DEFAULTRPCMAXCALLS )); dwMaxCalls = DEFAULTRPCMAXCALLS; } if (dwMinCalls == 0) { LOG((TL_INFO, "RPC min at 0. Changed to %lu", DEFAULTRPCMINCALLS )); dwMinCalls = DEFAULTRPCMINCALLS; } if (dwMaxCalls > RPCMAXMAX) { LOG((TL_INFO, "RPC max too high at %lu. Changed to %lu", dwMaxCalls, RPCMAXMAX )); dwMaxCalls = RPCMAXMAX; } if (dwMinCalls > dwMaxCalls) { LOG((TL_INFO, "RPC min greater than RPC max. Changed to %lu", dwMaxCalls )); dwMinCalls = dwMaxCalls; } if (dwMinCalls > RPCMINMAX) { LOG((TL_INFO, "RPC min greater than allowed at %lu. Changed to %lu", dwMinCalls, RPCMINMAX )); dwMinCalls = RPCMINMAX; } dwDataSize = sizeof (DWORD); if (RegQueryValueEx( hKey, szRPCTimeout, NULL, &dwDataType, (LPBYTE) &gdwRpcTimeout, &dwDataSize ) != ERROR_SUCCESS) { gdwRpcTimeout = 30000; } VerifyDomainName (hKey); RegCloseKey (hKey); } } LOG((TL_TRACE, "ServiceMain: enter")); // // More server-only reg stuff // #if TELE_SERVER if (!bFatalError) { HKEY hKey; DWORD dwDataSize; DWORD dwDataType; DWORD dwTemp; DWORD dwHighSecurity; TCHAR szProductType[64]; // // Get the "Server" reg settings // // It would have made more sense if this reg value were named // "EnableSharing", but we have to support what's out there // already... // if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyServer, 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) { dwDataSize = sizeof (dwTemp); dwTemp = 1; // default is sharing == disabled if (RegQueryValueEx( hKey, TEXT("DisableSharing"), 0, &dwDataType, (LPBYTE) &dwTemp, &dwDataSize ) == ERROR_SUCCESS) { if (dwTemp == 0) { TapiGlobals.dwFlags |= TAPIGLOBALS_SERVER; } } gdwTotalAsyncThreads = 0; dwDataSize = sizeof (DWORD); RegQueryValueEx( hKey, TEXT("TotalAsyncThreads"), 0, &dwDataType, (LPBYTE) &gdwTotalAsyncThreads, &dwDataSize ); if (gdwTotalAsyncThreads) { LOG((TL_INFO, "Setting total async threads to %d", gdwTotalAsyncThreads )); } gdwThreadsPerProcessor = 4; dwDataSize = sizeof (DWORD); RegQueryValueEx( hKey, TEXT("ThreadsPerProcessor"), 0, &dwDataType, (LPBYTE) &gdwThreadsPerProcessor, &dwDataSize ); LOG((TL_INFO, "Threads per processor is %d", gdwThreadsPerProcessor)); dwHighSecurity = 1; dwDataSize = sizeof (DWORD); if (ERROR_SUCCESS == RegQueryValueEx( hKey, gszHighSecurity, 0, &dwDataType, (LPBYTE) &dwHighSecurity, &dwDataSize ) && 0 == dwHighSecurity ) { LOG((TL_INFO, "Setting High Security to FALSE")); gbHighSecurity = FALSE; } RegCloseKey( hKey ); } // // Now check to see if this is really running on NT Server. // If not, then, turn off the SERVER bit in dwFlags. // if (!gbNTServer) { TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); } } #endif // // Init the lock table // if (!bFatalError) { HKEY hKey; DWORD i, dwLockTableNumEntries, dwDataSize = sizeof(DWORD), dwDataType, dwBitMask; BOOL bException = FALSE; #define MIN_HANDLE_BUCKETS 8 #define MAX_HANDLE_BUCKETS 128 dwLockTableNumEntries = (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER ? 32 : MIN_HANDLE_BUCKETS); // // Retrieve registry override settings, if any // if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) { RegQueryValueExW( hKey, L"TapisrvNumHandleBuckets", 0, &dwDataType, (LPBYTE) &dwLockTableNumEntries, &dwDataSize ); //RegQueryValueExW( // hKey, // L"TapisrvSpinCount", // 0, // &dwDataType, // (LPBYTE) &gdwSpinCount, // &dwDataSize // ); RegCloseKey (hKey); } // // Determine a reasonable number of lock table entries, which // is some number == 2**N within min/max possible values // if (dwLockTableNumEntries > MAX_HANDLE_BUCKETS) { dwLockTableNumEntries = MAX_HANDLE_BUCKETS; } else if (dwLockTableNumEntries < MIN_HANDLE_BUCKETS) { dwLockTableNumEntries = MIN_HANDLE_BUCKETS; } for( dwBitMask = MAX_HANDLE_BUCKETS; (dwBitMask & dwLockTableNumEntries) == 0; dwBitMask >>= 1 ); dwLockTableNumEntries = dwBitMask; // // Calculate pointer-to-lock-table-index conversion value // (significant bits) // gdwPointerToLockTableIndexBits = dwLockTableNumEntries - 1; //gdwSpinCount = ( gdwSpinCount > MAX_SPIN_COUNT ? // MAX_SPIN_COUNT : gdwSpinCount ); // // Alloc & init the lock table // if (!(gLockTable = ServerAlloc( dwLockTableNumEntries * sizeof (CRITICAL_SECTION) ))) { gLockTable = gLockTableCritSecs; dwLockTableNumEntries = sizeof(gLockTableCritSecs) / sizeof(CRITICAL_SECTION); gdwPointerToLockTableIndexBits = dwLockTableNumEntries - 1; } for (i = 0; i < dwLockTableNumEntries; i++) { if ( NO_ERROR != MyInitializeCriticalSection (&gLockTable[i], 1000) ) { bException = TRUE; break; } } if (bException) { bFatalError = TRUE; LOG((TL_ERROR, "Exception in InitializeCriticalSection" )); for (; i > 0; i--) { DeleteCriticalSection (&gLockTable[i-1]); } if (gLockTable != gLockTableCritSecs) { ServerFree (gLockTable); } gLockTable = NULL; } else { gdwNumLockTableEntries = dwLockTableNumEntries; gdwServiceInitFlags |= SERVICE_INIT_LOCKTABLE; } } bFatalError = bFatalError || MyInitializeCriticalSection (&gSafeMutexCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_SAFEMUTEX; bFatalError = bFatalError || MyInitializeCriticalSection (&gRemoteCliEventBufCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_REMOTECLI; bFatalError = bFatalError || MyInitializeCriticalSection (&gPriorityListCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_PRILIST; bFatalError = bFatalError || MyInitializeCriticalSection (&gManagementDllsCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_MGMTDLLS; bFatalError = bFatalError || MyInitializeCriticalSection (&gDllListCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_DLLLIST; bFatalError = bFatalError || MyInitializeCriticalSection (&gClientHandleCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_CLIENTHND; bFatalError = bFatalError || MyInitializeCriticalSection (&gCnClientMsgPendingCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_CNCLIENTMSG; bFatalError = bFatalError || MyInitializeCriticalSection (&gDgClientMsgPendingCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_DGCLIENTMSG; bFatalError = bFatalError || TapiMyInitializeCriticalSection (&TapiGlobals.CritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_GLOB_CRITSEC; bFatalError = bFatalError || MyInitializeCriticalSection (&TapiGlobals.RemoteSPCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_GLOB_REMOTESP; bFatalError = bFatalError || MyInitializeCriticalSection (&gMgmtCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_MGMT; bFatalError = bFatalError || MyInitializeCriticalSection (&gSCPCritSec, 200); if(!bFatalError) gdwServiceInitFlags |= SERVICE_INIT_CRITSEC_SCP; ghProvRegistryMutex = CreateMutex (NULL, FALSE, NULL); bFatalError = bFatalError || (NULL == ghProvRegistryMutex); if (!bFatalError) { DWORD dwTID, i; HANDLE hThread; SYSTEM_INFO SystemInfo; BOOL bError = FALSE; // // Start a thread for as many processors there are // SystemInfo.dwNumberOfProcessors = 1; GetSystemInfo( &SystemInfo ); aSPEventHandlerThreadInfo = ServerAlloc( SystemInfo.dwNumberOfProcessors * sizeof (SPEVENTHANDLERTHREADINFO) ); if (!aSPEventHandlerThreadInfo) { aSPEventHandlerThreadInfo = &gSPEventHandlerThreadInfo; SystemInfo.dwNumberOfProcessors = 1; } for (i = 0; i < SystemInfo.dwNumberOfProcessors; i++) { if ( NO_ERROR != MyInitializeCriticalSection( &aSPEventHandlerThreadInfo[i].CritSec, 1000 ) ) { bError = TRUE; LOG((TL_ERROR, "Exception in InitializeCriticalSection")); break; } InitializeListHead (&aSPEventHandlerThreadInfo[i].ListHead); aSPEventHandlerThreadInfo[i].hEvent = CreateEvent( (LPSECURITY_ATTRIBUTES) NULL, TRUE, // manual reset FALSE, // non-signaled NULL // unnamed ); if (aSPEventHandlerThreadInfo[i].hEvent == NULL) { bError = TRUE; LOG((TL_ERROR, "CreateEvent('SPEventHandlerThread') " \ "(Proc%d)failed, err=%d", SystemInfo.dwNumberOfProcessors, GetLastError() )); DeleteCriticalSection(&aSPEventHandlerThreadInfo[i].CritSec); break; } if ((hThread = CreateThread( (LPSECURITY_ATTRIBUTES) NULL, 0, (LPTHREAD_START_ROUTINE) SPEventHandlerThread, (LPVOID) (aSPEventHandlerThreadInfo + gdwNumSPEventHandlerThreads), 0, &dwTID ))) { gdwNumSPEventHandlerThreads++; CloseHandle (hThread); } else { LOG((TL_ERROR, "CreateThread('SPEventHandlerThread') " \ "(Proc%d)failed, err=%d", SystemInfo.dwNumberOfProcessors, GetLastError() )); } } if (bError && i == 0) { bFatalError = TRUE; } else { glNumActiveSPEventHandlerThreads = (LONG) gdwNumSPEventHandlerThreads; gdwServiceInitFlags |= SERVICE_INIT_SPEVENT_HANDLER; } } // // Init some globals // #if TELE_SERVER TapiGlobals.pIDArrays = NULL; #endif if (!bFatalError) { DWORD dwSize = (MAX_COMPUTERNAME_LENGTH + 1) * sizeof(WCHAR); TapiGlobals.pszComputerName = ServerAlloc (dwSize); if (TapiGlobals.pszComputerName) { #ifdef PARTIAL_UNICODE { CHAR buf[MAX_COMPUTERNAME_LENGTH + 1]; GetComputerName (buf, &dwSize); MultiByteToWideChar( GetACP(), MB_PRECOMPOSED, buf, dwSize, TapiGlobals.pszComputerName, dwSize ); } #else GetComputerNameW(TapiGlobals.pszComputerName, &dwSize); #endif TapiGlobals.dwComputerNameSize = (1 + lstrlenW(TapiGlobals.pszComputerName)) * sizeof(WCHAR); } // Allocate the priority lists TapiGlobals.dwTotalPriorityLists = 0; TapiGlobals.dwUsedPriorityLists = 0; TapiGlobals.pPriLists = ( PRILISTSTRUCT * ) ServerAlloc( (sizeof(PRILISTSTRUCT)) * 5); if (NULL == TapiGlobals.pPriLists) { LOG((TL_ERROR, "ServerAlloc pPriLists failed.")); bFatalError = TRUE; } else { TapiGlobals.dwTotalPriorityLists = 5; } } #if TELE_SERVER if (!bFatalError) { ReadAndInitMapper(); ReadAndInitManagementDlls(); gdwServiceInitFlags |= SERVICE_INIT_MANAGEMENT_DLL; } // // Alloc the EventNotificationThread resources and start the thread // if ( !bFatalError && (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) { DWORD dwID; // now start a thread to wait for changes to the managementdll key hThreadMgmt = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)ManagementProc, 0, 0, &dwID ); if (!(gEventNotificationThreadParams.hEvent = CreateEvent( (LPSECURITY_ATTRIBUTES) NULL, // no security attrs TRUE, // manual reset FALSE, // initially non-signaled NULL // unnamed ))) { } gEventNotificationThreadParams.bExit = FALSE; { DWORD dwTID, dwCount; SYSTEM_INFO SystemInfo; // // Start a thread for as many processors there are // GetSystemInfo( &SystemInfo ); if (gdwTotalAsyncThreads) { dwCount = gdwTotalAsyncThreads; } else { dwCount = SystemInfo.dwNumberOfProcessors * gdwThreadsPerProcessor; } if (dwCount <= 0) { dwCount = 1; } while (dwCount > 0) { gEventNotificationThreadParams.phThreads = ServerAlloc( sizeof (HANDLE) * dwCount ); if (!gEventNotificationThreadParams.phThreads) { --dwCount; continue; } gEventNotificationThreadParams.pWatchDogStruct = ServerAlloc( sizeof (WATCHDOGSTRUCT) * dwCount ); if (!gEventNotificationThreadParams.pWatchDogStruct) { ServerFree (gEventNotificationThreadParams.phThreads); --dwCount; continue; } break; } gEventNotificationThreadParams.dwNumThreads = dwCount; for (i = 0; i < gEventNotificationThreadParams.dwNumThreads;) { if ((gEventNotificationThreadParams.phThreads[i] = CreateThread( (LPSECURITY_ATTRIBUTES) NULL, 0, (LPTHREAD_START_ROUTINE) EventNotificationThread, (LPVOID) ULongToPtr(i), 0, &dwTID ))) { i++; } else { LOG((TL_ERROR, "CreateThread('EventNotificationThread') failed, " \ "err=%d", GetLastError() )); gEventNotificationThreadParams.dwNumThreads--; } } } gdwServiceInitFlags |= SERVICE_INIT_EVENT_NOTIFICATION; } #endif // // Init Rpc server // gRundownLock.bIgnoreRundowns = FALSE; { RPC_STATUS status; unsigned int fDontWait = FALSE; BOOL fInited = FALSE; SECURITY_DESCRIPTOR sd; PSID psid = NULL; PACL pdacl = NULL; static SERVICE_SHUTDOWN_PARAMS s_ssp; HANDLE hWait; DWORD dwNumRetries = 0; s_ssp.psid = NULL; s_ssp.pdacl = NULL; s_ssp.hThreadMgmt = hThreadMgmt; if (!bFatalError) { InitSecurityDescriptor (&sd, &psid, &pdacl); s_ssp.psid = psid; s_ssp.pdacl = pdacl; // // The RPC endpoints are static => they will exist as long as the service // process has not exited => stop and restart on client machines will hit // error 1740 RPC_NT_DUPLICATE_ENDPOINT, but this is ok. // // On server machines, if we get error 1740 RPC_S_DUPLICATE_ENDPOINT, // it means that the previous tapisrv process instance has not completely // gone away, and when it will, it will also remove the RPC endpoint. // In this case we need to wait a bit and retry publishing the endpoint. // dwNumRetries = 0; RpcEp_retry: status = RpcServerUseProtseqEp( TEXT("ncacn_np"), (unsigned int) dwMaxCalls, TEXT("\\pipe\\tapsrv"), NULL ); if (status) { LOG((TL_TRACE, "RpcServerUseProtseqEp(np) ret'd %d", status)); if (RPC_S_DUPLICATE_ENDPOINT == status && gbNTServer) { // retry if (dwNumRetries++ < gdwRpcRetryCount) { Sleep (1000); goto RpcEp_retry; } } } dwNumRetries = 0; LpcEp_retry: status = RpcServerUseProtseqEp( TEXT("ncalrpc"), (unsigned int) dwMaxCalls, TEXT("tapsrvlpc"), &sd ); if (status) { LOG((TL_TRACE, "RpcServerUseProtseqEp(lrpc) ret'd %d", status)); if (RPC_S_DUPLICATE_ENDPOINT == status && gbNTServer) { // retry if (dwNumRetries++ < gdwRpcRetryCount) { Sleep (1000); goto LpcEp_retry; } } } LOG((TL_TRACE, "calling RpcServerRegisterAuthInfo")); status = RpcServerRegisterAuthInfo( NULL, RPC_C_AUTHN_WINNT, NULL, NULL ); if (status) { LOG((TL_TRACE, "RpcServerRegisterAuthInfo ret'd %d", status)); } ReportStatusToSCMgr( (gdwServiceState = SERVICE_RUNNING), // service state NO_ERROR, // exit code 0, // checkpoint 0 // wait hint ); LOG((TL_TRACE, "calling RpcServerListen")); status = RpcServerListen( (unsigned int)dwMinCalls, (unsigned int)dwMaxCalls, TRUE ); if (status) { LOG((TL_TRACE, "RpcServerListen ret'd %d", status)); } LOG((TL_TRACE, "calling RpcServerRegisterIfEx")); status = RpcServerRegisterIfEx( tapsrv_ServerIfHandle, // interface to register NULL, // MgrTypeUuid NULL, // MgrEpv; null means use default RPC_IF_AUTOLISTEN | RPC_IF_ALLOW_SECURE_ONLY, dwMaxCalls, NULL ); if (status) { LOG((TL_TRACE, "RpcServerRegisterIfEx ret'd %d", status)); } // // In TAPI server machine with a few thousands of lines or more, // ServerInit will take considerable amount of time, the // first user who does a lineInitialize will be hit with this // delay. Also the first person who does MMC management will also // hit a delay waiting for the server to collect information. Both // affects people's perception of TAPI performance. // // Solution: // 1. We put ServerInit to be done immediately after the server // is up. This way, as long as user does not come too fast, he won't // be penalized for being the first. // 2. We now try to build the management cache immediately // instead of waiting until MMC is used. This way, when MMC is started // the user do not have to wait. // // Of course, in both of the above cases, if a user tries to use // TAPI server before all the dusts settle down. He will have to // wait. // gbServerInited = FALSE; if (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) { TapiEnterCriticalSection (&TapiGlobals.CritSec); if (TapiGlobals.dwNumLineInits == 0 && TapiGlobals.dwNumPhoneInits == 0) { if (ServerInit(FALSE) == S_OK) { gbServerInited = TRUE; } else { LOG((TL_ERROR, "ServiceMain: ServerInit failed")); } } // Holde a reference here to prevent ServerShutdown TapiLeaveCriticalSection (&TapiGlobals.CritSec); UpdateTapiSCP (TRUE, NULL, NULL); EnterCriticalSection (&gMgmtCritSec); UpdateLastWriteTime(TRUE); BuildDeviceInfoList(TRUE); UpdateLastWriteTime(FALSE); BuildDeviceInfoList(FALSE); LeaveCriticalSection (&gMgmtCritSec); } gdwServiceInitFlags |= SERVICE_INIT_RPC; if (ghEventService == NULL || !RegisterWaitForSingleObject( &hWait, ghEventService, ServiceShutdown, (PVOID)&s_ssp, INFINITE, WT_EXECUTEONLYONCE ) ) { ServiceShutdown ((PVOID) &s_ssp, FALSE); } } if (bFatalError) { ServiceShutdown ((PVOID) &s_ssp, FALSE); } } } VOID CALLBACK ServiceShutdown ( PVOID lpParam, BOOLEAN fTimeOut ) { SERVICE_SHUTDOWN_PARAMS *pssp = (SERVICE_SHUTDOWN_PARAMS *)lpParam; HANDLE hThreadMgmt; PSID psid; PACL pdacl; DWORD i; if (pssp == NULL) { return; } hThreadMgmt = pssp->hThreadMgmt; psid = pssp->psid; pdacl = pssp->pdacl; // Mark Tapi server to be inactive for service stop // Wait max 20 seconds for Management thread to terminate if (hThreadMgmt) { WaitForSingleObject (hThreadMgmt, INFINITE); CloseHandle (hThreadMgmt); } if (gbNTServer && (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_GLOB_CRITSEC) ) { TapiEnterCriticalSection (&TapiGlobals.CritSec); if (TapiGlobals.dwNumLineInits == 0 && TapiGlobals.dwNumPhoneInits == 0 && gbServerInited ) { ServerShutdown(); } TapiLeaveCriticalSection (&TapiGlobals.CritSec); } ServerFree (psid); ServerFree (pdacl); gbSPEventHandlerThreadExit = TRUE; // // If there are any clients left then tear them down. This will // cause any existing service providers to get unloaded, etc. // { PTCLIENT ptClient; while ((ptClient = TapiGlobals.ptClients) != NULL) { if (!CleanUpClient (ptClient, TRUE)) { // // CleanUpClient will only return FALSE if another // thread is cleaning up the specified tClient, or // if the pointer is really bad. // // So, we'll spin for a little while waiting to see // if the tClient gets removed from the list, & if // not assume that we're experiencing heap // corruption or some such, and manually shutdown. // for (i = 0; ptClient == TapiGlobals.ptClients && i < 10; i++) { Sleep (100); } if (i >= 10) { TapiEnterCriticalSection (&TapiGlobals.CritSec); if (TapiGlobals.dwNumLineInits || TapiGlobals.dwNumPhoneInits) { ServerShutdown (); } TapiLeaveCriticalSection (&TapiGlobals.CritSec); break; } } } } // // Tell the SPEventHandlerThread(s) to terminate // for (i = 0; i < gdwNumSPEventHandlerThreads; i++) { EnterCriticalSection (&aSPEventHandlerThreadInfo[i].CritSec); SetEvent (aSPEventHandlerThreadInfo[i].hEvent); LeaveCriticalSection (&aSPEventHandlerThreadInfo[i].CritSec); } // // Disable rundowns & wait for any active rundowns to complete // while (InterlockedExchange (&gRundownLock.lCookie, 1) == 1) { Sleep (50); } gRundownLock.bIgnoreRundowns = TRUE; InterlockedExchange (&gRundownLock.lCookie, 0); while (gRundownLock.lNumRundowns != 0) { Sleep (50); } #if TELE_SERVER // // Wait for the EventNotificationThread's to terminate, // then clean up the related resources // if ( (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && (gdwServiceInitFlags & SERVICE_INIT_EVENT_NOTIFICATION) ) { gEventNotificationThreadParams.bExit = TRUE; while (gEventNotificationThreadParams.dwNumThreads) { SetEvent (gEventNotificationThreadParams.hEvent); Sleep (100); } CloseHandle (gEventNotificationThreadParams.hEvent); ServerFree (gEventNotificationThreadParams.phThreads); ServerFree (gEventNotificationThreadParams.pWatchDogStruct); } if (gdwServiceInitFlags & SERVICE_INIT_MANAGEMENT_DLL) { CleanUpManagementMemory(); } #endif ServerFree (TapiGlobals.pszComputerName); // // Wait for the SPEVentHandlerThread(s) to terminate // while (glNumActiveSPEventHandlerThreads) { Sleep (100); } for (i = 0; i < gdwNumSPEventHandlerThreads; i++) { CloseHandle (aSPEventHandlerThreadInfo[i].hEvent); DeleteCriticalSection (&aSPEventHandlerThreadInfo[i].CritSec); } if (aSPEventHandlerThreadInfo != (&gSPEventHandlerThreadInfo)) { ServerFree (aSPEventHandlerThreadInfo); } // // Free up resources // if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_MGMT) DeleteCriticalSection (&gMgmtCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_GLOB_CRITSEC) TapiDeleteCriticalSection (&TapiGlobals.CritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_GLOB_REMOTESP) DeleteCriticalSection (&TapiGlobals.RemoteSPCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_CNCLIENTMSG) DeleteCriticalSection (&gCnClientMsgPendingCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_DGCLIENTMSG) DeleteCriticalSection (&gDgClientMsgPendingCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_SAFEMUTEX) DeleteCriticalSection (&gSafeMutexCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_REMOTECLI) DeleteCriticalSection (&gRemoteCliEventBufCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_PRILIST) DeleteCriticalSection (&gPriorityListCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_MGMTDLLS) DeleteCriticalSection (&gManagementDllsCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_DLLLIST) DeleteCriticalSection (&gDllListCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_SCP) DeleteCriticalSection (&gSCPCritSec); if (gdwServiceInitFlags & SERVICE_INIT_CRITSEC_CLIENTHND) DeleteCriticalSection (&gClientHandleCritSec); if (ghProvRegistryMutex) CloseHandle (ghProvRegistryMutex); // // Free ICON resources // if (TapiGlobals.hLineIcon) { DestroyIcon (TapiGlobals.hLineIcon); TapiGlobals.hLineIcon = NULL; } if (TapiGlobals.hPhoneIcon) { DestroyIcon (TapiGlobals.hPhoneIcon); TapiGlobals.hPhoneIcon = NULL; } if (gdwServiceInitFlags & SERVICE_INIT_LOCKTABLE) { for (i = 0; i < gdwNumLockTableEntries; i++) { DeleteCriticalSection (&gLockTable[i]); } if (gLockTable != gLockTableCritSecs) { ServerFree (gLockTable); } } if (TapiGlobals.pPriLists) { ServerFree(TapiGlobals.pPriLists); } if (ghHandleTable) { DeleteHandleTable (ghHandleTable); ghHandleTable = NULL; } if (ghTapisrvHeap != GetProcessHeap()) { HeapDestroy (ghTapisrvHeap); } if (ghEventService) { CloseHandle (ghEventService); ghEventService = NULL; } // // Report the stopped status to the service control manager. // if (NULL != ghSCMAutostartEvent) { CloseHandle (ghSCMAutostartEvent); } if (gdwServiceInitFlags & SERVICE_INIT_SCM_REGISTERED) { ReportStatusToSCMgr ((gdwServiceState = SERVICE_STOPPED), 0, 0, 0); } gdwServiceInitFlags = 0; // // When SERVICE MAIN FUNCTION returns in a single service // process, the StartServiceCtrlDispatcher function in // the main thread returns, terminating the process. // LOG((TL_TRACE, "ServiceMain: exit")); TRACELOGDEREGISTER(); return; } BOOL PASCAL QueueSPEvent( PSPEVENT pSPEvent ) { // // If there are multiple SPEventHandlerThread's running then make // sure to always queue events for a particular object to the same // SPEventHandlerThread so that we can preserve message ordering. // Without doing this call state messages might be received out of // order (or discarded altogether, if processed before a MakeCall // completion routine run, etc), etc. // BOOL bSetEvent; ULONG_PTR htXxx; PSPEVENTHANDLERTHREADINFO pInfo; switch (pSPEvent->dwType) { case SP_LINE_EVENT: case SP_PHONE_EVENT: htXxx = (ULONG_PTR)pSPEvent->htLine; break; case TASYNC_KEY: htXxx = ((PASYNCREQUESTINFO) pSPEvent)->htXxx; break; default: LOG((TL_ERROR, "QueueSPEvent: bad pSPEvent=x%p", pSPEvent)); #if DBG if (gfBreakOnSeriousProblems) { DebugBreak(); } #endif return FALSE; } pInfo = (gdwNumSPEventHandlerThreads > 1 ? aSPEventHandlerThreadInfo + MAP_HANDLE_TO_SP_EVENT_QUEUE_ID (htXxx) : aSPEventHandlerThreadInfo ); if (gbQueueSPEvents) { EnterCriticalSection (&pInfo->CritSec); bSetEvent = IsListEmpty (&pInfo->ListHead); InsertTailList (&pInfo->ListHead, &pSPEvent->ListEntry); LeaveCriticalSection (&pInfo->CritSec); if (bSetEvent) { SetEvent (pInfo->hEvent); } return TRUE; } return FALSE; } BOOL PASCAL DequeueSPEvent( PSPEVENTHANDLERTHREADINFO pInfo, PSPEVENT *ppSPEvent ) { BOOL bResult; LIST_ENTRY *pEntry; EnterCriticalSection (&pInfo->CritSec); if ((bResult = !IsListEmpty (&pInfo->ListHead))) { pEntry = RemoveHeadList (&pInfo->ListHead); *ppSPEvent = CONTAINING_RECORD (pEntry, SPEVENT, ListEntry); } if (IsListEmpty (&pInfo->ListHead)) { ResetEvent (pInfo->hEvent); } LeaveCriticalSection (&pInfo->CritSec); return bResult; } void SPEventHandlerThread( PSPEVENTHANDLERTHREADINFO pInfo ) { // // This thread processes the events & completion notifications // indicated to us by an SP at a previous time/thread context. // There are a couple of reasons for doing this in a separate // thread rather than within the SP's thread context: // // 1. for some msgs (i.e. XXX_CLOSE) TAPI will call back // into the SP, which it may not be expecting // // 2. we don't want to block the SP's thread by processing // the msg, forwarding it on to the appropriate clients, // etc // LOG((TL_INFO, "SPEventHandlerThread: enter (tid=%d)", GetCurrentThreadId() )); if (!SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL )) { LOG((TL_ERROR, "Could not raise priority of SPEventHandlerThread")); } while (1) { PSPEVENT pSPEvent; #if TELE_SERVER // // Timeout no more than gdwRpcTimeout to check on threads... // { #if DBG DWORD dwReturnValue; dwReturnValue = #endif WaitForSingleObject (pInfo->hEvent, gdwRpcTimeout); #if DBG if ( WAIT_TIMEOUT == dwReturnValue ) LOG((TL_INFO, "Timed out waiting for an sp event...")); else LOG((TL_INFO, "Found an sp event...")); #endif } #else WaitForSingleObject (pInfo->hEvent, INFINITE); #endif while (DequeueSPEvent (pInfo, &pSPEvent)) { switch (pSPEvent->dwType) { case SP_LINE_EVENT: LOG((TL_INFO, "Got a line spevent, htLine = 0x%x, htCall = 0x%x, dwMsg = 0x%x", pSPEvent->htLine,pSPEvent->htCall,pSPEvent->dwMsg)); LineEventProc( pSPEvent->htLine, pSPEvent->htCall, pSPEvent->dwMsg, pSPEvent->dwParam1, pSPEvent->dwParam2, pSPEvent->dwParam3 ); ServerFree (pSPEvent); break; case TASYNC_KEY: LOG((TL_INFO, "Got an async completion event, requestID = 0x%x, htXxx = 0x%x, lResult = 0x%x", ((PASYNCREQUESTINFO) pSPEvent)->dwLocalRequestID, ((PASYNCREQUESTINFO) pSPEvent)->htXxx, ((PASYNCREQUESTINFO) pSPEvent)->lResult)); CompletionProc( (PASYNCREQUESTINFO) pSPEvent, ((PASYNCREQUESTINFO) pSPEvent)->lResult ); DereferenceObject( ghHandleTable, ((PASYNCREQUESTINFO) pSPEvent)->dwLocalRequestID, 1 ); break; case SP_PHONE_EVENT: LOG((TL_INFO, "Got a phone spevent, htPhone = 0x%x, dwMsg = 0x%x", pSPEvent->htPhone,pSPEvent->dwMsg)); PhoneEventProc( pSPEvent->htPhone, pSPEvent->dwMsg, pSPEvent->dwParam1, pSPEvent->dwParam2, pSPEvent->dwParam3 ); ServerFree (pSPEvent); break; } } #if TELE_SERVER // // Check the remotesp event threads to make sure no // one is hung in an RPC call // if (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) { DWORD dwCount = gEventNotificationThreadParams.dwNumThreads; DWORD dwTickCount = GetTickCount(); DWORD dwStartCount, dwDiff; RPC_STATUS status; while (dwCount) { dwCount--; dwStartCount = gEventNotificationThreadParams. pWatchDogStruct[dwCount].dwTickCount; if ( gEventNotificationThreadParams. pWatchDogStruct[dwCount].ptClient && ( ( dwTickCount - dwStartCount ) > gdwRpcTimeout ) ) { // did it wrap? if ((((LONG)dwStartCount) < 0) && ((LONG)dwTickCount) > 0) { dwDiff = dwTickCount + (0 - ((LONG)dwStartCount)); if (dwDiff <= gdwRpcTimeout) { continue; } } // Kill the chicken! LOG((TL_INFO, "Calling RpcCancelThread on thread #%lx", gEventNotificationThreadParams.phThreads[dwCount] )); gEventNotificationThreadParams. pWatchDogStruct[dwCount].ptClient = NULL; status = RpcCancelThread( gEventNotificationThreadParams.phThreads[dwCount] ); } } } #endif if (gbSPEventHandlerThreadExit) { // // ServiceMain has stopped listening, so we want to exit NOW // break; } // // Check to see if all the clients are gone, and if so wait a // while to see if anyone else attaches. If no one else attaches // in the specified amount of time then shut down. // // don't quit if we're a server // // don't quit if we've not yet ever had anyone attach (like a service // that has a dependency on us, but has not yet done a lineInit) // // // don't quit if SCM didn't finish to start the automatic services; // there may be services that depend on us to start // if ( !gbAutostartDone && ghSCMAutostartEvent && WAIT_OBJECT_0 == WaitForSingleObject(ghSCMAutostartEvent, 0) ) { gbAutostartDone = TRUE; } if (TapiGlobals.ptClients == NULL && !(TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && gfWeHadAtLeastOneClient && gbAutostartDone) { DWORD dwDeferredShutdownTimeout, dwSleepInterval, dwLoopCount, i; RPC_STATUS status; HKEY hKey; dwDeferredShutdownTimeout = 120; // 120 seconds dwSleepInterval = 250; // 250 milliseconds if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_ALL_ACCESS, &hKey ) == ERROR_SUCCESS) { DWORD dwDataSize = sizeof (DWORD), dwDataType; if (RegQueryValueEx( hKey, TEXT("DeferredShutdownTimeout"), 0, &dwDataType, (LPBYTE) &dwDeferredShutdownTimeout, &dwDataSize ) == ERROR_SUCCESS ) { LOG((TL_ERROR, "Overriding Shutdown Timeout: %lu", dwDeferredShutdownTimeout )); } RegCloseKey (hKey); } dwLoopCount = dwDeferredShutdownTimeout * 1000 / dwSleepInterval; for (i = 0; i < dwLoopCount; i++) { if (gbSPEventHandlerThreadExit) { i = dwLoopCount; break; } Sleep (dwSleepInterval); if (TapiGlobals.ptClients != NULL) { break; } } if (i == dwLoopCount) { // // The 1st SPEVentHandlerThread instance is in charge of // tearing down the rpc server listen // if (pInfo == aSPEventHandlerThreadInfo) { ReportStatusToSCMgr( (gdwServiceState = SERVICE_STOP_PENDING), 0, (gdwCheckPoint = 0), gdwWaitHint ); LOG((TL_TRACE, "SPEventHandlerThread: calling RpcServerUnregisterIf")); RpcServerUnregisterIf (tapsrv_ServerIfHandle, NULL, TRUE); if (ghEventService) { SetEvent (ghEventService); } #if DBG DumpHandleList(); #endif } break; } } } InterlockedDecrement (&glNumActiveSPEventHandlerThreads); LOG((TL_TRACE, "SPEventHandlerThread: exit (pid=%d)", GetCurrentThreadId())); ExitThread (0); } DWORD InitSecurityDescriptor( PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID * ppSid, PACL * ppDacl ) { // // Note: this code was borrowed from Steve Cobb, who borrowed from RASMAN // DWORD dwResult; DWORD cbDaclSize; PULONG pSubAuthority; PSID pObjSid = NULL; PACL pDacl = NULL; SID_IDENTIFIER_AUTHORITY SidIdentifierWorldAuth = SECURITY_WORLD_SID_AUTHORITY; // // The do - while(FALSE) statement is used so that the break statement // maybe used insted of the goto statement, to execute a clean up and // and exit action. // do { dwResult = 0; // // Set up the SID for the admins that will be allowed to have // access. This SID will have 1 sub-authorities // SECURITY_BUILTIN_DOMAIN_RID. // if (!(pObjSid = (PSID) ServerAlloc (GetSidLengthRequired (1)))) { dwResult = GetLastError(); LOG((TL_ERROR, "GetSidLengthRequired() failed, err=%d", dwResult)); break; } if (!InitializeSid (pObjSid, &SidIdentifierWorldAuth, 1)) { dwResult = GetLastError(); LOG((TL_ERROR, "InitializeSid() failed, err=%d", dwResult)); break; } // // Set the sub-authorities // pSubAuthority = GetSidSubAuthority (pObjSid, 0); *pSubAuthority = SECURITY_WORLD_RID; // // Set up the DACL that will allow all processeswith the above // SID all access. It should be large enough to hold all ACEs. // cbDaclSize = sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid (pObjSid) + sizeof(ACL); if (!(pDacl = (PACL) ServerAlloc (cbDaclSize))) { dwResult = GetLastError (); break; } if (!InitializeAcl (pDacl, cbDaclSize, ACL_REVISION2)) { dwResult = GetLastError(); LOG((TL_ERROR, "InitializeAcl() failed, err=%d", dwResult)); break; } // // Add the ACE to the DACL // if (!AddAccessAllowedAce( pDacl, ACL_REVISION2, STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL, pObjSid )) { dwResult = GetLastError(); LOG((TL_ERROR, "AddAccessAllowedAce() failed, err=%d", dwResult)); break; } // // Create the security descriptor an put the DACL in it. // if (!InitializeSecurityDescriptor (pSecurityDescriptor, 1)) { dwResult = GetLastError(); LOG((TL_ERROR, "InitializeSecurityDescriptor() failed, err=%d", dwResult )); break; } if (!SetSecurityDescriptorDacl( pSecurityDescriptor, TRUE, pDacl, FALSE )) { dwResult = GetLastError(); LOG((TL_ERROR, "SetSecurityDescriptorDacl() failed, err=%d",dwResult)); break; } // // Set owner for the descriptor // if (!SetSecurityDescriptorOwner( pSecurityDescriptor, NULL, FALSE )) { dwResult = GetLastError(); LOG((TL_ERROR, "SetSecurityDescriptorOwnr() failed, err=%d",dwResult)); break; } // // Set group for the descriptor // if (!SetSecurityDescriptorGroup( pSecurityDescriptor, NULL, FALSE )) { dwResult = GetLastError(); LOG((TL_ERROR,"SetSecurityDescriptorGroup() failed, err=%d",dwResult)); break; } } while (FALSE); *ppSid = pObjSid; *ppDacl = pDacl; return dwResult; } void EventNotificationThread( LPVOID pParams ) { struct { HANDLE hMailslot; DWORD dwData; } *pBuf; DWORD dwID = PtrToUlong (pParams), dwBufSize = 512, dwTimeout = INFINITE; PTCLIENT ptClient; LIST_ENTRY *pEntry; LOG((TL_TRACE, "EventNotificationThread: enter")); if (!SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL )) { LOG((TL_ERROR, "Could not raise priority of EventNotificationThread")); } // // The following will make control return to the thread as soon // as RpcCancelThread() is called // if ( RpcMgmtSetCancelTimeout (0) != RPC_S_OK ) { LOG((TL_ERROR, "Could not set the RPC cancel timeout")); } pBuf = ServerAlloc (dwBufSize); if (!pBuf) { goto ExitHere; } while (1) { // // Wait for someone to tell us there's clients to notify // if (dwID == 0) { Sleep (DGCLIENT_TIMEOUT); walkDgClient_list: if (gEventNotificationThreadParams.bExit) { break; } // // Check to see if there are any connectionless clients // that we should notify. // if (!IsListEmpty (&DgClientMsgPendingListHead)) { DWORD i, j, dwTickCount, dwBytesWritten, dwNeededSize; // // Build a list of connectionless clients that we should // notify of pending events // // Note: the fact that we're in the critical section & the // tClient is in the list means that we can safely access // the tClient. // dwTickCount = GetTickCount(); EnterCriticalSection (&gDgClientMsgPendingCritSec); pEntry = DgClientMsgPendingListHead.Flink; for( i = 0, dwNeededSize = sizeof (*pBuf); pEntry != &DgClientMsgPendingListHead; dwNeededSize += sizeof (*pBuf) ) { do { ptClient = CONTAINING_RECORD( pEntry, TCLIENT, MsgPendingListEntry ); pEntry = pEntry->Flink; if ((ptClient->dwDgRetryTimeoutTickCount - dwTickCount) & 0x80000000) { // // Check the last time the client retrieved // events, & if it's been too long then nuke // them. // // Ideally, RPC should notify us of a // disconnected client via our rundown routine. // But we have seen in rstress that this is not // always the case (in fact, we wind up with 2 // or more active instances of the same client // machine!), and so we use this watchdog scheme // for backup. Otherwise, a stale client might // have lines open w/ owner or monitor privs // and it's event queue would grow & grow. // if ((dwTickCount - ptClient->dwDgEventsRetrievedTickCount) > gdwRpcTimeout) { LOG((TL_ERROR, "EventNotificationThread: timeout, " \ "cleaning up Dg client=x%p", ptClient )); LeaveCriticalSection( &gDgClientMsgPendingCritSec ); CleanUpClient (ptClient, FALSE); goto walkDgClient_list; } // // Grow the buffer if necessary // if (dwNeededSize > dwBufSize) { LPVOID p; if ((p = ServerAlloc (dwBufSize + 512))) { CopyMemory (p, pBuf, dwBufSize); ServerFree (pBuf); (LPVOID) pBuf = p; dwBufSize += 512; } else { pEntry = &DgClientMsgPendingListHead; break; } } ptClient->dwDgRetryTimeoutTickCount = dwTickCount + DGCLIENT_TIMEOUT; pBuf[i].hMailslot = ptClient->hValidEventBufferDataEvent; try { if (ptClient->ptLineApps) { pBuf[i].dwData = (DWORD) ptClient->ptLineApps->InitContext; } else { pBuf[i].dwData = 0; } } myexcept { pBuf[i].dwData = 0; } i++; break; } } while (pEntry != &DgClientMsgPendingListHead); } LeaveCriticalSection (&gDgClientMsgPendingCritSec); // // Notify those clients // for (j = 0; j < i; j++) { if (!WriteFile( pBuf[j].hMailslot, &pBuf[j].dwData, sizeof (DWORD), &dwBytesWritten, (LPOVERLAPPED) NULL )) { LOG((TL_ERROR, "EventNotificationThread: Writefile(mailslot) " \ "failed, err=%d", GetLastError() )); } } } continue; } else { WaitForSingleObject( gEventNotificationThreadParams.hEvent, INFINITE ); } if (gEventNotificationThreadParams.bExit) { break; } if (!IsListEmpty (&CnClientMsgPendingListHead)) { // // Try to find a remote client with pending messages that no // other EventNotificationThread is currently servicing. // If we find one, then mark it busy, remove it from the // list, & then break out of the loop. // // Note: the fact that we're in the critical section & the // tClient is in the list means that we can safely access // the tClient. // findCnClientMsgPending: EnterCriticalSection (&gCnClientMsgPendingCritSec); for( pEntry = CnClientMsgPendingListHead.Flink; pEntry != &CnClientMsgPendingListHead; pEntry = pEntry->Flink ) { ptClient = CONTAINING_RECORD( pEntry, TCLIENT, MsgPendingListEntry ); if (!ptClient->dwCnBusy) { ptClient->dwCnBusy = 1; RemoveEntryList (pEntry); ptClient->MsgPendingListEntry.Flink = ptClient->MsgPendingListEntry.Blink = NULL; break; } } LeaveCriticalSection (&gCnClientMsgPendingCritSec); // // If a remote client was found then copy all it's event // data over to our local buffer & send it off // if (pEntry != &CnClientMsgPendingListHead) { if (WaitForExclusiveClientAccess (ptClient)) { DWORD dwMoveSize, dwMoveSizeWrapped, dwRetryCount; PCONTEXT_HANDLE_TYPE2 phContext; // // We want to copy all the events in the tClient's // buffer to our local buffer in one shot, so see // if we need to grow our buffer first // if (ptClient->dwEventBufferUsedSize > dwBufSize) { LPVOID p; if (!(p = ServerAlloc( ptClient->dwEventBufferUsedSize ))) { UNLOCKTCLIENT (ptClient); break; } ServerFree (pBuf); (LPVOID) pBuf = p; dwBufSize = ptClient->dwEventBufferUsedSize; } if (ptClient->pDataOut < ptClient->pDataIn) { dwMoveSize = (DWORD) (ptClient->pDataIn - ptClient->pDataOut); dwMoveSizeWrapped = 0; } else { dwMoveSize = ptClient->dwEventBufferTotalSize - (DWORD) (ptClient->pDataOut - ptClient->pEventBuffer); dwMoveSizeWrapped = (DWORD) (ptClient->pDataIn - ptClient->pEventBuffer); } CopyMemory (pBuf, ptClient->pDataOut, dwMoveSize); if (dwMoveSizeWrapped) { CopyMemory( pBuf + dwMoveSize, ptClient->pEventBuffer, dwMoveSizeWrapped ); } ptClient->dwEventBufferUsedSize = 0; ptClient->pDataIn = ptClient->pDataOut = ptClient->pEventBuffer; phContext = ptClient->phContext; UNLOCKTCLIENT (ptClient); // // Set the watchdog entry for this thread indicating // what client we're talking to & when we started // gEventNotificationThreadParams.pWatchDogStruct[dwID]. dwTickCount = GetTickCount(); gEventNotificationThreadParams.pWatchDogStruct[dwID]. ptClient = ptClient; // // Send the data // dwRetryCount = gdwRpcRetryCount; while (dwRetryCount) { RpcTryExcept { RemoteSPEventProc( phContext, (unsigned char *) pBuf, dwMoveSize + dwMoveSizeWrapped ); dwRetryCount = 0; } RpcExcept (I_RpcExceptionFilter(RpcExceptionCode())) { unsigned long ulResult = RpcExceptionCode(); LOG((TL_ERROR, "EventNotificationThread: exception #%d", ulResult )); if ((ulResult == RPC_S_CALL_CANCELLED) || (ulResult == ERROR_INVALID_HANDLE)) { LOG((TL_ERROR, "EventNotificationThread: rpc timeout " \ "(ptClient=x%p)", ptClient )); // // The canceled because of a timeout. // Flag the context, so we don't try // to call it again! // CleanUpClient (ptClient, FALSE); // // When using TCP, or SPX, RPC will probably // toast the session context, so we'll not // be able to call to the client again. // // (If RpcCancelThread() is called and the // server ACKs within the time set int // RpcMgmtSetCancelTimeout(), RPC // (well, the underlying transport) _won't_ // kill the context, but how likely is that...) // dwRetryCount = 1; // so it'll go to 0 after -- } dwRetryCount--; } RpcEndExcept } gEventNotificationThreadParams.pWatchDogStruct[dwID]. ptClient = NULL; // // Safely reset the tClient.dwCnBusy flag // if (WaitForExclusiveClientAccess (ptClient)) { ptClient->dwCnBusy = 0; UNLOCKTCLIENT (ptClient); } } goto findCnClientMsgPending; } } dwTimeout = INFINITE; ResetEvent (gEventNotificationThreadParams.hEvent); } ExitHere: ServerFree (pBuf); CloseHandle (gEventNotificationThreadParams.phThreads[dwID]); InterlockedDecrement( (LPLONG) &gEventNotificationThreadParams.dwNumThreads ); LOG((TL_TRACE, "EventNotificationThread: exit")); ExitThread (0); } void __RPC_FAR * __RPC_API midl_user_allocate( size_t len ) { return (ServerAlloc(len)); } void __RPC_API midl_user_free( void __RPC_FAR * ptr ) { ServerFree (ptr); } #if TELE_SERVER // implement these functions! void ManagementAddLineProc( PTCLIENT ptClient, DWORD dwReserved ) { ASYNCEVENTMSG msg; // this should sent linedevstate_reinit message to remotesp msg.TotalSize = sizeof(msg); msg.InitContext = ptClient->ptLineApps->InitContext; msg.fnPostProcessProcHandle = 0; msg.hDevice = 0; msg.Msg = LINE_LINEDEVSTATE; msg.OpenContext = 0; msg.Param1 = LINEDEVSTATE_REINIT; msg.Param2 = RSP_MSG; msg.Param3 = 0; msg.Param4 = 0; WriteEventBuffer (ptClient, &msg); } void ManagementAddPhoneProc( PTCLIENT ptClient, DWORD dwReserved ) { ASYNCEVENTMSG msg; // this should sent linedevstate_reinit message to remotesp msg.TotalSize = sizeof(msg); msg.InitContext = ptClient->ptLineApps->InitContext; msg.fnPostProcessProcHandle = 0; msg.hDevice = 0; msg.Msg = LINE_LINEDEVSTATE; msg.OpenContext = 0; msg.Param1 = LINEDEVSTATE_REINIT; msg.Param2 = RSP_MSG; msg.Param3 = 0; msg.Param4 = 0; WriteEventBuffer (ptClient, &msg); } void CleanUpManagementMemory( ) { PTMANAGEDLLINFO pDll, pDllHold; PPERMANENTIDARRAYHEADER pIDArray, pArrayHold; if (!(TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) { return; } (TapiGlobals.pMapperDll->aProcs[TC_FREE])(); FreeLibrary(TapiGlobals.pMapperDll->hDll); ServerFree (TapiGlobals.pMapperDll->pszName); ServerFree (TapiGlobals.pMapperDll); TapiGlobals.pMapperDll = NULL; if (TapiGlobals.pManageDllList) { pDll = TapiGlobals.pManageDllList->pFirst; while (pDll) { (pDll->aProcs[TC_FREE])(); FreeLibrary (pDll->hDll); ServerFree (pDll->pszName); pDllHold = pDll->pNext; ServerFree (pDll); pDll = pDllHold; } ServerFree (TapiGlobals.pManageDllList); TapiGlobals.pManageDllList = NULL; } pIDArray = TapiGlobals.pIDArrays; while (pIDArray) { ServerFree (pIDArray->pLineElements); ServerFree (pIDArray->pPhoneElements); pArrayHold = pIDArray->pNext; ServerFree (pIDArray); pIDArray = pArrayHold; } } void GetProviderSortedArray( DWORD dwProviderID, PPERMANENTIDARRAYHEADER *ppArrayHeader ) { *ppArrayHeader = TapiGlobals.pIDArrays; // look for the provider in the list while (*ppArrayHeader) { if ((*ppArrayHeader)->dwPermanentProviderID == dwProviderID) { return; } *ppArrayHeader = (*ppArrayHeader)->pNext; } LOG((TL_ERROR, "Couldn't find Provider - id %d pIDArrays %p", dwProviderID, TapiGlobals.pIDArrays )); *ppArrayHeader = NULL; return; } BOOL GetLinePermanentIdFromDeviceID( PTCLIENT ptClient, DWORD dwDeviceID, LPTAPIPERMANENTID pID ) { LPDWORD pDevices = ptClient->pLineDevices; DWORD dwCount = ptClient->dwLineDevices; while (dwCount) { dwCount--; if (pDevices[dwCount] == dwDeviceID) { pID->dwProviderID = ptClient->pLineMap[dwCount].dwProviderID; pID->dwDeviceID = ptClient->pLineMap[dwCount].dwDeviceID; return TRUE; } } LOG((TL_INFO, "GetLinePermanentIdFromDeviceID failed for %d device", dwDeviceID )); return FALSE; } BOOL GetPhonePermanentIdFromDeviceID( PTCLIENT ptClient, DWORD dwDeviceID, LPTAPIPERMANENTID pID ) { LPDWORD pDevices = ptClient->pPhoneDevices; DWORD dwCount = ptClient->dwPhoneDevices; while (dwCount) { dwCount--; if (pDevices[dwCount] == dwDeviceID) { pID->dwProviderID = ptClient->pPhoneMap[dwCount].dwProviderID; pID->dwDeviceID = ptClient->pPhoneMap[dwCount].dwDeviceID; return TRUE; } } LOG((TL_INFO, "GetPhonePermanentIdFromDeviceID failed for %d device", dwDeviceID )); return FALSE; } DWORD GetDeviceIDFromPermanentID( TAPIPERMANENTID ID, BOOL bLine ) /*++ Gets the regulare tapi device ID from the permanent ID --*/ { PPERMANENTIDARRAYHEADER pArrayHeader; PPERMANENTIDELEMENT pArray; LONG lLow, lHigh, lMid; DWORD dwTotalElements; DWORD dwPermanentID; dwPermanentID = ID.dwDeviceID; // get the array corresponding to this provider ID GetProviderSortedArray (ID.dwProviderID, &pArrayHeader); if (!pArrayHeader) { LOG((TL_ERROR, "Couldn't find the provider in the permanent array list!")); return 0xFFFFFFFF; } // // Serialize access to the device array // while (InterlockedExchange (&pArrayHeader->lCookie, 1) == 1) { Sleep (10); } // set up stuff for search // dwCurrent is a total - subtract one to make it an index into array. if (bLine) { lHigh = (LONG)(pArrayHeader->dwCurrentLines - 1); pArray = pArrayHeader->pLineElements; dwTotalElements = pArrayHeader->dwNumLines; } else { lHigh = (LONG)(pArrayHeader->dwCurrentPhones - 1); pArray = pArrayHeader->pPhoneElements; dwTotalElements = pArrayHeader->dwNumPhones; } lLow = 0; // binary search through the provider's id array // this search is from a book, so it must be right. while (lHigh >= lLow) { lMid = (lHigh + lLow) / 2; if (dwPermanentID == pArray[lMid].dwPermanentID) { InterlockedExchange (&pArrayHeader->lCookie, 0); return pArray[lMid].dwDeviceID; } if (dwPermanentID < pArray[lMid].dwPermanentID) { lHigh = lMid-1; } else { lLow = lMid+1; } } InterlockedExchange (&pArrayHeader->lCookie, 0); return 0xFFFFFFFF; } void InsertIntoTable( BOOL bLine, DWORD dwDeviceID, PTPROVIDER ptProvider, DWORD dwPermanentID ) { PPERMANENTIDARRAYHEADER pArrayHeader; PPERMANENTIDELEMENT pArray; LONG lLow, lHigh, lMid; DWORD dwTotalElements, dwCurrentElements; GetProviderSortedArray (ptProvider->dwPermanentProviderID, &pArrayHeader); if (!pArrayHeader) { LOG((TL_ERROR, "Couldn't find the provider in the permanent array list!")); return; } // // Serialize access to the device array // while (InterlockedExchange (&pArrayHeader->lCookie, 1) == 1) { Sleep (10); } // // set up stuff for search // dwCurrent is a total - subtract one to make it an index into array. // if (bLine) { dwCurrentElements = pArrayHeader->dwCurrentLines; pArray = pArrayHeader->pLineElements; dwTotalElements = pArrayHeader->dwNumLines; } else { dwCurrentElements = pArrayHeader->dwCurrentPhones; pArray = pArrayHeader->pPhoneElements; dwTotalElements = pArrayHeader->dwNumPhones; } lLow = 0; lHigh = dwCurrentElements-1; // binary search if (dwCurrentElements > 0) { while (TRUE) { lMid = ( lHigh + lLow ) / 2 + ( lHigh + lLow ) % 2; if (lHigh < lLow) { break; } if (pArray[lMid].dwPermanentID == dwPermanentID) { LOG((TL_ERROR, "Trying to insert an item already in the perm ID array" )); LOG((TL_ERROR, "Provider %s, %s array, ID 0x%lu", ptProvider->szFileName, (bLine ? "Line" : "Phone"), dwPermanentID )); } if (pArray[lMid].dwPermanentID > dwPermanentID) { lHigh = lMid-1; } else { lLow = lMid+1; } } } // // Grow the table if necessary // if (dwCurrentElements >= dwTotalElements) { PPERMANENTIDELEMENT pNewArray; // realloc array by doubling it if (!(pNewArray = ServerAlloc( dwTotalElements * 2 * sizeof(PERMANENTIDELEMENT) ))) { InterlockedExchange (&pArrayHeader->lCookie, 0); return; } // copy old stuff over CopyMemory( pNewArray, pArray, dwTotalElements * sizeof(PERMANENTIDELEMENT) ); // free old array ServerFree (pArray); // save new array if (bLine) { pArrayHeader->dwNumLines = dwTotalElements * 2; pArray = pArrayHeader->pLineElements = pNewArray; } else { pArrayHeader->dwNumPhones = dwTotalElements * 2; pArray = pArrayHeader->pPhoneElements = pNewArray; } } // dwCurrentElements is a count (1 based), lLow is an index (0 based) // if lLow is < dwcurrent, then it's getting inserted somewhere in the // middle of the array, so scootch all the other elements out. if (lLow < (LONG)dwCurrentElements) { MoveMemory( &(pArray[lLow+1]), &(pArray[lLow]), sizeof(PERMANENTIDELEMENT) * (dwCurrentElements - lLow) ); } if (lLow > (LONG)dwCurrentElements) { LOG((TL_INFO, "InsertIntoTable: lLow %d > dwCurrentElements %d", lLow, dwCurrentElements )); } pArray[lLow].dwPermanentID = dwPermanentID; pArray[lLow].dwDeviceID = dwDeviceID; if (bLine) { pArrayHeader->dwCurrentLines++; } else { pArrayHeader->dwCurrentPhones++; } InterlockedExchange (&pArrayHeader->lCookie, 0); } void FreeDll( PTMANAGEDLLINFO pDll ) { } LONG AddProviderToIdArrayList( PTPROVIDER ptProvider, DWORD dwNumLines, DWORD dwNumPhones ) /*++ Adds a new provider corresponding array to the list of permanent device ID arrays --*/ { PPERMANENTIDARRAYHEADER pNewArray; // // Alloc a header & arrays for this provider (make sure at least // 1 entry in each array) // if (!(pNewArray = ServerAlloc(sizeof(PERMANENTIDARRAYHEADER)))) { return LINEERR_NOMEM; } dwNumLines = (dwNumLines ? dwNumLines : 1); dwNumPhones = (dwNumPhones ? dwNumPhones : 1); pNewArray->pLineElements = ServerAlloc( sizeof(PERMANENTIDELEMENT) * dwNumLines ); pNewArray->pPhoneElements = ServerAlloc( sizeof(PERMANENTIDELEMENT) * dwNumPhones ); if ((!pNewArray->pLineElements) || (!pNewArray->pPhoneElements)) { ServerFree (pNewArray->pLineElements); ServerFree (pNewArray->pPhoneElements); ServerFree (pNewArray); return LINEERR_NOMEM; } // // Initialize elements // pNewArray->dwNumLines = dwNumLines; pNewArray->dwNumPhones = dwNumPhones; pNewArray->dwCurrentLines = 0; pNewArray->dwCurrentPhones = 0; pNewArray->dwPermanentProviderID = ptProvider->dwPermanentProviderID; // // Insert at the beginning of the list // pNewArray->pNext = TapiGlobals.pIDArrays; TapiGlobals.pIDArrays = pNewArray; return 0; } LONG GetDeviceAccess( PTMANAGEDLLINFO pDll, PTCLIENT ptClient, HMANAGEMENTCLIENT hClient ) /*++ Calls the mapper DLL to get the access map arrays for a client --*/ { LONG lResult; DWORD dwLineDevs, dwPhoneDevs, dwCount; DWORD dwNumLinesHold, dwNumPhonesHold, dwRealDevs; LPTAPIPERMANENTID pLineMap = NULL, pPhoneMap = NULL; #define DEFAULTACCESSDEVS 3 dwLineDevs = DEFAULTACCESSDEVS; dwPhoneDevs = DEFAULTACCESSDEVS; // alloc an default array size if (!(pLineMap = ServerAlloc (dwLineDevs * sizeof (TAPIPERMANENTID)))) { goto GetDeviceAccess_MemoryError; } if (!(pPhoneMap = ServerAlloc (dwPhoneDevs * sizeof (TAPIPERMANENTID)))) { goto GetDeviceAccess_MemoryError; } // call the mapper dll // LOG((TL_INFO, "Calling GetDeviceAccess in mapper DLL")); while (TRUE) { dwNumLinesHold = dwLineDevs; dwNumPhonesHold = dwPhoneDevs; lResult = (pDll->aProcs[TC_GETDEVICEACCESS])( hClient, ptClient, pLineMap, &dwLineDevs, pPhoneMap, &dwPhoneDevs ); if (lResult == LINEERR_STRUCTURETOOSMALL) { if (dwLineDevs < dwNumLinesHold) { LOG((TL_ERROR, "Returned STRUCTURETOOSMALL, but specified less " \ "line devs in TAPICLINET_GETDEVICEACCESS" )); } if (dwPhoneDevs < dwNumPhonesHold) { LOG((TL_ERROR, "Returned STRUCTURETOOSMALL, but specified less " \ "phone devs in TAPICLINET_GETDEVICEACCESS" )); } // realloc ServerFree (pLineMap); if (!(pLineMap = ServerAlloc( dwLineDevs * sizeof (TAPIPERMANENTID) ))) { goto GetDeviceAccess_MemoryError; } ServerFree (pPhoneMap); if (!(pPhoneMap = ServerAlloc( dwPhoneDevs * sizeof ( TAPIPERMANENTID) ))) { goto GetDeviceAccess_MemoryError; } } else { break; } } // if still an error if (lResult) { LOG((TL_ERROR, "GetDeviceAccess failed - error %lu", lResult)); ServerFree (pLineMap); ServerFree (pPhoneMap); return lResult; } if (dwLineDevs > dwNumLinesHold) { LOG((TL_ERROR, "Returned dwLineDevs greater that the buffer specified in TAPICLIENT_GETDEVICEACCESS")); LOG((TL_ERROR, " Will only use the number the buffer can hold")); dwLineDevs = dwNumLinesHold; } if (dwPhoneDevs > dwNumPhonesHold) { LOG((TL_ERROR, "Returned dwPhoneDevs greater that the buffer specified in TAPICLIENT_GETDEVICEACCESS")); LOG((TL_ERROR, " Will only use the number the buffer can hold")); dwPhoneDevs = dwNumPhonesHold; } // alloc another array for regular tapi device IDs if (!(ptClient->pLineDevices = ServerAlloc( dwLineDevs * sizeof (DWORD) ) ) ) { goto GetDeviceAccess_MemoryError; } // alloc a permanent ID array if (!(ptClient->pLineMap = ServerAlloc( dwLineDevs * sizeof (TAPIPERMANENTID) ) ) ) { goto GetDeviceAccess_MemoryError; } // loop through all the mapped elements and get the regular // tapi device ID dwRealDevs = 0; for (dwCount = 0; dwCount < dwLineDevs; dwCount++) { DWORD dwID; dwID = GetDeviceIDFromPermanentID( pLineMap[dwCount], TRUE ); // make sure it's a good id if ( dwID != 0xffffffff ) { // save it ptClient->pLineDevices[dwRealDevs] = dwID; ptClient->pLineMap[dwRealDevs].dwProviderID = pLineMap[dwCount].dwProviderID; ptClient->pLineMap[dwRealDevs].dwDeviceID = pLineMap[dwCount].dwDeviceID; // inc real devs dwRealDevs++; } } // save the real number of devices ptClient->dwLineDevices = dwRealDevs; // free the line map ServerFree (pLineMap); // now do phone devices if (!(ptClient->pPhoneDevices = ServerAlloc( dwPhoneDevs * sizeof (DWORD) ) ) ) { goto GetDeviceAccess_MemoryError; } if (!(ptClient->pPhoneMap = ServerAlloc( dwPhoneDevs * sizeof (TAPIPERMANENTID) ) ) ) { goto GetDeviceAccess_MemoryError; } dwRealDevs = 0; for (dwCount = 0; dwCount < dwPhoneDevs; dwCount++) { DWORD dwID; dwID = GetDeviceIDFromPermanentID( pPhoneMap[dwCount], FALSE ); if ( 0xffffffff != dwID ) { ptClient->pPhoneDevices[dwRealDevs] = dwID; ptClient->pPhoneMap[dwRealDevs].dwProviderID = pPhoneMap[dwCount].dwProviderID; ptClient->pPhoneMap[dwRealDevs].dwDeviceID = pPhoneMap[dwCount].dwDeviceID; dwRealDevs++; } } // save the real number of devices ptClient->dwPhoneDevices = dwRealDevs; // free the original map ServerFree (pPhoneMap); return 0; GetDeviceAccess_MemoryError: if (pLineMap != NULL) ServerFree (pLineMap); if (pPhoneMap != NULL) ServerFree (pPhoneMap); if (ptClient->pLineMap != NULL) ServerFree (ptClient->pLineMap); if (ptClient->pPhoneMap != NULL) ServerFree (ptClient->pPhoneMap); return LINEERR_NOMEM; } LONG InitializeClient( PTCLIENT ptClient ) { PTMANAGEDLLINFO pDll; PTMANAGEDLLLISTHEADER pDllList; PTCLIENTHANDLE pClientHandle = NULL; LONG lResult = 0; if (!(TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) || IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { return 0; } // call the mapper DLL pDll = TapiGlobals.pMapperDll; lResult = (pDll->aProcs[TC_CLIENTINITIALIZE])( ptClient->pszDomainName, ptClient->pszUserName, ptClient->pszComputerName, &ptClient->hMapper ); if (lResult != 0) { // error on init LOG((TL_ERROR, "ClientInitialize internal failure - error %lu", lResult)); //LOG((TL_ERROR, "Disabling the Telephony server! (2)")); //TapiGlobals.bServer = FALSE; //CleanUpManagementMemory(); return lResult; } if (lResult = GetDeviceAccess( pDll, ptClient, ptClient->hMapper )) { LOG((TL_ERROR, "GetDeviceAccess failed - error x%lx", lResult)); //LOG((TL_ERROR, "Disabling the Telephony server! (3)")); //TapiGlobals.bServer = FALSE; //CleanUpManagementMemory(); return lResult; } // get the manage dll list GetManageDllListPointer(&pDllList); if (pDllList && (pDll = pDllList->pFirst)) { if (!(pClientHandle = ServerAlloc(sizeof(TCLIENTHANDLE)))) { lResult = LINEERR_NOMEM; goto clientinit_exit; } ptClient->pClientHandles = pClientHandle; while (pDll) { // walk the list and call init for this client pClientHandle->dwID = pDll->dwID; pClientHandle->fValid = TRUE; // call init if (lResult = (pDll->aProcs[TC_CLIENTINITIALIZE])( ptClient->pszDomainName, ptClient->pszUserName, ptClient->pszComputerName, &pClientHandle->hClient )) { // failed client init LOG((TL_ERROR, "ClientInitialize failed for %ls, result x%lx", pDll->pszName, lResult)); pClientHandle->fValid = FALSE; } lResult = 0; // if there's another DLL, setup another structure if (pDll = pDll->pNext) { if (!(pClientHandle->pNext = ServerAlloc(sizeof(TCLIENTHANDLE)))) { lResult = LINEERR_NOMEM; goto clientinit_exit; } pClientHandle = pClientHandle->pNext; } } } clientinit_exit: FreeManageDllListPointer(pDllList); return lResult; } #endif BOOL ValidClientAttachParams( long lProcessID, wchar_t *pszDomainUser, wchar_t *pszMachineIn ) { wchar_t * pBinding; wchar_t * pPlaceHolder; wchar_t * pProtocolSequence; int idxPair; if (NULL == pszDomainUser || NULL == pszMachineIn) { return FALSE; } if (lProcessID == 0xffffffff) { // This is a remote client // pszMachineIn should have the format: // machinename"binding0"endpoint0" ... bindingN"endpointN" (new style) or // machinename"binding"endpoint (old style) pPlaceHolder = wcschr( pszMachineIn, L'\"' ); if (NULL == pPlaceHolder || pPlaceHolder == pszMachineIn) { return FALSE; } // validate binding/endpoint pairs idxPair = 0; do { idxPair++; pBinding = pPlaceHolder + 1; pPlaceHolder = wcschr( pBinding, L'\"' ); if (NULL == pPlaceHolder || pPlaceHolder == pBinding) { return FALSE; } pProtocolSequence = pPlaceHolder + 1; pPlaceHolder = wcschr( pProtocolSequence, L'\"' ); if (NULL == pPlaceHolder) { if (idxPair >1) { return FALSE; } } else { if (pPlaceHolder == pProtocolSequence) { return FALSE; } if (*(pPlaceHolder + 1) == '\0') { pPlaceHolder = NULL; } } } while (NULL != pPlaceHolder); } return TRUE; } LONG ClientAttach( PCONTEXT_HANDLE_TYPE *pphContext, long lProcessID, long *phAsyncEventsEvent, wchar_t *pszDomainUser, wchar_t *pszMachineIn ) { PTCLIENT ptClient; wchar_t *pszMachine; wchar_t *pProtocolSequence; wchar_t *pProtocolEndpoint; wchar_t *pPlaceHolder; LONG lResult = 0; #define NAMEBUFSIZE 96 WCHAR szAccountName[NAMEBUFSIZE], szDomainName[NAMEBUFSIZE]; DWORD dwInfoBufferSize, dwSize, dwAccountNameSize = NAMEBUFSIZE *sizeof(WCHAR), dwDomainNameSize = NAMEBUFSIZE *sizeof(WCHAR); HANDLE hThread, hAccessToken; LPWSTR InfoBuffer = NULL; PSID psidAdministrators; SID_IDENTIFIER_AUTHORITY siaNtAuthority = SECURITY_NT_AUTHORITY; UINT x; PTOKEN_USER ptuUser; SID_NAME_USE use; RPC_STATUS status; DWORD dwException = 0; #if TELE_SERVER RPC_CALL_ATTRIBUTES RPCAttributes; #endif if (!ValidClientAttachParams(lProcessID, pszDomainUser, pszMachineIn)) { lResult = LINEERR_INVALPARAM; goto ClientAttach_error0; } LOG((TL_TRACE, "ClientAttach: enter, pid=x%x, user='%ls', machine='%ls'", lProcessID, pszDomainUser, pszMachineIn )); // // The new remotesp will send in pszMachine thus: // machinename"binding0"endpoint0" ... bindingN"endpointN" // pszMachine = pszMachineIn; if ( pPlaceHolder = wcschr( pszMachineIn, L'\"' ) ) { *pPlaceHolder = L'\0'; pProtocolSequence = pPlaceHolder + 1; } // // Alloc & init a tClient struct // if (!(ptClient = ServerAlloc (sizeof(TCLIENT)))) { goto ClientAttach_error0; } ptClient->htClient = NewObject( ghHandleTable, ptClient, NULL); if (ptClient->htClient == 0) { ServerFree(ptClient); goto ClientAttach_error0; } if (!(ptClient->pEventBuffer = ServerAlloc( INITIAL_EVENT_BUFFER_SIZE ))) { goto ClientAttach_error1; } ptClient->dwEventBufferTotalSize = INITIAL_EVENT_BUFFER_SIZE; ptClient->dwEventBufferUsedSize = 0; ptClient->pDataIn = ptClient->pDataOut = ptClient->pEventBuffer; ptClient->pClientHandles = NULL; #if TELE_SERVER // // If an authorized user did a NET PAUSE TAPISRV, don't allow new // remote clients. // if ( TapiGlobals.dwFlags & TAPIGLOBALS_PAUSED ) { if ((lProcessID == 0xffffffff) || (lProcessID == 0xfffffffd)) { LOG((TL_ERROR, "A client tried to attach, but TAPISRV is PAUSED")); goto Admin_error; } } if ((status = RpcImpersonateClient (0)) != RPC_S_OK) { LOG((TL_ERROR, "ClientAttach: RpcImpersonateClient failed, err=%d", status )); goto Admin_error; } hThread = GetCurrentThread(); // Note: no need to close this handle if (!OpenThreadToken (hThread, TOKEN_READ, FALSE, &hAccessToken)) { LOG((TL_ERROR, "ClientAttach: OpenThreadToken failed, err=%d", GetLastError() )); RpcRevertToSelf(); goto Admin_error; } dwSize = 2048; alloc_infobuffer: dwInfoBufferSize = 0; if (!(InfoBuffer = (LPWSTR) ServerAlloc (dwSize))) { CloseHandle (hAccessToken); RpcRevertToSelf(); goto ClientAttach_error2; } // first get the user name and domain name ptuUser = (PTOKEN_USER) InfoBuffer; if (!GetTokenInformation( hAccessToken, TokenUser, InfoBuffer, dwSize, &dwInfoBufferSize )) { LOG((TL_ERROR, "ClientAttach: GetTokenInformation failed, err=%d", GetLastError() )); ServerFree (InfoBuffer); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { dwSize *= 2; goto alloc_infobuffer; } CloseHandle (hAccessToken); RpcRevertToSelf(); goto Admin_error; } if (!LookupAccountSidW( NULL, ptuUser->User.Sid, szAccountName, &dwAccountNameSize, szDomainName, &dwDomainNameSize, &use )) { LOG((TL_ERROR, "ClientAttach: LookupAccountSidW failed, err=%d", GetLastError() )); ServerFree (InfoBuffer); CloseHandle (hAccessToken); RpcRevertToSelf(); goto Admin_error; } LOG((TL_INFO, "ClientAttach: LookupAccountSidW: User name %ls Domain name %ls", szAccountName, szDomainName )); // // Get administrator status // if (AllocateAndInitializeSid( &siaNtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &psidAdministrators ) ) { BOOL bAdmin = FALSE; RESET_FLAG(ptClient->dwFlags,PTCLIENT_FLAG_ADMINISTRATOR); if (!CheckTokenMembership( hAccessToken, psidAdministrators, &bAdmin )) { LOG((TL_ERROR, "ClientAttach: CheckTokenMembership failed, err=%d", GetLastError() )); } // // If both the client & server machine has blank // password for local administrator account, and if // remotesp runs in local admin account on remote machine // NTLM will actually think RPC request is from // server_machine\administrator, thus falsely set // bAdmin to be true. // if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && bAdmin && lProcessID == 0xffffffff) { WCHAR szLocalComp[NAMEBUFSIZE]; dwSize = sizeof(szLocalComp) / sizeof(WCHAR); if (GetComputerNameW ( szLocalComp, &dwSize ) && _wcsicmp (szLocalComp, szDomainName) == 0 ) { bAdmin = FALSE; wcsncpy ( szDomainName, pszMachine, sizeof(szLocalComp) / sizeof(WCHAR) ); szDomainName[sizeof(szLocalComp) / sizeof(WCHAR) - 1] = 0; } } if (bAdmin || S_OK == IsLocalSystem(hAccessToken)) { SET_FLAG(ptClient->dwFlags,PTCLIENT_FLAG_ADMINISTRATOR); } FreeSid (psidAdministrators); if (gbNTServer && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { // // Check to see if client is a TAPI admin, as // specified in the TAPI MMC Snapin. This is // determined simply by looking for a // <Domain>\<User>=1 value under the TapiAdministrators // section in tsec.ini. // wcscpy ((WCHAR *) InfoBuffer, szDomainName); wcscat ((WCHAR *) InfoBuffer, L"\\"); wcscat ((WCHAR *) InfoBuffer, szAccountName); if (GetPrivateProfileIntW( gszTapiAdministrators, (LPCWSTR) InfoBuffer, 0, gszFileName ) == 1) { SET_FLAG(ptClient->dwFlags,PTCLIENT_FLAG_ADMINISTRATOR); } } } else { LOG((TL_ERROR, "ClientAttach: AllocateAndInitializeSid failed, err=%d", GetLastError() )); ServerFree (InfoBuffer); CloseHandle (hAccessToken); RpcRevertToSelf(); goto Admin_error; } ServerFree (InfoBuffer); CloseHandle (hAccessToken); RpcRevertToSelf(); // // Save the user, domain, & machine names // ptClient->dwUserNameSize = (lstrlenW (szAccountName) + 1) * sizeof (WCHAR); if (!(ptClient->pszUserName = ServerAlloc (ptClient->dwUserNameSize))) { goto ClientAttach_error2; } wcscpy (ptClient->pszUserName, szAccountName); if (!(ptClient->pszDomainName = ServerAlloc( (lstrlenW (szDomainName) + 1) * sizeof(WCHAR) ))) { goto ClientAttach_error3; } wcscpy (ptClient->pszDomainName, szDomainName); if ((lProcessID == 0xffffffff) || (lProcessID == 0xfffffffd)) { ptClient->dwComputerNameSize = (1 + lstrlenW (pszMachine)) * sizeof(WCHAR); if (!(ptClient->pszComputerName = ServerAlloc( ptClient->dwComputerNameSize ))) { goto ClientAttach_error4; } wcscpy (ptClient->pszComputerName, pszMachine); } // Get the RPC call attributes ZeroMemory(&RPCAttributes, sizeof(RPCAttributes)); RPCAttributes.Version = RPC_CALL_ATTRIBUTES_VERSION; RPCAttributes.Flags = 0; status = RpcServerInqCallAttributes (NULL, &RPCAttributes); if (status) { LOG((TL_ERROR, "ClientAttach: Failed to retrieve the RPC call attributes, error 0x%x", status)); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } LOG((TL_INFO, "ClientAttach(%S): Auth level = 0x%x", ptClient->pszUserName, RPCAttributes.AuthenticationLevel)); #else ptClient->dwUserNameSize = (lstrlenW (pszDomainUser) + 1) * sizeof(WCHAR); if (!(ptClient->pszUserName = ServerAlloc (ptClient->dwUserNameSize))) { goto ClientAttach_error2; } wcscpy (ptClient->pszUserName, pszDomainUser); #endif if (lProcessID == 0xffffffff) { #if TELE_SERVER ULONG RPCAuthLevel = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; #endif // // This is a remote client // #if TELE_SERVER if (0 == (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) #endif { // // This machine has been set up to _not_ be a server so fail // ServerFree (ptClient->pszUserName); LOG((TL_ERROR, "ClientAttach: attach request received, but this is " \ "not a telephony svr!" )); goto Admin_error; } #if TELE_SERVER if (RPCAttributes.AuthenticationLevel != RPC_C_AUTHN_LEVEL_PKT_PRIVACY) { // Is this call secure enough ? if (gbHighSecurity) { // We are in high security mode // Reject calls that don't have packet privacy LOG((TL_ERROR, "ClientAttach: unsecure call, AuthLevel=0x%x", RPCAttributes.AuthenticationLevel)); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } else { RPCAuthLevel = RPC_C_AUTHN_LEVEL_DEFAULT; } } // // Special hack introduced because in SP4 beta I nullified the // entry in gaFuncs[] corresponding to the old-lOpenInt / // new-xNegotiateAPIVersionForAllDevices. So if a newer // remotesp tries to send a NegoAllDevices request to an // SP4 beta then tapisrv on the server will blow up. // // By setting *phAsyncEventsEvent = to a secret value remotesp // knows whether or not it's ok to send a NegoAllDevices request. // *phAsyncEventsEvent = 0xa5c369a5; // // If pszDomainUser is non-empty then it contains the // name of a mailslot that we can open & write to to // indicate when async events are pending for this client. // if (wcslen (pszDomainUser) > 0) { ptClient->hProcess = (HANDLE) DG_CLIENT; if ((ptClient->hMailslot = CreateFileW( pszDomainUser, GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL )) != INVALID_HANDLE_VALUE) { goto ClientAttach_AddClientToList; } LOG((TL_ERROR, "ClientAttach: CreateFile(%ws) failed, err=%d", pszDomainUser, GetLastError() )); LOG((TL_ERROR, "ClientAttach: trying connection-oriented approach...", pszDomainUser, GetLastError() )); } ptClient->hProcess = (HANDLE) CN_CLIENT; // // // { RPC_STATUS status; PCONTEXT_HANDLE_TYPE2 phContext = NULL; WCHAR *pszStringBinding = NULL; WCHAR *pszMachineName; BOOL bError; // Allocate enough incase we have to prepend... pszMachineName = ServerAlloc( (lstrlenW(pszMachine) + 3) * sizeof(WCHAR) ); if (!pszMachineName) { goto ClientAttach_error5; } // // Should we prepend whackwhack? // if (!_wcsicmp (L"ncacn_np", pProtocolSequence)) { // // Yes. It's needed for named pipes // pszMachineName[0] = '\\'; pszMachineName[1] = '\\'; wcscpy (pszMachineName + 2, pszMachine); } else { // // Don't prepend \\ // wcscpy (pszMachineName, pszMachine); } // // Serialize access to hRemoteSP // EnterCriticalSection (&TapiGlobals.RemoteSPCritSec); // // Try to find a protseq/endpoint pair in the list passed // to us by the client that works ok // find_protocol_sequence: do { // // New strings look like: prot1"ep1"prot2"ep2"\0 // ...where there's one or more protseq/enpoint combos, // each members of which is followed by a dbl-quote char // // Old strings look like: prot"ep\0 // ...where there's only one protseq/endpoint combo, // and the endpoint member is followed by a \0 (no dbl-quote) // pPlaceHolder = wcschr (pProtocolSequence, L'\"'); *pPlaceHolder = L'\0'; pProtocolEndpoint = pPlaceHolder + 1; if ((pPlaceHolder = wcschr (pProtocolEndpoint, L'\"'))) { *pPlaceHolder = L'\0'; } else { // // If this is an old-style string then munge // pPlaceHolder such that the error handling // code down below doesn't jump back up here // to get the next protseq/endpoint combo // pPlaceHolder = pProtocolEndpoint + wcslen (pProtocolEndpoint) - 1; } RpcTryExcept { status = RpcStringBindingComposeW( NULL, // uuid pProtocolSequence, pszMachineName, // server name pProtocolEndpoint, NULL, // options &pszStringBinding ); if (status != 0) { LOG((TL_ERROR, "ClientAttach: RpcStringBindingComposeW " \ "failed, err=%d", status )); } status = RpcBindingFromStringBindingW( pszStringBinding, &hRemoteSP ); if (status != 0) { LOG((TL_ERROR, "ClientAttach: RpcBindingFromStringBinding " \ "failed, err=%d", status )); LOG((TL_INFO, "\t szMachine=%ws, protseq=%ws endpoint=%ws", pszMachine, pProtocolSequence, pProtocolEndpoint )); } } RpcExcept (I_RpcExceptionFilter(RpcExceptionCode())) { // // Set status != 0 so our error handler below executes // status = 1; } RpcEndExcept if (status != 0) { RpcStringFreeW (&pszStringBinding); pProtocolSequence = pPlaceHolder + 1; } } while (status != 0 && *pProtocolSequence); if (status != 0) { LOG((TL_ERROR, "ClientAttach: error, can't find a usable protseq" )); LeaveCriticalSection (&TapiGlobals.RemoteSPCritSec); ServerFree (pszMachineName); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } LOG((TL_TRACE, "ClientAttach: szMachine=%ws trying protseq=%ws endpoint=%ws", pszMachine, pProtocolSequence, pProtocolEndpoint )); RpcTryExcept { status = RpcBindingSetAuthInfo( hRemoteSP, NULL, RPCAuthLevel, RPC_C_AUTHN_WINNT, NULL, 0 ); RemoteSPAttach ((PCONTEXT_HANDLE_TYPE2 *) &phContext); bError = FALSE; } RpcExcept (I_RpcExceptionFilter(RpcExceptionCode())) { dwException = RpcExceptionCode(); LOG((TL_ERROR, "ClientAttach: RemoteSPAttach failed. Exception %d", dwException )); bError = TRUE; } RpcEndExcept RpcTryExcept { RpcBindingFree (&hRemoteSP); RpcStringFreeW (&pszStringBinding); } RpcExcept (I_RpcExceptionFilter(RpcExceptionCode())) { // do nothing } RpcEndExcept LeaveCriticalSection (&TapiGlobals.RemoteSPCritSec); if (bError) { // // If there's at least one other protocol we can try // then go for it, otherwise jump to error handler // pProtocolSequence = pPlaceHolder + 1; if (*pProtocolSequence) { EnterCriticalSection (&TapiGlobals.RemoteSPCritSec); goto find_protocol_sequence; } ServerFree (pszMachineName); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } ServerFree (pszMachineName); // RevertToSelf(); ptClient->phContext = phContext; } #endif // TELE_SERVER } else if (lProcessID == 0xfffffffd) { if (!gbNTServer) { lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } #if TELE_SERVER // Is this call secure enough ? if (gbHighSecurity && RPCAttributes.AuthenticationLevel != RPC_C_AUTHN_LEVEL_PKT_PRIVACY) { // We are in high security mode // Reject calls that don't have packet privacy LOG((TL_ERROR, "ClientAttach: unsecure call, AuthLevel=0x%x", RPCAttributes.AuthenticationLevel)); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } #endif // // Deny the access if not the admin // if (!IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { lResult = TAPIERR_NOTADMIN; goto ClientAttach_error5; } ptClient->hProcess = (HANDLE) MMC_CLIENT; #ifdef _WIN64 *phAsyncEventsEvent = 0x64646464; #else *phAsyncEventsEvent = 0x32323232; #endif } else { RPC_STATUS rpcStatus; // // Open a handle to the client process. We will use this to duplicate an // event handle into that process. // rpcStatus = RpcImpersonateClient (NULL); if (RPC_S_OK != rpcStatus) { LOG((TL_ERROR, "RpcImpersonateClient failed, err=%d", rpcStatus)); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } if (!(ptClient->hProcess = OpenProcess( PROCESS_DUP_HANDLE, FALSE, lProcessID ))) { LOG((TL_ERROR, "OpenProcess(pid=x%x) failed, err=%d", lProcessID, GetLastError() )); RpcRevertToSelf (); goto ClientAttach_error5; } // // This is a local client, so set up all the event buffer stuff // ptClient->dwComputerNameSize = TapiGlobals.dwComputerNameSize; ptClient->pszComputerName = TapiGlobals.pszComputerName; if (!(ptClient->hValidEventBufferDataEvent = CreateEvent( (LPSECURITY_ATTRIBUTES) NULL, TRUE, // manual-reset FALSE, // nonsignaled NULL // unnamed ))) { RpcRevertToSelf (); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } if (!DuplicateHandle( TapiGlobals.hProcess, ptClient->hValidEventBufferDataEvent, ptClient->hProcess, (HANDLE *) phAsyncEventsEvent, 0, FALSE, DUPLICATE_SAME_ACCESS )) { LOG((TL_ERROR, "ClientAttach: DupHandle failed, err=%d", GetLastError() )); } RpcRevertToSelf (); // // Load the priority lists if we haven't already done so // if (gbPriorityListsInitialized == FALSE) { RPC_STATUS status; if ((status = RpcImpersonateClient (0)) != RPC_S_OK) { LOG((TL_ERROR, "ClientAttach: RpcImpersonateClient failed, err=%d", status )); lResult = LINEERR_OPERATIONFAILED; goto ClientAttach_error5; } EnterCriticalSection (&gPriorityListCritSec); if (gbPriorityListsInitialized == FALSE) { HKEY hKeyHandoffPriorities, hKeyCurrentUser; LONG lResult; gbPriorityListsInitialized = TRUE; if (ERROR_SUCCESS == (lResult = RegOpenCurrentUser (KEY_ALL_ACCESS, &hKeyCurrentUser))) { if ((lResult = RegOpenKeyEx( hKeyCurrentUser, gszRegKeyHandoffPriorities, 0, KEY_READ, &hKeyHandoffPriorities )) == ERROR_SUCCESS) { HKEY hKeyMediaModes; DWORD dwDisp; if ((lResult = RegCreateKeyEx( hKeyHandoffPriorities, gszRegKeyHandoffPrioritiesMediaModes, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyMediaModes, &dwDisp )) == ERROR_SUCCESS) { GetMediaModesPriorityLists( hKeyMediaModes, &(TapiGlobals.pPriLists) ); RegCloseKey( hKeyMediaModes ); } GetPriorityList( hKeyHandoffPriorities, gszRequestMakeCallW, &TapiGlobals.pszReqMakeCallPriList ); GetPriorityList( hKeyHandoffPriorities, gszRequestMediaCallW, &TapiGlobals.pszReqMediaCallPriList ); RegCloseKey (hKeyHandoffPriorities); } else { LOG((TL_ERROR, "RegOpenKey('\\HandoffPri') failed, err=%ld", lResult )); } RegCloseKey (hKeyCurrentUser); } else { LOG((TL_ERROR, "RegOpenCurrentUser failed, err=%ld", lResult )); } } LeaveCriticalSection (&gPriorityListCritSec); if (status == RPC_S_OK) { RpcRevertToSelf (); } } } // // Add tClient to global list // ClientAttach_AddClientToList: TapiEnterCriticalSection (&TapiGlobals.CritSec); if ((ptClient->pNext = TapiGlobals.ptClients)) { ptClient->pNext->pPrev = ptClient; } TapiGlobals.ptClients = ptClient; gfWeHadAtLeastOneClient = TRUE; ptClient->dwKey = TCLIENT_KEY; { PTPROVIDER ptProvider; ptProvider = TapiGlobals.ptProviders; while (NULL != ptProvider) { if (NULL != ptProvider->apfn[SP_PROVIDERCHECKFORNEWUSER]) { CallSP1( ptProvider->apfn[SP_PROVIDERCHECKFORNEWUSER], "providerCheckForNewUser", SP_FUNC_SYNC, (DWORD)ptProvider->dwPermanentProviderID ); } ptProvider = ptProvider->pNext; } } TapiLeaveCriticalSection (&TapiGlobals.CritSec); // // Fill in return values // *pphContext = (PCONTEXT_HANDLE_TYPE) UIntToPtr(ptClient->htClient); PerfBlock.dwClientApps++; return 0; // // Error cleanup // Admin_error: ServerFree (ptClient->pEventBuffer); DereferenceObject (ghHandleTable, ptClient->htClient, 1); return LINEERR_OPERATIONFAILED; ClientAttach_error5: if (ptClient->pszComputerName != TapiGlobals.pszComputerName) { ServerFree (ptClient->pszComputerName); } #if TELE_SERVER ClientAttach_error4: #endif ServerFree (ptClient->pszDomainName); #if TELE_SERVER ClientAttach_error3: #endif ServerFree (ptClient->pszUserName); ClientAttach_error2: ServerFree (ptClient->pEventBuffer); ClientAttach_error1: DereferenceObject (ghHandleTable, ptClient->htClient, 1); ClientAttach_error0: if (lResult == 0) { lResult = LINEERR_NOMEM; } return lResult; } void ClientRequest( PCONTEXT_HANDLE_TYPE phContext, unsigned char *pBuffer, long lNeededSize, long *plUsedSize ) { PTAPI32_MSG pMsg = (PTAPI32_MSG) pBuffer; DWORD dwFuncIndex; PTCLIENT ptClient = NULL; DWORD objectToDereference = DWORD_CAST((ULONG_PTR)phContext,__FILE__,__LINE__); if (lNeededSize < sizeof (TAPI32_MSG) || *plUsedSize < sizeof (ULONG_PTR)) // sizeof (pMsg->u.Req_Func) { pMsg->u.Ack_ReturnValue = LINEERR_INVALPARAM; goto ExitHere; } dwFuncIndex = pMsg->u.Req_Func; ptClient = ReferenceObject( ghHandleTable, objectToDereference, TCLIENT_KEY); if (ptClient == NULL) { pMsg->u.Ack_ReturnValue = TAPIERR_INVALRPCCONTEXT; goto ExitHere; } // // Old (nt4sp4, win98) clients pass across a usedSize // == 3 * sizeof(DWORD) for the xgetAsyncEvents request, // so we have to special case them when checking buf size // if (*plUsedSize < (long) (dwFuncIndex == xGetAsyncEvents ? 3 * sizeof (ULONG_PTR) : sizeof (TAPI32_MSG))) { goto ExitHere; } *plUsedSize = sizeof (LONG_PTR); if (dwFuncIndex >= xLastFunc) { pMsg->u.Ack_ReturnValue = LINEERR_OPERATIONUNAVAIL; } else if (ptClient->dwKey == TCLIENT_KEY) { pMsg->u.Ack_ReturnValue = TAPI_SUCCESS; (*gaFuncs[dwFuncIndex])( ptClient, pMsg, lNeededSize - sizeof(TAPI32_MSG), pBuffer + sizeof(TAPI32_MSG), plUsedSize ); } else { pMsg->u.Ack_ReturnValue = LINEERR_REINIT; } ExitHere: if (ptClient) { DereferenceObject( ghHandleTable, ptClient->htClient, 1); } return; } void ClientDetach( PCONTEXT_HANDLE_TYPE *pphContext ) { PTCLIENT ptClient; DWORD objectToDereference = DWORD_CAST((ULONG_PTR)(*pphContext),__FILE__,__LINE__); LOG((TL_TRACE, "ClientDetach: enter")); ptClient = ReferenceObject( ghHandleTable, objectToDereference, TCLIENT_KEY); if (ptClient == NULL) { goto ExitHere; } { if (!IS_REMOTE_CLIENT (ptClient)) { // // Write the pri lists to the registry when a local client // detaches. // { HKEY hKeyHandoffPriorities, hKeyCurrentUser; LONG lResult; DWORD dwDisposition; RPC_STATUS status; if ((status = RpcImpersonateClient (0)) == RPC_S_OK) { if (ERROR_SUCCESS == (lResult = RegOpenCurrentUser (KEY_ALL_ACCESS, &hKeyCurrentUser))) { if ((lResult = RegCreateKeyEx( hKeyCurrentUser, gszRegKeyHandoffPriorities, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, (LPSECURITY_ATTRIBUTES) NULL, &hKeyHandoffPriorities, &dwDisposition )) == ERROR_SUCCESS) { HKEY hKeyHandoffPrioritiesMediaModes; EnterCriticalSection (&gPriorityListCritSec); RegDeleteKey( hKeyHandoffPriorities, gszRegKeyHandoffPrioritiesMediaModes ); if ((lResult = RegCreateKeyEx( hKeyHandoffPriorities, gszRegKeyHandoffPrioritiesMediaModes, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, (LPSECURITY_ATTRIBUTES) NULL, &hKeyHandoffPrioritiesMediaModes, &dwDisposition )) == ERROR_SUCCESS) { SetMediaModesPriorityList( hKeyHandoffPrioritiesMediaModes, TapiGlobals.pPriLists ); RegCloseKey( hKeyHandoffPrioritiesMediaModes ); } SetPriorityList( hKeyHandoffPriorities, gszRequestMakeCallW, TapiGlobals.pszReqMakeCallPriList ); SetPriorityList( hKeyHandoffPriorities, gszRequestMediaCallW, TapiGlobals.pszReqMediaCallPriList ); LeaveCriticalSection (&gPriorityListCritSec); RegCloseKey (hKeyHandoffPriorities); } else { LOG((TL_ERROR, "RegCreateKeyEx('\\HandoffPri') failed, err=%ld", lResult )); } RegCloseKey (hKeyCurrentUser); } else { LOG((TL_ERROR, "RegOpenCurrentUser failed, err=%ld", lResult )); } RpcRevertToSelf (); } else { LOG((TL_ERROR, "ClientDetach: RpcImpersonateClient failed, err=%d", status)); } } } } PCONTEXT_HANDLE_TYPE_rundown (*pphContext); *pphContext = (PCONTEXT_HANDLE_TYPE) NULL; PerfBlock.dwClientApps--; LOG((TL_TRACE, "ClientDetach: exit")); ExitHere: if (ptClient) { DereferenceObject( ghHandleTable, ptClient->htClient, 1); } return; } BOOL CleanUpClient( PTCLIENT ptClient, BOOL bRundown ) /*++ This function separates out the freeing of client resources and removing it from the client list from actually freeing the client. For the case where the client timed out we want to clean up all the client's resources. However, the client can potentially still call in to tapisrv, so we can't free the client handle (or it will fault in lineprolog / phoneprolog). --*/ { BOOL bResult, bExit; CleanUpClient_lockClient: try { LOCKTCLIENT (ptClient); } myexcept { // do nothing } try { if (bRundown) { switch (ptClient->dwKey) { case TCLIENT_KEY: // // Invalidate the key & proceed with clean up // ptClient->dwKey = INVAL_KEY; bExit = FALSE; break; case TZOMBIECLIENT_KEY: // // An EventNotificationThread already cleaned up this client, // so invalidate the key, exit & return TRUE // ptClient->dwKey = INVAL_KEY; bResult = bExit = TRUE; break; case TCLIENTCLEANUP_KEY: // // An EventNotificationThread is cleaning up this client. // Release the lock, wait a little while, then try again. // UNLOCKTCLIENT (ptClient); Sleep (50); goto CleanUpClient_lockClient; default: // // This is not a valid tClient, so exit & return FALSE // bResult = FALSE; bExit = TRUE; break; } } else // called by EventNotificationThread on timeout { if (ptClient->dwKey == TCLIENT_KEY) { // // Mark the key as "doing cleanup", then proceed // bExit = FALSE; ptClient->dwKey = TCLIENTCLEANUP_KEY; } else { // // Either the tClient is invalid or it's being cleaned // up by someone else, so exit & return FALSE // bResult = FALSE; bExit = TRUE; } } } myexcept { bResult = FALSE; bExit = TRUE; } try { UNLOCKTCLIENT (ptClient); } myexcept { // do nothing } if (bExit) { return bResult; } // Clear the MMC write lock if any if (IS_FLAG_SET (ptClient->dwFlags, PTCLIENT_FLAG_LOCKEDMMCWRITE)) { EnterCriticalSection (&gMgmtCritSec); gbLockMMCWrite = FALSE; LeaveCriticalSection (&gMgmtCritSec); } #if TELE_SERVER if (IS_REMOTE_CLIENT (ptClient) && ptClient->MsgPendingListEntry.Flink) { CRITICAL_SECTION *pCS = (IS_REMOTE_CN_CLIENT (ptClient) ? &gCnClientMsgPendingCritSec : &gDgClientMsgPendingCritSec); EnterCriticalSection (pCS); if (ptClient->MsgPendingListEntry.Flink) { RemoveEntryList (&ptClient->MsgPendingListEntry); } LeaveCriticalSection (pCS); } #endif TapiEnterCriticalSection (&TapiGlobals.CritSec); try { if (ptClient->pNext) { ptClient->pNext->pPrev = ptClient->pPrev; } if (ptClient->pPrev) { ptClient->pPrev->pNext = ptClient->pNext; } else { TapiGlobals.ptClients = ptClient->pNext; } } myexcept { // simply continue } TapiLeaveCriticalSection (&TapiGlobals.CritSec); #if TELE_SERVER if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { HMANAGEMENTCLIENT htClient; PTMANAGEDLLINFO pDll; (TapiGlobals.pMapperDll->aProcs[TC_CLIENTSHUTDOWN])(ptClient->hMapper); if (TapiGlobals.pManageDllList) { pDll = TapiGlobals.pManageDllList->pFirst; while (pDll) { if (GetTCClient (pDll, ptClient, TC_CLIENTSHUTDOWN, &htClient)) { try { (pDll->aProcs[TC_CLIENTSHUTDOWN])(htClient); } myexcept { LOG((TL_ERROR, "CLIENT DLL had a problem: x%p",ptClient)); break; } } pDll = pDll->pNext; } } } // // If client was remote then detach // if (IS_REMOTE_CN_CLIENT (ptClient) && bRundown) { RpcTryExcept { RemoteSPDetach (&ptClient->phContext); } RpcExcept (I_RpcExceptionFilter(RpcExceptionCode())) { unsigned long ulResult = RpcExceptionCode(); LOG((TL_ERROR, "rundown: exception #%d detaching from remotesp", ulResult )); if (ulResult == RPC_S_SERVER_TOO_BUSY) { } else { } } RpcEndExcept } #endif // // Close all XxxApps // while (ptClient->ptLineApps) { DestroytLineApp (ptClient->ptLineApps->hLineApp); } while (ptClient->ptPhoneApps) { DestroytPhoneApp (ptClient->ptPhoneApps->hPhoneApp); } // // Clean up any existing ProviderXxx dialog instances // { PTAPIDIALOGINSTANCE pProviderXxxDlgInst = ptClient->pProviderXxxDlgInsts, pNextProviderXxxDlgInst; while (pProviderXxxDlgInst) { TAPI32_MSG params; params.u.Req_Func = 0; params.Params[0] = pProviderXxxDlgInst->htDlgInst; params.Params[1] = LINEERR_OPERATIONFAILED; pNextProviderXxxDlgInst = pProviderXxxDlgInst->pNext; FreeDialogInstance( ptClient, (PFREEDIALOGINSTANCE_PARAMS) &params, sizeof (params), NULL, NULL ); pProviderXxxDlgInst = pNextProviderXxxDlgInst; } } // // Clean up associated resources // if (!IS_REMOTE_CLIENT (ptClient)) { CloseHandle (ptClient->hProcess); } if (!IS_REMOTE_CN_CLIENT (ptClient)) { CloseHandle (ptClient->hValidEventBufferDataEvent); } ServerFree (ptClient->pEventBuffer); ServerFree (ptClient->pszUserName); if (ptClient->pszComputerName != TapiGlobals.pszComputerName) { ServerFree (ptClient->pszComputerName); } #if TELE_SERVER if (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) { ServerFree (ptClient->pszDomainName); if (!IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) // security DLL handles { ServerFree (ptClient->pClientHandles); ServerFree (ptClient->pLineMap); ServerFree (ptClient->pLineDevices); ServerFree (ptClient->pPhoneMap); ServerFree (ptClient->pPhoneDevices); } } #endif // // If we're called due to timeout then reset key to == ZOMBIE // so that another thread doing rundown knows that it's ok // to free the tClient object // if (!bRundown) { ptClient->dwKey = TZOMBIECLIENT_KEY; } return TRUE; } void __RPC_USER PCONTEXT_HANDLE_TYPE_rundown( PCONTEXT_HANDLE_TYPE phContext ) { DWORD i; PTCLIENT ptClient; DWORD objectToDereference = DWORD_CAST((ULONG_PTR)phContext,__FILE__,__LINE__); ptClient = ReferenceObject ( ghHandleTable, objectToDereference, TCLIENT_KEY); if (ptClient == NULL) { goto ExitHere; } LOG((TL_TRACE, "PCONTEXT_HANDLE_TYPE_rundown: enter (ptClient=x%p)",ptClient)); while (InterlockedExchange (&gRundownLock.lCookie, 1) == 1) { Sleep (50); } if (!gRundownLock.bIgnoreRundowns) { InterlockedIncrement (&gRundownLock.lNumRundowns); InterlockedExchange (&gRundownLock.lCookie, 0); // // Wrap the following in a try/except because we definitely // want to make sure we decrement gRundownLock.lRundownCount // try { if (CleanUpClient (ptClient, TRUE)) { DereferenceObject ( ghHandleTable, ptClient->htClient, 1); // // If this was the last client then alert the // SPEventHandlerThread(s) that it should begin // it's deferred shutdown countdown // if (!TapiGlobals.ptClients) { for (i = 0; i < gdwNumSPEventHandlerThreads; i++) { EnterCriticalSection( &aSPEventHandlerThreadInfo[i].CritSec ); SetEvent (aSPEventHandlerThreadInfo[i].hEvent); LeaveCriticalSection( &aSPEventHandlerThreadInfo[i].CritSec ); } } } } myexcept { } InterlockedDecrement (&gRundownLock.lNumRundowns); } else { InterlockedExchange (&gRundownLock.lCookie, 0); } ExitHere: if (ptClient) { DereferenceObject(ghHandleTable, ptClient->htClient, 1); } LOG((TL_TRACE, "PCONTEXT_HANDLE_TYPE_rundown: exit")); return; } #if DBG LPVOID WINAPI ServerAllocReal( DWORD dwSize, DWORD dwLine, PSTR pszFile ) #else LPVOID WINAPI ServerAllocReal( DWORD dwSize ) #endif { LPVOID p; #if DBG dwSize += sizeof (MYMEMINFO); #endif p = HeapAlloc (ghTapisrvHeap, HEAP_ZERO_MEMORY, dwSize); #if DBG if (p) { ((PMYMEMINFO) p)->dwLine = dwLine; ((PMYMEMINFO) p)->pszFile = pszFile; p = (LPVOID) (((PMYMEMINFO) p) + 1); } else { static BOOL fBeenThereDoneThat = FALSE; static DWORD fBreakOnAllocFailed = 0; if ( !fBeenThereDoneThat ) { HKEY hKey; TCHAR szTapisrvDebugBreak[] = TEXT("TapisrvDebugBreak"); fBeenThereDoneThat = TRUE; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_ALL_ACCESS, &hKey ) == ERROR_SUCCESS) { DWORD dwDataSize = sizeof (DWORD), dwDataType; RegQueryValueEx( hKey, szTapisrvDebugBreak, 0, &dwDataType, (LPBYTE) &fBreakOnAllocFailed, &dwDataSize ); dwDataSize = sizeof (DWORD); RegCloseKey (hKey); LOG((TL_ERROR, "BreakOnAllocFailed=%ld", fBreakOnAllocFailed)); } } if ( fBreakOnAllocFailed ) { DebugBreak(); } } #endif return p; } VOID WINAPI ServerFree( LPVOID p ) { if (!p) { return; } #if DBG // // Fill the buffer (but not the MYMEMINFO header) with 0xa1's // to facilitate debugging // { LPVOID p2 = p; DWORD dwSize; p = (LPVOID) (((PMYMEMINFO) p) - 1); dwSize = (DWORD) HeapSize (ghTapisrvHeap, 0, p); if ((dwSize != 0xFFFFFFFF) && (dwSize > sizeof (MYMEMINFO))) { FillMemory( p2, dwSize - sizeof (MYMEMINFO), 0xa1 ); } } #endif HeapFree (ghTapisrvHeap, 0, p); } #if DBG void DumpHandleList() { #ifdef INTERNALBUILD PMYHANDLEINFO pHold; if (gpHandleFirst == NULL) { LOG((TL_ERROR, "All mutexes deallocated")); return; } pHold = gpHandleFirst; while (pHold) { LOG((TL_INFO, "DumpHandleList - MUTEX %lx, FILE %s, LINE %d", pHold->hMutex, pHold->pszFile, pHold->dwLine)); pHold = pHold->pNext; } if (gbBreakOnLeak) { DebugBreak(); } #endif } #endif BOOL PASCAL MyDuplicateHandle( HANDLE hSource, LPHANDLE phTarget ) { if (!DuplicateHandle( TapiGlobals.hProcess, hSource, TapiGlobals.hProcess, phTarget, 0, FALSE, DUPLICATE_SAME_ACCESS )) { LOG((TL_ERROR, "MyDuplicateHandle: DuplicateHandle failed, err=%ld", GetLastError() )); return FALSE; } return TRUE; } #if DBG HANDLE MyRealCreateMutex( PSTR pFile, DWORD dwLine ) #else HANDLE MyRealCreateMutex( void ) #endif { HANDLE hMutex; hMutex = CreateMutex( NULL, // no security attrs FALSE, // unowned NULL // unnamed ); return (hMutex); } BOOL WaitForMutex( HANDLE hMutex, HANDLE *phMutex, BOOL *pbDupedMutex, LPVOID pWidget, DWORD dwKey, DWORD dwTimeout ) { DWORD dwResult; // note that waitformutex and code that uses the mutex must be // wrapped in a try except because the object could possibly // go away even though the thread has the mutex // // First try to instantaneously grab the specified mutex. We wrap // this in a critical section and preface it with widget validation // to make sure that we don't happen grab a pWidget->hMutex right // after it is released and right before it is closed by some other // thread "T2" in a DestroyWidget routine. This scenario could cause // deadlock, since there could be thread "T3" waiting on this mutex // (or a dup'd handle), and this thread "T1" would have no way to // release the mutex (the handle having been subsequently closed by // thread "T2" calling DestroyWidget above). // EnterCriticalSection (&gSafeMutexCritSec); if (pWidget) { try { if (*((LPDWORD) pWidget) != dwKey) { LeaveCriticalSection (&gSafeMutexCritSec); return FALSE; } } myexcept { LeaveCriticalSection (&gSafeMutexCritSec); return FALSE; } } switch ((dwResult = WaitForSingleObject (hMutex, 0))) { case WAIT_OBJECT_0: LeaveCriticalSection (&gSafeMutexCritSec); *phMutex = hMutex; *pbDupedMutex = FALSE; return TRUE; //case WAIT_ABANDONED: //assert: no calling thread should ever be terminated! default: break; } LeaveCriticalSection (&gSafeMutexCritSec); // // If here we failed to instantaneously grab the specified mutex. // Try to dup it, and then wait on the dup'd handle. We do this so // that each thread which grabs a mutex is guaranteed to have a valid // handle to release at some future time, as the original hMutex might // get closed by some other thread calling a DestroyWidget routine. // if (!DuplicateHandle( TapiGlobals.hProcess, hMutex, TapiGlobals.hProcess, phMutex, 0, FALSE, DUPLICATE_SAME_ACCESS )) { return FALSE; } WaitForMutex_wait: switch ((dwResult = WaitForSingleObject (*phMutex, dwTimeout))) { case WAIT_OBJECT_0: *pbDupedMutex = TRUE; return TRUE; case WAIT_TIMEOUT: try { if (*((LPDWORD) pWidget) == dwKey) { goto WaitForMutex_wait; } } myexcept { // just fall thru without blowing up } MyCloseMutex (*phMutex); break; //case WAIT_ABANDONED: //assert: no calling thread should ever be terminated! default: break; } return FALSE; } void MyReleaseMutex( HANDLE hMutex, BOOL bCloseMutex ) { if (hMutex) { ReleaseMutex (hMutex); if (bCloseMutex) { MyCloseMutex (hMutex); } } } void MyCloseMutex( HANDLE hMutex ) { if (hMutex) { CloseHandle (hMutex); } } void CALLBACK CompletionProcSP( DWORD dwRequestID, LONG lResult ) { PASYNCREQUESTINFO pAsyncRequestInfo; if ((pAsyncRequestInfo = ReferenceObject( ghHandleTable, dwRequestID, TASYNC_KEY ))) { #if DBG char szResult[32]; LOG((TL_TRACE, "CompletionProcSP: enter, dwReqID=x%x, lResult=%s", dwRequestID, MapResultCodeToText (lResult, szResult) )); #else LOG((TL_TRACE, "CompletionProcSP: enter, dwReqID=x%x, lResult=x%x", dwRequestID, lResult )); #endif pAsyncRequestInfo->lResult = lResult; DereferenceObject (ghHandleTable, dwRequestID, 1); } else { LOG((TL_ERROR, "CompletionProcSP: bad dwRequestID=x%x", dwRequestID)); #if DBG if (gfBreakOnSeriousProblems) { DebugBreak(); } #endif return; } if (!QueueSPEvent ((PSPEVENT) pAsyncRequestInfo)) { // // If here we're going thru shutdown & service provider // is completing any outstanding events, so process this // inline so it gets cleaned up right now. // CompletionProc (pAsyncRequestInfo, lResult); DereferenceObject (ghHandleTable, dwRequestID, 1); } } VOID PASCAL CompletionProc( PASYNCREQUESTINFO pAsyncRequestInfo, LONG lResult ) { // // Assumes pAsyncRequestInfo has been verified upon entry. // // If the tClient is bad WriteEventBuffer should handle it ok, // as should any post-processing routine. // ASYNCEVENTMSG msg[2], *pMsg = msg; #if DBG { char szResult[32]; LOG((TL_TRACE, "CompletionProc: enter, dwReqID=x%x, lResult=%s", pAsyncRequestInfo->dwLocalRequestID, MapResultCodeToText (lResult, szResult) )); } #else LOG((TL_TRACE, "CompletionProc: enter, dwReqID=x%x, lResult=x%x", pAsyncRequestInfo->dwLocalRequestID, lResult )); #endif pAsyncRequestInfo->dwKey = INVAL_KEY; // // Init the msg we'll send to client // pMsg->TotalSize = sizeof (ASYNCEVENTMSG); pMsg->InitContext = pAsyncRequestInfo->InitContext; pMsg->fnPostProcessProcHandle = pAsyncRequestInfo->hfnClientPostProcessProc; pMsg->hDevice = 0; pMsg->Msg = ((pAsyncRequestInfo->dwLineFlags & 1) ? LINE_REPLY : PHONE_REPLY); pMsg->OpenContext = pAsyncRequestInfo->OpenContext; pMsg->Param1 = pAsyncRequestInfo->dwRemoteRequestID; pMsg->Param2 = lResult; pMsg->Param3 = 0; // // If there's a post processing proc call it. Note that ppprocs can // create their own msg to pass, so we need to check for this case. // Finally, write the msg to the client's event buffer. // if (pAsyncRequestInfo->pfnPostProcess) { LPVOID pBuf = NULL; (*pAsyncRequestInfo->pfnPostProcess)(pAsyncRequestInfo, pMsg, &pBuf); WriteEventBuffer (pAsyncRequestInfo->ptClient, (pBuf ? pBuf : pMsg)); if (pBuf) { ServerFree (pBuf); } } else { WriteEventBuffer (pAsyncRequestInfo->ptClient, pMsg); } // caller will free pAsyncRequestInfo } void WriteEventBuffer( PTCLIENT ptClient, PASYNCEVENTMSG pMsg ) { BOOL bSignalRemote = FALSE; DWORD dwMoveSize = (DWORD) pMsg->TotalSize, dwMoveSizeWrapped = 0, dwPreviousUsedSize, dwData; HANDLE hMailslot; #if DBG if (dwMoveSize & 0x3) { LOG((TL_ERROR, "WriteEventBuffer: ERROR! bad MsgSize=x%x (Msg=x%x, pCli=x%p)", dwMoveSize, pMsg->Msg, ptClient )); } #endif LOG((TL_TRACE, "WriteEventBuffer - enter")); if (WaitForExclusiveClientAccess (ptClient)) { // // Check to see if we need to grow the event buffer // if (dwMoveSize > (ptClient->dwEventBufferTotalSize - ptClient->dwEventBufferUsedSize)) { DWORD dwMoveSize2, dwMoveSizeWrapped2, dwNewEventBufferTotalSize; LPBYTE pNewEventBuffer; // // Do some math to have the total be a multiple // of sizeof(ASYNCEVENTMSG) // dwNewEventBufferTotalSize = ptClient->dwEventBufferTotalSize + ( (( dwMoveSize / sizeof(ASYNCEVENTMSG) ) + 20 ) * sizeof(ASYNCEVENTMSG)); if (!(pNewEventBuffer = ServerAlloc( dwNewEventBufferTotalSize ))) { UNLOCKTCLIENT (ptClient); return; } if (ptClient->dwEventBufferUsedSize != 0) { if (ptClient->pDataIn > ptClient->pDataOut) { dwMoveSize2 = (DWORD) (ptClient->pDataIn - ptClient->pDataOut); dwMoveSizeWrapped2 = 0; } else { dwMoveSize2 = (DWORD) ((ptClient->pEventBuffer + ptClient->dwEventBufferTotalSize) - ptClient->pDataOut); dwMoveSizeWrapped2 = (DWORD) (ptClient->pDataIn - ptClient->pEventBuffer); } CopyMemory( pNewEventBuffer, ptClient->pDataOut, dwMoveSize2 ); if (dwMoveSizeWrapped2) { CopyMemory( pNewEventBuffer + dwMoveSize2, ptClient->pEventBuffer, dwMoveSizeWrapped2 ); } ptClient->pDataIn = pNewEventBuffer + dwMoveSize2 + dwMoveSizeWrapped2; } else { ptClient->pDataIn = pNewEventBuffer; } ServerFree (ptClient->pEventBuffer); ptClient->pDataOut = ptClient->pEventBuffer = pNewEventBuffer; ptClient->dwEventBufferTotalSize = dwNewEventBufferTotalSize; } // // Compute the MoveSize's, do the copy(ies), & update the pointers // if (ptClient->pDataIn >= ptClient->pDataOut) { DWORD dwFreeSize = ptClient->dwEventBufferTotalSize - (DWORD) (ptClient->pDataIn - ptClient->pEventBuffer); if (dwMoveSize > dwFreeSize) { dwMoveSizeWrapped = dwMoveSize - dwFreeSize; dwMoveSize = dwFreeSize; } } CopyMemory (ptClient->pDataIn, (LPBYTE) pMsg, dwMoveSize); if (dwMoveSizeWrapped != 0) { CopyMemory( ptClient->pEventBuffer, ((LPBYTE) pMsg) + dwMoveSize, dwMoveSizeWrapped ); ptClient->pDataIn = ptClient->pEventBuffer + dwMoveSizeWrapped; } else { ptClient->pDataIn += dwMoveSize; if (ptClient->pDataIn >= (ptClient->pEventBuffer + ptClient->dwEventBufferTotalSize)) { ptClient->pDataIn = ptClient->pEventBuffer; } } dwPreviousUsedSize = ptClient->dwEventBufferUsedSize; ptClient->dwEventBufferUsedSize += (DWORD) pMsg->TotalSize; if (!IS_REMOTE_CLIENT (ptClient)) { LOG((TL_TRACE, "WriteEventBuffer: SetEvent %p for local client", ptClient->hValidEventBufferDataEvent)); SetEvent (ptClient->hValidEventBufferDataEvent); } else if (dwPreviousUsedSize == 0) { if (IS_REMOTE_CN_CLIENT (ptClient)) { EnterCriticalSection (&gCnClientMsgPendingCritSec); InsertTailList( &CnClientMsgPendingListHead, &ptClient->MsgPendingListEntry ); LeaveCriticalSection (&gCnClientMsgPendingCritSec); hMailslot = NULL; bSignalRemote = TRUE; } else { if (dwPreviousUsedSize == 0) { ptClient->dwDgEventsRetrievedTickCount = GetTickCount(); } EnterCriticalSection (&gDgClientMsgPendingCritSec); InsertTailList( &DgClientMsgPendingListHead, &ptClient->MsgPendingListEntry ); LeaveCriticalSection (&gDgClientMsgPendingCritSec); hMailslot = ptClient->hMailslot; if (ptClient->ptLineApps != NULL) { dwData = (DWORD) ptClient->ptLineApps->InitContext; } else { dwData = 0; } bSignalRemote = TRUE; } } UNLOCKTCLIENT (ptClient); if (bSignalRemote) { if (hMailslot) { DWORD dwBytesWritten; if (!WriteFile( hMailslot, &dwData, sizeof (DWORD), &dwBytesWritten, (LPOVERLAPPED) NULL )) { LOG((TL_ERROR, "WriteEventBuffer: Writefile(mailslot) " \ "failed, err=%d", GetLastError() )); } else { ptClient->dwDgRetryTimeoutTickCount = GetTickCount() + 2 * DGCLIENT_TIMEOUT; } } else { SetEvent (gEventNotificationThreadParams.hEvent); } } } else { LOG((TL_ERROR, "WriteEventBuffer: - WaitForExclusiveClientAccess returns 0")); } } LONG GetPermLineIDAndInsertInTable( PTPROVIDER ptProvider, DWORD dwDeviceID, DWORD dwSPIVersion ) { #if TELE_SERVER LONG lResult = 0; DWORD dwSize; LPLINEDEVCAPS pCaps; if (!ptProvider || !ptProvider->apfn[SP_LINEGETDEVCAPS]) { return LINEERR_OPERATIONFAILED; } dwSize = sizeof (LINEDEVCAPS); if (!(pCaps = ServerAlloc (dwSize))) { return LINEERR_NOMEM; } pCaps->dwTotalSize = pCaps->dwUsedSize = pCaps->dwNeededSize = dwSize; if ((lResult = CallSP4( ptProvider->apfn[SP_LINEGETDEVCAPS], "lineGetDevCaps", SP_FUNC_SYNC, (DWORD)dwDeviceID, (DWORD)dwSPIVersion, (DWORD)0, (ULONG_PTR) pCaps )) == 0) { // // add to sorted array // InsertIntoTable( TRUE, dwDeviceID, ptProvider, pCaps->dwPermanentLineID ); } ServerFree (pCaps); return lResult; #else return 0; #endif } LONG AddLine( PTPROVIDER ptProvider, DWORD dwDeviceID, BOOL bInit ) { DWORD dwSPIVersion; HANDLE hMutex = NULL; PTLINELOOKUPTABLE pLookup; if (ptProvider->apfn[SP_LINENEGOTIATETSPIVERSION] == NULL) { return LINEERR_OPERATIONUNAVAIL; } // // First try to negotiate an SPI ver for this device, and alloc the // necessary resources // if (CallSP4( ptProvider->apfn[SP_LINENEGOTIATETSPIVERSION], "lineNegotiateTSPIVersion", SP_FUNC_SYNC, (DWORD)dwDeviceID, (DWORD)TAPI_VERSION1_0, (DWORD)TAPI_VERSION_CURRENT, (ULONG_PTR) &dwSPIVersion ) != 0) { // // Device failed version negotiation, so we'll keep the id around // (since the id's for the devices that follow have already been // assigned) but mark this device as bad // ptProvider = NULL; } else if (!(hMutex = MyCreateMutex ())) { LOG((TL_ERROR, "AddLine: MyCreateMutex failed, err=%d", GetLastError() )); return LINEERR_OPERATIONFAILED; } // // Now walk the lookup table to find a free entry // pLookup = TapiGlobals.pLineLookup; while (pLookup->pNext) { pLookup = pLookup->pNext; } if (pLookup->dwNumUsedEntries == pLookup->dwNumTotalEntries) { PTLINELOOKUPTABLE pNewLookup; if (bInit) { // // If we're initializing we want to put everything in one big table // if (!(pNewLookup = ServerAlloc( sizeof (TLINELOOKUPTABLE) + (2 * pLookup->dwNumTotalEntries - 1) * sizeof (TLINELOOKUPENTRY) ))) { return LINEERR_NOMEM; } pNewLookup->dwNumTotalEntries = 2 * pLookup->dwNumTotalEntries; pNewLookup->dwNumUsedEntries = pLookup->dwNumTotalEntries; CopyMemory( pNewLookup->aEntries, pLookup->aEntries, pLookup->dwNumTotalEntries * sizeof (TLINELOOKUPENTRY) ); ServerFree (pLookup); TapiGlobals.pLineLookup = pNewLookup; } else { if (!(pNewLookup = ServerAlloc( sizeof (TLINELOOKUPTABLE) + (pLookup->dwNumTotalEntries - 1) * sizeof (TLINELOOKUPENTRY) ))) { return LINEERR_NOMEM; } pNewLookup->dwNumTotalEntries = pLookup->dwNumTotalEntries; pLookup->pNext = pNewLookup; } pLookup = pNewLookup; } // // Initialize the entry // { DWORD index = pLookup->dwNumUsedEntries; pLookup->aEntries[index].dwSPIVersion = dwSPIVersion; pLookup->aEntries[index].hMutex = hMutex; pLookup->aEntries[index].ptProvider = ptProvider; if (ptProvider && lstrcmpi(ptProvider->szFileName, TEXT("remotesp.tsp")) == 0) { pLookup->aEntries[index].bRemote = TRUE; } } pLookup->dwNumUsedEntries++; #if TELE_SERVER // // If this is an NT Server we want to be able to set user // permissions regardless of whether or not TAPI server // functionality is enabled. This allows an admin to set // stuff up while the server is "offline". // if (gbNTServer) { GetPermLineIDAndInsertInTable (ptProvider, dwDeviceID, dwSPIVersion); } #endif return 0; } DWORD GetNumLineLookupEntries () { PTLINELOOKUPTABLE pLineLookup; DWORD dwNumLines; pLineLookup = TapiGlobals.pLineLookup; dwNumLines = 0; while (pLineLookup) { dwNumLines += pLineLookup->dwNumUsedEntries; pLineLookup = pLineLookup->pNext; } return dwNumLines; } LONG GetPermPhoneIDAndInsertInTable( PTPROVIDER ptProvider, DWORD dwDeviceID, DWORD dwSPIVersion ) { #if TELE_SERVER LONG lResult = 0; DWORD dwSize; LPPHONECAPS pCaps; if (!ptProvider->apfn[SP_PHONEGETDEVCAPS]) { return PHONEERR_OPERATIONFAILED; } dwSize = sizeof (PHONECAPS); if (!(pCaps = ServerAlloc (dwSize))) { return PHONEERR_NOMEM; } pCaps->dwTotalSize = pCaps->dwUsedSize = pCaps->dwNeededSize = dwSize; if ((lResult = CallSP4( ptProvider->apfn[SP_PHONEGETDEVCAPS], "phoneGetCaps", SP_FUNC_SYNC, (DWORD)dwDeviceID, (DWORD)dwSPIVersion, (DWORD)0, (ULONG_PTR) pCaps )) == 0) { // // add to sorted array // InsertIntoTable( FALSE, dwDeviceID, ptProvider, pCaps->dwPermanentPhoneID ); } ServerFree (pCaps); return lResult; #else return 0; #endif } LONG AddPhone( PTPROVIDER ptProvider, DWORD dwDeviceID, BOOL bInit ) { DWORD dwSPIVersion; HANDLE hMutex = NULL; PTPHONELOOKUPTABLE pLookup; if (ptProvider->apfn[SP_PHONENEGOTIATETSPIVERSION] == NULL) { return PHONEERR_OPERATIONUNAVAIL; } // // First try to negotiate an SPI ver for this device, and alloc the // necessary resources // if (CallSP4( ptProvider->apfn[SP_PHONENEGOTIATETSPIVERSION], "phoneNegotiateTSPIVersion", SP_FUNC_SYNC, (DWORD)dwDeviceID, (DWORD)TAPI_VERSION1_0, (DWORD)TAPI_VERSION_CURRENT, (ULONG_PTR) &dwSPIVersion ) != 0) { // // Device failed version negotiation, so we'll keep the id around // (since the id's for the devices that follow have already been // assigned) but mark this device as bad // return PHONEERR_OPERATIONFAILED; } else if (!(hMutex = MyCreateMutex ())) { LOG((TL_ERROR, "AddPhone: MyCreateMutex failed, err=%d", GetLastError() )); return PHONEERR_OPERATIONFAILED; } // // Now walk the lookup table to find a free entry // pLookup = TapiGlobals.pPhoneLookup; while (pLookup->pNext) { pLookup = pLookup->pNext; } if (pLookup->dwNumUsedEntries == pLookup->dwNumTotalEntries) { PTPHONELOOKUPTABLE pNewLookup; if (bInit) { // // If we're initializing we want to put everything in one big table // if (!(pNewLookup = ServerAlloc( sizeof (TPHONELOOKUPTABLE) + (2 * pLookup->dwNumTotalEntries - 1) * sizeof (TPHONELOOKUPENTRY) ))) { return PHONEERR_NOMEM; } pNewLookup->dwNumTotalEntries = 2 * pLookup->dwNumTotalEntries; pNewLookup->dwNumUsedEntries = pLookup->dwNumTotalEntries; CopyMemory( pNewLookup->aEntries, pLookup->aEntries, pLookup->dwNumTotalEntries * sizeof (TPHONELOOKUPENTRY) ); ServerFree (pLookup); TapiGlobals.pPhoneLookup = pNewLookup; } else { if (!(pNewLookup = ServerAlloc( sizeof (TPHONELOOKUPTABLE) + (pLookup->dwNumTotalEntries - 1) * sizeof (TPHONELOOKUPENTRY) ))) { return PHONEERR_NOMEM; } pNewLookup->dwNumTotalEntries = pLookup->dwNumTotalEntries; pLookup->pNext = pNewLookup; } pLookup = pNewLookup; } // // Initialize the entry // { DWORD index = pLookup->dwNumUsedEntries; pLookup->aEntries[index].dwSPIVersion = dwSPIVersion; pLookup->aEntries[index].hMutex = hMutex; pLookup->aEntries[index].ptProvider = ptProvider; } pLookup->dwNumUsedEntries++; #if TELE_SERVER // // If this is an NT Server we want to be able to set user // permissions regardless of whether or not TAPI server // functionality is enabled. This allows an admin to set // stuff up while the server is "offline". // if (gbNTServer) { GetPermPhoneIDAndInsertInTable (ptProvider, dwDeviceID, dwSPIVersion); } #endif return 0; } DWORD GetNumPhoneLookupEntries () { PTPHONELOOKUPTABLE pPhoneLookup; DWORD dwNumPhones; pPhoneLookup = TapiGlobals.pPhoneLookup; dwNumPhones = 0; while (pPhoneLookup) { dwNumPhones += pPhoneLookup->dwNumUsedEntries; pPhoneLookup = pPhoneLookup->pNext; } return dwNumPhones; } void PASCAL GetMediaModesPriorityLists( HKEY hKeyHandoffPriorities, PRILISTSTRUCT **ppList ) { #define REGNAMESIZE ( 10 * sizeof(TCHAR) ) DWORD dwCount; DWORD dwType, dwNameSize, dwNumBytes; TCHAR *pszName; dwNameSize = REGNAMESIZE; pszName = ServerAlloc( dwNameSize*sizeof(TCHAR) ); if (NULL == pszName) { return; } dwCount = 0; while ( TRUE ) { if (TapiGlobals.dwUsedPriorityLists == TapiGlobals.dwTotalPriorityLists) { // realloc PRILISTSTRUCT * pNewList; pNewList = ServerAlloc( sizeof(PRILISTSTRUCT) * (2*TapiGlobals.dwTotalPriorityLists) ); if (NULL == pNewList) { LOG((TL_ERROR, "ServerAlloc failed in GetMediaModesPriorityLists 2")); ServerFree( pszName ); return; } CopyMemory( pNewList, *ppList, sizeof( PRILISTSTRUCT ) * TapiGlobals.dwTotalPriorityLists ); ServerFree( *ppList ); *ppList = pNewList; TapiGlobals.dwTotalPriorityLists *= 2; } dwNameSize = REGNAMESIZE; if ( ERROR_SUCCESS != RegEnumValue( hKeyHandoffPriorities, dwCount, pszName, &dwNameSize, NULL, NULL, NULL, NULL ) ) { break; } (*ppList)[dwCount].dwMediaModes = (DWORD) _ttol( pszName ); if ((RegQueryValueEx( hKeyHandoffPriorities, pszName, NULL, &dwType, NULL, &dwNumBytes )) == ERROR_SUCCESS && (dwNumBytes != 0)) { // pszPriotiryList needs to be wide because we pack it into one of our // little structures and these structures are always WCHAR. LPWSTR pszPriorityList; // convert from the bytes needed to hold a TCHAR into the bytes to hold a WCHAR dwNumBytes *= sizeof(WCHAR)/sizeof(TCHAR); pszPriorityList = ServerAlloc ( dwNumBytes + sizeof(WCHAR)); // need an extra WCHAR for the extra '"' if (NULL != pszPriorityList) { pszPriorityList[0] = L'"'; if ((TAPIRegQueryValueExW( hKeyHandoffPriorities, pszName, NULL, &dwType, (LPBYTE)(pszPriorityList + 1), &dwNumBytes )) == ERROR_SUCCESS) { _wcsupr( pszPriorityList ); (*ppList)[dwCount].pszPriList = pszPriorityList; LOG((TL_INFO, "PriList: %ls=%ls", pszName, pszPriorityList)); } } } TapiGlobals.dwUsedPriorityLists++; dwCount++; } ServerFree( pszName ); } void PASCAL GetPriorityList( HKEY hKeyHandoffPriorities, const TCHAR *pszListName, WCHAR **ppszPriorityList ) { LONG lResult; DWORD dwType, dwNumBytes; *ppszPriorityList = NULL; if ((lResult = TAPIRegQueryValueExW( hKeyHandoffPriorities, pszListName, NULL, &dwType, NULL, &dwNumBytes )) == ERROR_SUCCESS && (dwNumBytes != 0)) { // Once again, this is going to get packed into a struct and we always use // wide chars for things packed in structs. WCHAR *pszPriorityList = ServerAlloc ( dwNumBytes + sizeof(WCHAR)); // need an extra WCHAR for the extra '"' if (pszPriorityList) { pszPriorityList[0] = L'"'; if ((lResult = TAPIRegQueryValueExW( hKeyHandoffPriorities, pszListName, NULL, &dwType, (LPBYTE)(pszPriorityList + 1), &dwNumBytes )) == ERROR_SUCCESS) { _wcsupr( pszPriorityList ); *ppszPriorityList = pszPriorityList; LOG((TL_INFO, "PriList: %ls=%ls", pszListName, pszPriorityList)); } } else { // // Don't bother with the failure to alloc a priority list // (list defaults to NULL anyway), we'll deal with a lack // of memory at a later time // *ppszPriorityList = NULL; } } else { *ppszPriorityList = NULL; LOG((TL_INFO, "PriList: %ls=NULL", pszListName)); } } LONG ServerInit( BOOL fReinit ) { UINT uiNumProviders, i, j; HKEY hKeyTelephony, hKeyProviders; DWORD dwDataSize, dwDataType, dwNameHash; TCHAR *psz; LONG lResult = 0; DWORD dw1, dw2; // // Clean up our private heap // if (ghTapisrvHeap != GetProcessHeap()) { HeapCompact (ghTapisrvHeap, 0); } // // Initialize the globals // if (!fReinit) { TapiGlobals.ptProviders = NULL; TapiGlobals.pLineLookup = (PTLINELOOKUPTABLE) ServerAlloc( sizeof (TLINELOOKUPTABLE) + (DEF_NUM_LOOKUP_ENTRIES - 1) * sizeof (TLINELOOKUPENTRY) ); if (!(TapiGlobals.pLineLookup)) { lResult = LINEERR_NOMEM; goto ExitHere; } TapiGlobals.pLineLookup->dwNumTotalEntries = DEF_NUM_LOOKUP_ENTRIES; TapiGlobals.pPhoneLookup = (PTPHONELOOKUPTABLE) ServerAlloc( sizeof (TPHONELOOKUPTABLE) + (DEF_NUM_LOOKUP_ENTRIES - 1) * sizeof (TPHONELOOKUPENTRY) ); if (!(TapiGlobals.pPhoneLookup)) { ServerFree(TapiGlobals.pLineLookup); TapiGlobals.pLineLookup = NULL; lResult = LINEERR_NOMEM; goto ExitHere; } TapiGlobals.pPhoneLookup->dwNumTotalEntries = DEF_NUM_LOOKUP_ENTRIES; gbQueueSPEvents = TRUE; OnProxySCPInit (); } // // Determine number of providers // WaitForSingleObject (ghProvRegistryMutex, INFINITE); lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_ALL_ACCESS, &hKeyTelephony ); if (ERROR_SUCCESS != lResult) { goto ExitHere; } lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ); if (ERROR_SUCCESS != lResult) { RegCloseKey (hKeyTelephony); goto ExitHere; } dwDataSize = sizeof(uiNumProviders); uiNumProviders = 0; RegQueryValueEx( hKeyProviders, gszNumProviders, 0, &dwDataType, (LPBYTE) &uiNumProviders, &dwDataSize ); LOG((TL_INFO, "ServerInit: NumProviders=%d", uiNumProviders)); // // Load & init the providers // for (i = 0; i < uiNumProviders; i++) { #define FILENAME_SIZE 128 TCHAR szFilename[FILENAME_SIZE]; TCHAR buf[32]; LONG lResult; DWORD dwNumLines, dwNumPhones, dwPermanentProviderID; PTPROVIDER ptProvider; BOOL fEnumDevices; fEnumDevices = FALSE; wsprintf(buf, TEXT("%s%d"), gszProviderID, i); dwDataSize = sizeof(dwPermanentProviderID); dwPermanentProviderID = 0; RegQueryValueEx( hKeyProviders, buf, //"ProviderID#" 0, &dwDataType, (LPBYTE) &dwPermanentProviderID, &dwDataSize ); // // Back to the main section // dwDataSize = FILENAME_SIZE; wsprintf(buf, TEXT("%s%d"), gszProviderFilename, i); RegQueryValueEx( hKeyProviders, buf, // "ProviderFilename#" 0, &dwDataType, (LPBYTE) szFilename, &dwDataSize ); szFilename[dwDataSize/sizeof(TCHAR)] = TEXT('\0'); // // Compute name hash // dwNameHash = 0; psz = szFilename; while (*psz) { dwNameHash += (DWORD)(*psz); psz++; } // // If fReinit, make sure the provider is not already in // if (fReinit) { PTPROVIDER ptProvider2; BOOL fFound = FALSE; ptProvider2 = TapiGlobals.ptProviders; while (ptProvider2) { if ((ptProvider2->dwNameHash == dwNameHash) && (lstrcmpi(ptProvider2->szFileName, szFilename) == 0)) { fFound = TRUE; break; } ptProvider2 = ptProvider2->pNext; } if (fFound) { continue; } } LOG((TL_INFO, "ServerInit: ProviderFilename=%S", szFilename)); if (!(ptProvider = (PTPROVIDER) ServerAlloc( sizeof(TPROVIDER) + ((lstrlen(szFilename) + 1) * sizeof(TCHAR)) ))) { break; } if (!(ptProvider->hDll = LoadLibrary(szFilename))) { LOG((TL_ERROR, "ServerInit: LoadLibrary(%S) failed, err=x%x", szFilename, GetLastError() )); ServerFree (ptProvider); continue; } ptProvider->dwNameHash = dwNameHash; lstrcpy(ptProvider->szFileName, szFilename); // // Get all the TSPI proc addrs // for (j = 0; gaszTSPIFuncNames[j]; j++) { ptProvider->apfn[j] = (TSPIPROC) GetProcAddress( ptProvider->hDll, (LPCSTR) gaszTSPIFuncNames[j] ); } dwNumLines = dwNumPhones = 0; // // A real quick check to see if a couple of required entrypoints // are exported // if (!ptProvider->apfn[SP_LINENEGOTIATETSPIVERSION] || !ptProvider->apfn[SP_PROVIDERENUMDEVICES] || !ptProvider->apfn[SP_PROVIDERINIT] || !ptProvider->apfn[SP_PROVIDERSHUTDOWN] ) { goto ServerInit_validateEntrypoints; } // // Do global provider version negotiation // lResult = CallSP4( ptProvider->apfn[SP_LINENEGOTIATETSPIVERSION], "lineNegotiateTSPIVersion", SP_FUNC_SYNC, (DWORD)INITIALIZE_NEGOTIATION, (DWORD)TAPI_VERSION1_0, (DWORD)TAPI_VERSION_CURRENT, (ULONG_PTR) &ptProvider->dwSPIVersion ); if (lResult != 0) { provider_init_error: if (fEnumDevices) { lResult = CallSP2( ptProvider->apfn[SP_PROVIDERSHUTDOWN], "providerShutdown", SP_FUNC_SYNC, (DWORD)ptProvider->dwSPIVersion, (DWORD)ptProvider->dwPermanentProviderID ); } if (ptProvider->hMutex) { MyCloseMutex (ptProvider->hMutex); } if (ptProvider->hHashTableReaderEvent) { CloseHandle (ptProvider->hHashTableReaderEvent); } if (ptProvider->pHashTable) { ServerFree (ptProvider->pHashTable); } FreeLibrary (ptProvider->hDll); ServerFree (ptProvider); continue; } // // Try to enum the devices if provider supports it, otherwise // try grabbing the num lines & phones from ProviderN section // lResult = CallSP6( ptProvider->apfn[SP_PROVIDERENUMDEVICES], "providerEnumDevices", SP_FUNC_SYNC, (DWORD)dwPermanentProviderID, (ULONG_PTR) &dwNumLines, (ULONG_PTR) &dwNumPhones, (ULONG_PTR) ptProvider, (ULONG_PTR) LineEventProcSP, (ULONG_PTR) PhoneEventProcSP ); if (lResult != 0) { LOG((TL_ERROR, "ServerInit: %s: failed TSPI_providerEnumDevices, err=x%x" \ " - skipping it...", szFilename, lResult )); goto provider_init_error; } // // Init the provider // // !!! HACK ALERT: for kmddsp pass ptr's to dwNumXxxs // { BOOL bKmddsp; LOG((TL_INFO, "ServerInit: %s: Calling TSPI_providerInit", szFilename)); if (lstrcmpi(szFilename, TEXT("kmddsp.tsp")) == 0) { bKmddsp = TRUE; } else { bKmddsp = FALSE; if (lstrcmpi(szFilename, TEXT("remotesp.tsp")) == 0) { pRemoteSP = ptProvider; } } lResult = CallSP8( ptProvider->apfn[SP_PROVIDERINIT], "providerInit", SP_FUNC_SYNC, (DWORD)ptProvider->dwSPIVersion, (DWORD)dwPermanentProviderID, (DWORD)GetNumLineLookupEntries (), (DWORD)GetNumPhoneLookupEntries (), (bKmddsp ? (ULONG_PTR) &dwNumLines : (ULONG_PTR) dwNumLines), (bKmddsp ? (ULONG_PTR) &dwNumPhones : (ULONG_PTR) dwNumPhones), (ULONG_PTR) CompletionProcSP, (ULONG_PTR) &ptProvider->dwTSPIOptions ); } if (lResult != 0) { LOG((TL_ERROR, "ServerInit: %s: failed TSPI_providerInit, err=x%x" \ " - skipping it...", szFilename, lResult )); goto provider_init_error; } LOG((TL_INFO, "ServerInit: %s init'd, dwNumLines=%ld, dwNumPhones=%ld", szFilename, dwNumLines, dwNumPhones )); fEnumDevices = TRUE; // // Now that we know if we have line and/or phone devs check for // the required entry points // ServerInit_validateEntrypoints: { DWORD adwRequiredEntrypointIndices[] = { SP_LINENEGOTIATETSPIVERSION, SP_PROVIDERINIT, SP_PROVIDERSHUTDOWN, SP_PHONENEGOTIATETSPIVERSION, 0xffffffff }; BOOL bRequiredEntrypointsExported = TRUE; // // If this provider doesn't support any phone devices then // it isn't required to export phone funcs // if (dwNumPhones == 0) { adwRequiredEntrypointIndices[3] = 0xffffffff; } for (j = 0; adwRequiredEntrypointIndices[j] != 0xffffffff; j++) { if (ptProvider->apfn[adwRequiredEntrypointIndices[j]] == (TSPIPROC) NULL) { LOG((TL_ERROR, "ServerInit: %s: can't init, function [%s] " \ "not exported", szFilename, (LPCSTR) gaszTSPIFuncNames[ adwRequiredEntrypointIndices[j] ] )); bRequiredEntrypointsExported = FALSE; } } if (bRequiredEntrypointsExported == FALSE) { FreeLibrary (ptProvider->hDll); ServerFree (ptProvider); continue; } } ptProvider->dwPermanentProviderID = dwPermanentProviderID; // // // ptProvider->hMutex = MyCreateMutex(); // // Initialize the call hub hash table for this provider // MyInitializeCriticalSection (&ptProvider->HashTableCritSec, 1000); ptProvider->hHashTableReaderEvent = CreateEvent( (LPSECURITY_ATTRIBUTES) NULL, FALSE, // auto reset FALSE, // initially non-signaled NULL // unnamed ); ptProvider->dwNumHashTableEntries = TapiPrimes[0]; ptProvider->pHashTable = ServerAlloc( ptProvider->dwNumHashTableEntries * sizeof (THASHTABLEENTRY) ); if (ptProvider->pHashTable) { PTHASHTABLEENTRY pEntry = ptProvider->pHashTable; for (j = 0; j < ptProvider->dwNumHashTableEntries; j++, pEntry++) { InitializeListHead (&pEntry->CallHubList); } } else { ptProvider->dwNumHashTableEntries = 0; } if (ptProvider->hMutex == NULL || ptProvider->hHashTableReaderEvent == NULL || ptProvider->pHashTable == NULL ) { DeleteCriticalSection (&ptProvider->HashTableCritSec); goto provider_init_error; } #if TELE_SERVER // // If this is an NT Server we want to be able to set user // permissions regardless of whether or not TAPI server // functionality is enabled. This allows an admin to set // stuff up while the server is "offline". // if (gbNTServer) { LONG lResult; lResult = AddProviderToIdArrayList( ptProvider, dwNumLines, dwNumPhones ); if (lResult != 0) { LOG((TL_ERROR, "ServerInit: %s: failed AddProviderToIdArrayList [x%x]" \ " - skipping it...", ptProvider->szFileName, lResult )); DeleteCriticalSection (&ptProvider->HashTableCritSec); goto provider_init_error; } } #endif // // Do version negotiation on each device & add them to lookup lists // { DWORD dwDeviceIDBase; dwDeviceIDBase = GetNumLineLookupEntries (); for (j = dwDeviceIDBase; j < (dwDeviceIDBase + dwNumLines); j++) { if (AddLine (ptProvider, j, !fReinit)) { } } dwDeviceIDBase = GetNumPhoneLookupEntries (); for (j = dwDeviceIDBase; j < (dwDeviceIDBase + dwNumPhones); j++) { if (AddPhone (ptProvider, j, !fReinit)) { } } } // // Add provider to head of list, mark as valid // ptProvider->pPrev = NULL; ptProvider->pNext = TapiGlobals.ptProviders; if (TapiGlobals.ptProviders) { TapiGlobals.ptProviders->pPrev = ptProvider; } TapiGlobals.ptProviders = ptProvider; ptProvider->dwKey = TPROVIDER_KEY; } RegCloseKey (hKeyProviders); RegCloseKey (hKeyTelephony); ReleaseMutex (ghProvRegistryMutex); // // Save lookup lists & num devices // if (fReinit) { dw1 = TapiGlobals.dwNumLines; dw2 = TapiGlobals.dwNumPhones; } TapiGlobals.dwNumLines = GetNumLineLookupEntries (); TapiGlobals.dwNumPhones = GetNumPhoneLookupEntries (); // // Notify those apps about these new line/phone devices // if (fReinit) { // TAPI 1.4 and above get LINE_CREATE for each line for (i = dw1; i < TapiGlobals.dwNumLines; ++i) { SendAMsgToAllLineApps( TAPI_VERSION1_4 | 0x80000000, LINE_CREATE, // Msg i, // Param1 0, // Param2 0 // Param3 ); } // TAPI 1.3 get LINE_LINEDEVSTATE with LINEDEVSTATE_REINIT if (dw1 < TapiGlobals.dwNumLines) { SendAMsgToAllLineApps( TAPI_VERSION1_0, LINE_LINEDEVSTATE, LINEDEVSTATE_REINIT, 0, 0); } // TAPI 1.4 and above get PHONE_CREATE for each phone for (i = dw2; i < TapiGlobals.dwNumPhones; ++i) { SendAMsgToAllPhoneApps( TAPI_VERSION1_4 | 0x80000000, PHONE_CREATE, // Msg i, // Param1 0, // Param2 0 // Param3 ); } // TAPI 1.3 gets PHONE_STATE with PHONESTATE_REINIT if (dw2 < TapiGlobals.dwNumPhones) { SendAMsgToAllPhoneApps( TAPI_VERSION1_0, PHONE_STATE, PHONESTATE_REINIT, 0, 0); } for (i = dw1; i < TapiGlobals.dwNumLines; ++i) { AppendNewDeviceInfo (TRUE, i); } for (i = dw2; i < TapiGlobals.dwNumPhones; ++i) { AppendNewDeviceInfo (FALSE, i); } } // init perf stuff PerfBlock.dwLines = TapiGlobals.dwNumLines; PerfBlock.dwPhones = TapiGlobals.dwNumPhones; ExitHere: return lResult; } #if TELE_SERVER #ifndef UNICODE #pragma message( "ERROR: TELE_SERVER builds must define UNICODE" ) #endif BOOL LoadNewDll(PTMANAGEDLLINFO pDll) { DWORD dwCount; LONG lResult; // verify pointers. should we do more? if (!pDll || !pDll->pszName) { return FALSE; } // load dll pDll->hDll = LoadLibraryW(pDll->pszName); // if it fails, return if (!pDll->hDll) { LOG((TL_ERROR, "LoadLibrary failed for management DLL %ls - error x%lx", pDll->pszName, GetLastError() )); return FALSE; } if ((!(pDll->aProcs[TC_CLIENTINITIALIZE] = (CLIENTPROC) GetProcAddress( pDll->hDll, gaszTCFuncNames[TC_CLIENTINITIALIZE] ))) || (!(pDll->aProcs[TC_CLIENTSHUTDOWN] = (CLIENTPROC) GetProcAddress( pDll->hDll, gaszTCFuncNames[TC_CLIENTSHUTDOWN] ))) || (!(pDll->aProcs[TC_LOAD] = (CLIENTPROC) GetProcAddress( pDll->hDll, gaszTCFuncNames[TC_LOAD] ))) || (!(pDll->aProcs[TC_FREE] = (CLIENTPROC) GetProcAddress( pDll->hDll, gaszTCFuncNames[TC_FREE] )))) { // must export client init and client shutdown LOG((TL_ERROR, "Management DLL %ls does not export Load, Free, ClientIntialize or ClientShutdown", pDll->pszName)); LOG((TL_ERROR, " The DLL will not be used")); FreeLibrary(pDll->hDll); return FALSE; } // get proc addresses for (dwCount = 0; dwCount < TC_LASTPROCNUMBER; dwCount++) { pDll->aProcs[dwCount] = (CLIENTPROC) GetProcAddress( pDll->hDll, gaszTCFuncNames[dwCount] ); } pDll->dwAPIVersion = TAPI_VERSION_CURRENT; lResult = (pDll->aProcs[TC_LOAD])( &pDll->dwAPIVersion, ManagementAddLineProc, ManagementAddPhoneProc, 0 ); if (lResult) { LOG((TL_ERROR, "Management DLL %ls returned %xlx from TAPICLIENT_Load", pDll->pszName, lResult)); LOG((TL_ERROR, " The DLL will not be used")); FreeLibrary(pDll->hDll); return FALSE; } if ((pDll->dwAPIVersion > TAPI_VERSION_CURRENT) || (pDll->dwAPIVersion < TAPI_VERSION2_1)) { LOG((TL_INFO, "Management DLL %ls returned an invalid API version - x%lx", pDll->pszName, pDll->dwAPIVersion )); LOG((TL_INFO, " Will use version x%lx", TAPI_VERSION_CURRENT)); pDll->dwAPIVersion = TAPI_VERSION_CURRENT; } return TRUE; } // Only exists for TELE_SERVER, which implies NT and thus Unicode. As // such it is safe to assume that TCHAR == WCHAR for these. void ReadAndInitMapper() { PTMANAGEDLLINFO pMapperInfo; HKEY hKey; DWORD dwDataSize, dwDataType, dwCount; LPBYTE pHold; LONG lResult; assert( sizeof(TCHAR) == sizeof(WCHAR) ); if (!(TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) { return; } if ( ! ( pMapperInfo = ServerAlloc( sizeof(TMANAGEDLLINFO) ) ) ) { LOG((TL_ERROR, "ServerAlloc failed in ReadAndInitMap")); TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); return; } // grab server specific stuff from registry RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyServer, 0, KEY_ALL_ACCESS, &hKey ); dwDataSize = 0; RegQueryValueExW( hKey, gszMapperDll, 0, &dwDataType, NULL, &dwDataSize ); if (dwDataSize == 0) { LOG((TL_ERROR, "Cannot init client/server stuff (registry damaged?)")); RegCloseKey( hKey ); ServerFree(pMapperInfo); TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); return; } if (!(pHold = ServerAlloc(dwDataSize))) { LOG((TL_ERROR, "Alloc failed in ReadAndInitMap(o)")); TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); ServerFree(pMapperInfo); return; } RegQueryValueExW( hKey, gszMapperDll, 0, &dwDataType, pHold, &dwDataSize ); RegCloseKey( hKey ); // LOG((TL_INFO, "MapperDll is %ls", pHold)); if (!(pMapperInfo->hDll = LoadLibraryW((LPWSTR)pHold))) { LOG((TL_ERROR, "Serious internal failure loading client/server DLL . Error %lu", pHold, GetLastError())); ServerFree( pHold ); ServerFree( pMapperInfo ); TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); return; } // don't need these two for the mapper pMapperInfo->pNext = NULL; // save the name pMapperInfo->pszName = (LPWSTR)pHold; // get proc addresses for the first 5 api for (dwCount = 0; dwCount < 5; dwCount ++) { if (!(pMapperInfo->aProcs[dwCount] = (CLIENTPROC) GetProcAddress( pMapperInfo->hDll, gaszTCFuncNames[dwCount] ))) { // one of these addresses failed. remove DLL LOG((TL_INFO, "MapperDLL does not export %s. Server functionality disabled", gaszTCFuncNames[dwCount])); LOG((TL_INFO, "Disabling the Telephony server! (8)")); FreeLibrary(pMapperInfo->hDll); ServerFree(pMapperInfo->pszName); ServerFree(pMapperInfo); TapiGlobals.pMapperDll = NULL; TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); return; } } pMapperInfo->dwAPIVersion = TAPI_VERSION_CURRENT; lResult = (pMapperInfo->aProcs[TC_LOAD])( &pMapperInfo->dwAPIVersion, ManagementAddLineProc, ManagementAddPhoneProc, 0 ); if (lResult) { LOG((TL_INFO, "Client/server loadup - x%lx.", lResult)); FreeLibrary(pMapperInfo->hDll); ServerFree(pMapperInfo->pszName); ServerFree(pMapperInfo); TapiGlobals.pMapperDll = NULL; TapiGlobals.dwFlags &= ~(TAPIGLOBALS_SERVER); return; } if ((pMapperInfo->dwAPIVersion > TAPI_VERSION_CURRENT) || (pMapperInfo->dwAPIVersion < TAPI_VERSION2_1)) { LOG((TL_ERROR, "Internal version mismatch! Check that all components are in sync x%lx", pMapperInfo->dwAPIVersion)); LOG((TL_INFO, " Will use version x%lx", TAPI_VERSION_CURRENT)); pMapperInfo->dwAPIVersion = TAPI_VERSION_CURRENT; } TapiGlobals.pMapperDll = pMapperInfo; } LONG FreeOldDllListProc( PTMANAGEDLLLISTHEADER pDllList ) { PTMANAGEDLLINFO pDll, pNext; #if DBG DWORD dwCount = 0; #endif SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_LOWEST ); // wait until count is 0 while (pDllList->lCount > 0) { Sleep(100); #if DBG dwCount++; if (dwCount > 100) { LOG((TL_INFO, "FreeOldDllListProc still waiting after 10 seconds")); } #endif } EnterCriticalSection(&gManagementDllsCritSec); // walk the list pDll = pDllList->pFirst; while (pDll) { // free all resources if (pDll->hDll) { (pDll->aProcs[TC_FREE])(); FreeLibrary(pDll->hDll); } ServerFree(pDll->pszName); pNext = pDll->pNext; ServerFree(pDll); pDll = pNext; } // free header ServerFree(pDllList); LeaveCriticalSection(&gManagementDllsCritSec); return 0; } void ManagementProc( LONG l ) { HKEY hKey = NULL; DWORD dw, dwDSObjTTLTicks; HANDLE hEventNotify = NULL; HANDLE aHandles[2]; if (ERROR_SUCCESS != RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyServer, 0, KEY_READ, &hKey )) { LOG((TL_ERROR, "RegOpenKeyExW failed in ManagementProc")); goto ExitHere; } hEventNotify = CreateEvent (NULL, FALSE, FALSE, NULL); if (hEventNotify == NULL) { goto ExitHere; } aHandles[0] = hEventNotify; aHandles[1] = ghEventService; // Compute TAPISRV SCP refresh interval in ticks // gdwTapiSCPTTL is expressed in terms of minutes dwDSObjTTLTicks = gdwTapiSCPTTL * 60 * 1000 / 2; while (TRUE) { RegNotifyChangeKeyValue( hKey, TRUE, REG_NOTIFY_CHANGE_LAST_SET, hEventNotify, TRUE ); dw = WaitForMultipleObjects ( sizeof(aHandles) / sizeof(HANDLE), aHandles, FALSE, dwDSObjTTLTicks ); if (dw == WAIT_OBJECT_0) { // Notified of the registry change ReadAndInitManagementDlls(); } else if (dw == WAIT_OBJECT_0 + 1) { // the service is shutting down, update // DS about this and break out UpdateTapiSCP (FALSE, NULL, NULL); break; } else if (dw == WAIT_TIMEOUT) { // Time to refresh our DS registration now UpdateTapiSCP (TRUE, NULL, NULL); } } ExitHere: if (hKey) { RegCloseKey(hKey); } if (hEventNotify) { CloseHandle (hEventNotify); } } ////////////////////////////////////////////////////////////////////// // // ReadAndInitManagementDLLs() // // This procedure will read the management dll list from the registry // It will then go through that list, and create a linked list of // TMANAGEDLLINFO structures to hold all the info about those DLLs // // If there is already a list of these DLLs in TapiGlobals, this procedure // will then go through that list and determine which of the old DLLs // are in the new list. For the matches, it will simply copy over // the info about that DLL, and zero out the fields in the old list // // It will go through the new list. Entries that are not already // filled in will get initialized. // // Then it will save the new list in TapiGlobals. // // If an old list existed, it will create a thread that will wait // for this old list to be freed // // The procedure isn't real efficient, but I believe it's thread safe. // Additionally, changing the security DLLs should happen very infrequently, // and the list of DLLs should be very short. // ////////////////////////////////////////////////////////////////////// void ReadAndInitManagementDlls() { DWORD dwDataSize, dwDataType, dwTID; HKEY hKey; LPWSTR pDLLs, pHold1, pHold2; DWORD dwCount = 0; PTMANAGEDLLINFO pManageDll, pHoldDll, pNewHoldDll, pPrevDll, pTempDll; PTMANAGEDLLLISTHEADER pNewDllList = NULL, pHoldDllList; BOOL bBreak = FALSE; // // If it's not a server, we have no business here. // if (!(TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) { return; } EnterCriticalSection(&gManagementDllsCritSec); // get info from registry RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyServer, 0, KEY_ALL_ACCESS, &hKey ); dwDataSize = 0; RegQueryValueExW( hKey, gszManagementDlls, 0, &dwDataType, NULL, &dwDataSize ); if (dwDataSize == 0) { LOG((TL_ERROR, "No management DLLs present on this server")); // if there was previously a list // free it. if (TapiGlobals.pManageDllList) { HANDLE hThread; pHoldDllList = TapiGlobals.pManageDllList; EnterCriticalSection( &gDllListCritSec ); TapiGlobals.pManageDllList = NULL; LeaveCriticalSection( &gDllListCritSec ); // create a thread to wait for the // list and free it hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)FreeOldDllListProc, pHoldDllList, 0, &dwTID ); CloseHandle( hThread ); } RegCloseKey( hKey ); LeaveCriticalSection(&gManagementDllsCritSec); return; } if (!(pDLLs = ServerAlloc(dwDataSize))) { RegCloseKey( hKey ); LeaveCriticalSection(&gManagementDllsCritSec); return; } RegQueryValueExW( hKey, gszManagementDlls, 0, &dwDataType, (LPBYTE)pDLLs, &dwDataSize ); RegCloseKey( hKey ); // alloc new list header and first element if (!(pNewDllList = (PTMANAGEDLLLISTHEADER) ServerAlloc( sizeof( TMANAGEDLLLISTHEADER ) ) ) ) { ServerFree( pDLLs ); LeaveCriticalSection(&gManagementDllsCritSec); return; } pNewDllList->lCount = 0; if (!(pNewDllList->pFirst = ServerAlloc( sizeof( TMANAGEDLLINFO ) ) ) ) { ServerFree( pDLLs ); ServerFree( pNewDllList ); LeaveCriticalSection(&gManagementDllsCritSec); return; } // now, go through the list of dll names and initialize // the new TMANAGEDLLINFO list pHold1 = pHold2 = pDLLs; pManageDll = pNewDllList->pFirst; while (TRUE) { // find end or " while (*pHold1 && *pHold1 != L'"') pHold1++; // null terminate name if (*pHold1) { *pHold1 = '\0'; } else { bBreak = TRUE; } LOG((TL_INFO, "Management DLL %d is %ls", dwCount, pHold2)); // alloc space for name and procaddresses pManageDll->pszName = ServerAlloc( ( lstrlenW( pHold2 ) + 1 ) * sizeof (WCHAR) ); if (!pManageDll->pszName) { goto ExitHere; } // save name wcscpy( pManageDll->pszName, pHold2 ); // save ID pManageDll->dwID = gdwDllIDs++; // if we're at the end of the list, // break out if (bBreak) break; // otherwise, skip over null pHold1++; // save beginning of next name pHold2 = pHold1; // inc count dwCount++; // prepare next buffer if (!(pManageDll->pNext = ServerAlloc( sizeof ( TMANAGEDLLINFO ) ) ) ) { goto ExitHere; } pManageDll = pManageDll->pNext; } // if an old list exists, walk through and copy over Dlls that have // not changed pHoldDllList = TapiGlobals.pManageDllList; if (pHoldDllList) { pHoldDll = pHoldDllList->pFirst; while (pHoldDll) { pNewHoldDll = pNewDllList->pFirst; // walk through list of new dlls while (pNewHoldDll) { // if they are the same if (!lstrcmpiW( pNewHoldDll->pszName, pHoldDll->pszName ) ) { // save info memcpy( pNewHoldDll->aProcs, pHoldDll->aProcs, sizeof( pHoldDll->aProcs ) ); pNewHoldDll->hDll = pHoldDll->hDll; pNewHoldDll->dwID = pHoldDll->dwID; // NULL old hDll so we know that // we have it pHoldDll->hDll = NULL; break; } pNewHoldDll = pNewHoldDll->pNext; } // while pNewHoldDll pHoldDll = pHoldDll->pNext; } // while pHoldDll } // walk through the new list and init items that // have not been initialized already pNewHoldDll = pNewDllList->pFirst; pPrevDll = NULL; while (pNewHoldDll) { if (!pNewHoldDll->hDll) { // try to load the new dll if (!LoadNewDll(pNewHoldDll)) { // it failed if (pPrevDll) { pPrevDll->pNext = pNewHoldDll->pNext; ServerFree(pNewHoldDll); pNewHoldDll = pPrevDll; } else { pNewDllList->pFirst = pNewHoldDll->pNext; ServerFree(pNewHoldDll); pNewHoldDll = pNewDllList->pFirst; continue; } } } // next dll pPrevDll = pNewHoldDll; pNewHoldDll = pNewHoldDll->pNext; } if (pNewDllList->pFirst == NULL) { // all the DLLs failed to load, or the DLL list was empty ServerFree( pNewDllList ); pNewDllList = NULL; } // save old list pointer pHoldDllList = TapiGlobals.pManageDllList; // replace the list EnterCriticalSection( &gDllListCritSec ); TapiGlobals.pManageDllList = pNewDllList; pNewDllList = NULL; LeaveCriticalSection( &gDllListCritSec ); if (pHoldDllList) { HANDLE hThread; // create a thread to wait for the // list and free it hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)FreeOldDllListProc, pHoldDllList, 0, &dwTID ); CloseHandle( hThread ); } ExitHere: ServerFree( pDLLs ); // Error during pNewDllList allocation if (pNewDllList != NULL) { pManageDll = pNewDllList->pFirst; while (pManageDll != NULL) { pTempDll = pManageDll; pManageDll = pManageDll->pNext; ServerFree (pTempDll->pszName); ServerFree (pTempDll); } ServerFree( pNewDllList ); } LeaveCriticalSection(&gManagementDllsCritSec); return; } void GetManageDllListPointer( PTMANAGEDLLLISTHEADER * ppDllList ) { EnterCriticalSection( &gDllListCritSec ); if (TapiGlobals.pManageDllList != NULL) { TapiGlobals.pManageDllList->lCount++; } *ppDllList = TapiGlobals.pManageDllList; LeaveCriticalSection( &gDllListCritSec ); } void FreeManageDllListPointer( PTMANAGEDLLLISTHEADER pDllList ) { EnterCriticalSection( &gDllListCritSec ); if (pDllList != NULL) { pDllList->lCount--; if ( pDllList->lCount < 0 ) { LOG((TL_INFO, "pDllList->lCount is less than 0 - pDllList %p", pDllList)); } } LeaveCriticalSection( &gDllListCritSec ); } #endif void PASCAL SetMediaModesPriorityList( HKEY hKeyPri, PRILISTSTRUCT * pPriList ) { DWORD dwCount; for (dwCount = 0; dwCount<TapiGlobals.dwUsedPriorityLists; dwCount++) { TCHAR szName[REGNAMESIZE]; if ( (NULL == pPriList[dwCount].pszPriList) || (L'\0' == *(pPriList[dwCount].pszPriList)) ) { // What if there USED TO be an entry, but the app setpri to 0, then this // entry would be '\0', but the registry entry would still be there. continue; } wsprintf( szName, TEXT("%d"), pPriList[dwCount].dwMediaModes ); TAPIRegSetValueExW( hKeyPri, szName, 0, REG_SZ, (LPBYTE)( (pPriList[dwCount].pszPriList) + 1 ), (lstrlenW(pPriList[dwCount].pszPriList)) * sizeof (WCHAR) ); } } void PASCAL SetPriorityList( HKEY hKeyHandoffPriorities, const TCHAR *pszListName, WCHAR *pszPriorityList ) { if (pszPriorityList == NULL) { // // There is no pri list for this media mode or ReqXxxCall, // so delete any existing value from the registry // RegDeleteValue (hKeyHandoffPriorities, pszListName); } else { // // Add the pri list to the registry (note that we don't // add the preceding '"') // TAPIRegSetValueExW( hKeyHandoffPriorities, pszListName, 0, REG_SZ, (LPBYTE)(pszPriorityList + 1), lstrlenW (pszPriorityList) * sizeof (WCHAR) ); } } LONG ServerShutdown( void ) { DWORD i, j; PTPROVIDER ptProvider; // // Reset the flag that says it's ok to queue sp events, & then wait // for the SPEventHandlerThread(s) to clean up the SP event queue(s) // gbQueueSPEvents = FALSE; // // Set a reasonable cap on the max time we'll sit here // Don't wait for a message to be dispatched if called // from "net stop tapisrv" // i = 10 * 20; // 200 * 100msecs = 20 seconds while (i && !gbSPEventHandlerThreadExit) { for (j = 0; j < gdwNumSPEventHandlerThreads; j++) { if (!IsListEmpty (&aSPEventHandlerThreadInfo[j].ListHead)) { break; } } if (j == gdwNumSPEventHandlerThreads) { break; } Sleep (100); i--; } // // For each provider call the shutdown proc & then unload // ptProvider = TapiGlobals.ptProviders; while (ptProvider) { PTPROVIDER ptNextProvider = ptProvider->pNext; LONG lResult; lResult = CallSP2( ptProvider->apfn[SP_PROVIDERSHUTDOWN], "providerShutdown", SP_FUNC_SYNC, (DWORD)ptProvider->dwSPIVersion, (DWORD)ptProvider->dwPermanentProviderID ); FreeLibrary (ptProvider->hDll); MyCloseMutex (ptProvider->hMutex); CloseHandle (ptProvider->hHashTableReaderEvent); DeleteCriticalSection (&ptProvider->HashTableCritSec); ServerFree (ptProvider->pHashTable); ServerFree (ptProvider); ptProvider = ptNextProvider; } TapiGlobals.ptProviders = NULL; // // Clean up lookup tables // while (TapiGlobals.pLineLookup) { PTLINELOOKUPTABLE pLookup = TapiGlobals.pLineLookup; for (i = 0; i < pLookup->dwNumUsedEntries; i++) { if (!pLookup->aEntries[i].bRemoved) { MyCloseMutex (pLookup->aEntries[i].hMutex); } } TapiGlobals.pLineLookup = pLookup->pNext; ServerFree (pLookup); } while (TapiGlobals.pPhoneLookup) { PTPHONELOOKUPTABLE pLookup = TapiGlobals.pPhoneLookup; for (i = 0; i < pLookup->dwNumUsedEntries; i++) { if (!pLookup->aEntries[i].bRemoved) { MyCloseMutex (pLookup->aEntries[i].hMutex); } } TapiGlobals.pPhoneLookup = pLookup->pNext; ServerFree (pLookup); } { TCHAR szPerfNumLines[] = TEXT("Perf1"); TCHAR szPerfNumPhones[] =TEXT("Perf2"); HKEY hKeyTelephony; DWORD dwValue; if (ERROR_SUCCESS == RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyTelephony, 0, KEY_ALL_ACCESS, &hKeyTelephony )) { dwValue = TapiGlobals.dwNumLines + 'PERF'; RegSetValueEx( hKeyTelephony, szPerfNumLines, 0, REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD) ); dwValue = TapiGlobals.dwNumPhones + 'PERF'; RegSetValueEx( hKeyTelephony, szPerfNumPhones, 0, REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD) ); RegCloseKey(hKeyTelephony); } } // // Reset globals // TapiGlobals.dwFlags &= ~(TAPIGLOBALS_REINIT); { PPERMANENTIDARRAYHEADER pIDArray = TapiGlobals.pIDArrays, pArrayHold; while (pIDArray) { ServerFree (pIDArray->pLineElements); ServerFree (pIDArray->pPhoneElements); pArrayHold = pIDArray->pNext; ServerFree (pIDArray); pIDArray = pArrayHold; } TapiGlobals.pIDArrays = NULL; if (gpLineInfoList) { ServerFree (gpLineInfoList); gpLineInfoList = NULL; ZeroMemory (&gftLineLastWrite, sizeof(gftLineLastWrite)); } if (gpPhoneInfoList) { ServerFree (gpPhoneInfoList); gpPhoneInfoList = NULL; ZeroMemory (&gftPhoneLastWrite, sizeof(gftPhoneLastWrite)); } if (gpLineDevFlags) { ServerFree (gpLineDevFlags); gpLineDevFlags = NULL; gdwNumFlags = 0; } gbLockMMCWrite = FALSE; OnProxySCPShutdown (); } return 0; } void WINAPI GetAsyncEvents( PTCLIENT ptClient, PGETEVENTS_PARAMS pParams, DWORD dwParamsBufferSize, LPBYTE pDataBuf, LPDWORD pdwNumBytesReturned ) { DWORD dwMoveSize, dwMoveSizeWrapped; LOG((TL_TRACE, "GetAsyncEvents: enter (TID=%d)", GetCurrentThreadId())); LOG((TL_INFO, "M ebfused:x%lx pEvtBuf: 0x%p pDataOut:0x%p pDataIn:0x%p", ptClient->dwEventBufferUsedSize, ptClient->pEventBuffer, ptClient->pDataOut, ptClient->pDataIn )); // // Verify size/offset/string params given our input buffer/size // if (pParams->dwTotalBufferSize > dwParamsBufferSize) { pParams->lResult = LINEERR_OPERATIONFAILED; return; } // // Copy data from ptClient's event buffer // // An optimization to be made is to alert client (via dwNeededSize) // that it might want to alloc a larger buffer when msg traffic is // real high // if (WaitForExclusiveClientAccess (ptClient)) { _TryAgain: if (ptClient->dwEventBufferUsedSize == 0) { if (!IS_REMOTE_CLIENT (ptClient)) { ResetEvent (ptClient->hValidEventBufferDataEvent); } pParams->dwNeededBufferSize = pParams->dwUsedBufferSize = 0; *pdwNumBytesReturned = sizeof (TAPI32_MSG); RESET_FLAG (ptClient->dwFlags, PTCLIENT_FLAG_SKIPFIRSTMESSAGE); goto GetAsyncEvents_releaseMutex; } if (ptClient->pDataOut < ptClient->pDataIn) { dwMoveSize = (DWORD) (ptClient->pDataIn - ptClient->pDataOut); dwMoveSizeWrapped = 0; } else { dwMoveSize = ptClient->dwEventBufferTotalSize - (DWORD) (ptClient->pDataOut - ptClient->pEventBuffer); dwMoveSizeWrapped = (DWORD) (ptClient->pDataIn - ptClient->pEventBuffer); } if (ptClient->dwEventBufferUsedSize <= pParams->dwTotalBufferSize) { // // If here the size of the queued event data is less than the // client buffer size, so we can just blast the bits into the // client buffer & return. Also make sure to reset the "events // pending" event // CopyMemory (pDataBuf, ptClient->pDataOut, dwMoveSize); if (dwMoveSizeWrapped) { CopyMemory( pDataBuf + dwMoveSize, ptClient->pEventBuffer, dwMoveSizeWrapped ); } ptClient->dwEventBufferUsedSize = 0; ptClient->pDataOut = ptClient->pDataIn = ptClient->pEventBuffer; RESET_FLAG (ptClient->dwFlags, PTCLIENT_FLAG_SKIPFIRSTMESSAGE); if (!IS_REMOTE_CLIENT (ptClient)) { ResetEvent (ptClient->hValidEventBufferDataEvent); } pParams->dwNeededBufferSize = pParams->dwUsedBufferSize = dwMoveSize + dwMoveSizeWrapped; *pdwNumBytesReturned = sizeof (TAPI32_MSG) + pParams->dwUsedBufferSize; } else { // // If here the size of the queued event data exceeds that // of the client buffer. Since our events aren't all the // same size we need to copy them over one by one, making // sure we don't overflow the client buffer. Don't reset // the "events pending" event, so async events thread will // call us again as soon as it's done processing messages // in the buffer. // DWORD dwBytesLeftInClientBuffer = pParams->dwTotalBufferSize, dwDataOffset = 0, dwDataOffsetWrapped = 0; DWORD dwTotalMoveSize = dwMoveSize; LOG((TL_TRACE, "GetAsyncEvents: event data exceeds client buffer")); pParams->dwNeededBufferSize = ptClient->dwEventBufferUsedSize; while (1) { DWORD dwMsgSize = (DWORD) ((PASYNCEVENTMSG) (ptClient->pDataOut + dwDataOffset))->TotalSize; if (dwMsgSize > dwBytesLeftInClientBuffer) { if ((pParams->dwUsedBufferSize = dwDataOffset) != 0) { ptClient->dwEventBufferUsedSize -= dwDataOffset; ptClient->pDataOut += dwDataOffset; } else { // // Special case: the 1st msg is bigger than the entire // buffer // if (IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_SKIPFIRSTMESSAGE)) { DWORD dwBytesToTheEndOfTheBuffer = ptClient->dwEventBufferTotalSize - (DWORD)(ptClient->pDataOut - ptClient->pEventBuffer); // This is the second time the client tries to get // this message, with too small a buffer. We can // assume that the client cannot allocate enough // memory, so skip this message... RESET_FLAG(ptClient->dwFlags, PTCLIENT_FLAG_SKIPFIRSTMESSAGE); if (dwMsgSize > dwBytesToTheEndOfTheBuffer) { // This means that this message wraps around... dwBytesToTheEndOfTheBuffer = dwMsgSize - dwBytesToTheEndOfTheBuffer; ptClient->pDataOut = ptClient->pEventBuffer + dwBytesToTheEndOfTheBuffer; } else { ptClient->pDataOut += dwMsgSize; } ptClient->dwEventBufferUsedSize -= dwMsgSize; goto _TryAgain; } else { // Set the flag, so next time we'll skip the message // if the buffer will still be too small. SET_FLAG(ptClient->dwFlags, PTCLIENT_FLAG_SKIPFIRSTMESSAGE); } } *pdwNumBytesReturned = sizeof (TAPI32_MSG) + pParams->dwUsedBufferSize; goto GetAsyncEvents_releaseMutex; } dwBytesLeftInClientBuffer -= dwMsgSize; if (dwMsgSize <= dwMoveSize) { // // Msg isn't wrapped, a single copy will do // CopyMemory( pDataBuf + dwDataOffset, ptClient->pDataOut + dwDataOffset, dwMsgSize ); // // Check to see if the msg ran to the end of the buffer, // & break to the wrapped data code if so // if ((dwDataOffset += dwMsgSize) >= dwTotalMoveSize) { ptClient->pDataOut = ptClient->pEventBuffer; break; } } else { // // This msg is wrapped. We need to do two copies, then // break out of this loop to the wrapped data code // CopyMemory( pDataBuf + dwDataOffset, ptClient->pDataOut + dwDataOffset, dwMoveSize ); dwDataOffset += dwMoveSize; CopyMemory( pDataBuf + dwDataOffset, ptClient->pEventBuffer, dwMsgSize - dwMoveSize ); dwDataOffset += ( dwMsgSize - dwMoveSize); ptClient->pDataOut = ptClient->pEventBuffer + (dwMsgSize - dwMoveSize); break; } dwMoveSize -= dwMsgSize; } while (1) { DWORD dwMsgSize = (DWORD) ((PASYNCEVENTMSG) (ptClient->pDataOut + dwDataOffsetWrapped))->TotalSize; if (dwMsgSize > dwBytesLeftInClientBuffer) { ptClient->dwEventBufferUsedSize -= dwDataOffset; ptClient->pDataOut += dwDataOffsetWrapped; pParams->dwUsedBufferSize = dwDataOffset; *pdwNumBytesReturned = sizeof (TAPI32_MSG) + pParams->dwUsedBufferSize; goto GetAsyncEvents_releaseMutex; } // // Msg isn't wrapped, a single copy will do // CopyMemory( pDataBuf + dwDataOffset, ptClient->pDataOut + dwDataOffsetWrapped, dwMsgSize ); dwDataOffset += dwMsgSize; dwDataOffsetWrapped += dwMsgSize; dwBytesLeftInClientBuffer -= dwMsgSize; } } LOG((TL_TRACE, "GetAsyncEvents: return dwUsedBufferSize:x%lx", pParams->dwUsedBufferSize )); GetAsyncEvents_releaseMutex: if (ptClient->MsgPendingListEntry.Flink) { // // This is a remote Dg client. // // If there is no more data in the event buffer then remove // this client from the DgClientMsgPendingList(Head) so the // EventNotificationThread will stop monitoring it. // // Else, update the tClient's Retry & EventsRetrieved tick // counts. // if (ptClient->dwEventBufferUsedSize == 0) { EnterCriticalSection (&gDgClientMsgPendingCritSec); RemoveEntryList (&ptClient->MsgPendingListEntry); ptClient->MsgPendingListEntry.Flink = ptClient->MsgPendingListEntry.Blink = NULL; LeaveCriticalSection (&gDgClientMsgPendingCritSec); } else { ptClient->dwDgEventsRetrievedTickCount = GetTickCount(); ptClient->dwDgRetryTimeoutTickCount = ptClient->dwDgEventsRetrievedTickCount + 3 * DGCLIENT_TIMEOUT; } } UNLOCKTCLIENT (ptClient); } } void WINAPI GetUIDllName( PTCLIENT ptClient, PGETUIDLLNAME_PARAMS pParams, DWORD dwParamsBufferSize, LPBYTE pDataBuf, LPDWORD pdwNumBytesReturned ) { LONG lResult = 0; TSPIPROC pfnTSPI_providerUIIdentify = (TSPIPROC) NULL; PTAPIDIALOGINSTANCE ptDlgInst = (PTAPIDIALOGINSTANCE) NULL; PTLINELOOKUPENTRY pLookupEntry = NULL; DWORD dwObjectID = pParams->dwObjectID; LOG((TL_TRACE, "Entering GetUIDllName")); switch (pParams->dwObjectType) { case TUISPIDLL_OBJECT_LINEID: { #if TELE_SERVER if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { if (pParams->dwObjectID >= ptClient->dwLineDevices) { pParams->lResult = LINEERR_OPERATIONFAILED; return; } dwObjectID = ptClient->pLineDevices[pParams->dwObjectID]; } #endif if (TapiGlobals.dwNumLineInits == 0 ) { lResult = LINEERR_UNINITIALIZED; break; } pLookupEntry = GetLineLookupEntry (dwObjectID); if (!pLookupEntry) { lResult = (TapiGlobals.dwNumLineInits == 0 ? LINEERR_UNINITIALIZED : LINEERR_BADDEVICEID); } else if (!pLookupEntry->ptProvider || pLookupEntry->bRemoved) { lResult = LINEERR_NODEVICE; } else if (!(pfnTSPI_providerUIIdentify = pLookupEntry->ptProvider->apfn[SP_PROVIDERUIIDENTIFY])) { lResult = LINEERR_OPERATIONUNAVAIL; } break; } case TUISPIDLL_OBJECT_PHONEID: { #if TELE_SERVER if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { if (pParams->dwObjectID >= ptClient->dwPhoneDevices) { pParams->lResult = PHONEERR_OPERATIONFAILED; return; } dwObjectID = ptClient->pPhoneDevices[pParams->dwObjectID]; } #endif if (TapiGlobals.dwNumPhoneInits == 0 ) { lResult = PHONEERR_UNINITIALIZED; break; } pLookupEntry = (PTLINELOOKUPENTRY) GetPhoneLookupEntry (dwObjectID); if (!pLookupEntry) { lResult = (TapiGlobals.dwNumPhoneInits == 0 ? PHONEERR_UNINITIALIZED : PHONEERR_BADDEVICEID); } else if (!pLookupEntry->ptProvider || pLookupEntry->bRemoved) { lResult = PHONEERR_NODEVICE; } else if (!(pfnTSPI_providerUIIdentify = pLookupEntry->ptProvider->apfn[SP_PROVIDERUIIDENTIFY])) { lResult = PHONEERR_OPERATIONUNAVAIL; } break; } case TUISPIDLL_OBJECT_PROVIDERID: LOG((TL_INFO, "Looking for provider...")); #if TELE_SERVER // Provider add/remove needs to be restricted to Admins. if (!IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR) && (pParams->bRemoveProvider || pParams->dwProviderFilenameOffset != TAPI_NO_DATA)) { lResult = LINEERR_OPERATIONFAILED; goto GetUIDllName_return; } #endif if (!(ptDlgInst = ServerAlloc (sizeof (TAPIDIALOGINSTANCE)))) { lResult = LINEERR_NOMEM; goto GetUIDllName_return; } ptDlgInst->htDlgInst = NewObject(ghHandleTable, ptDlgInst, NULL); if (0 == ptDlgInst->htDlgInst) { ServerFree (ptDlgInst); lResult = LINEERR_NOMEM; goto GetUIDllName_return; } if (pParams->dwProviderFilenameOffset == TAPI_NO_DATA) { // // This is a providerConfig or -Remove request. Loop thru the // list of installed providers, trying to find one with a // matching PPID. // int i, iNumProviders; TCHAR szProviderXxxN[32]; HKEY hKeyProviders; DWORD dwDataSize; DWORD dwDataType; DWORD dwTemp; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ) != ERROR_SUCCESS) { LOG((TL_ERROR, "RegOpenKeyEx(/Providers) failed, err=%d", GetLastError() )); DereferenceObject (ghHandleTable, ptDlgInst->htDlgInst, 1); lResult = LINEERR_OPERATIONFAILED; goto GetUIDllName_return; } dwDataSize = sizeof(iNumProviders); iNumProviders = 0; RegQueryValueEx( hKeyProviders, gszNumProviders, 0, &dwDataType, (LPBYTE) &iNumProviders, &dwDataSize ); for (i = 0; i < iNumProviders; i++) { wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderID, i); dwDataSize = sizeof(dwTemp); dwTemp = 0; RegQueryValueEx( hKeyProviders, szProviderXxxN, 0, &dwDataType, (LPBYTE)&dwTemp, &dwDataSize ); if (dwTemp == pParams->dwObjectID) { // // We found the provider, try to load it & get ptrs // to the relevant funcs // TCHAR szProviderFilename[MAX_PATH]; wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderFilename, i); dwDataSize = MAX_PATH*sizeof(TCHAR); RegQueryValueEx( hKeyProviders, szProviderXxxN, 0, &dwDataType, (LPBYTE)szProviderFilename, &dwDataSize ); if (!(ptDlgInst->hTsp = LoadLibrary(szProviderFilename))) { LOG((TL_ERROR, "LoadLibrary('%s') failed - err=%d", szProviderFilename, GetLastError() )); lResult = LINEERR_OPERATIONFAILED; goto clean_up_dlg_inst; } if (!(pfnTSPI_providerUIIdentify = (TSPIPROC) GetProcAddress( ptDlgInst->hTsp, (LPCSTR) gaszTSPIFuncNames[SP_PROVIDERUIIDENTIFY] ))) { LOG((TL_ERROR, "GetProcAddress(TSPI_providerUIIdentify) " \ "on [%s] failed, err=%d", szProviderFilename, GetLastError() )); lResult = LINEERR_OPERATIONUNAVAIL; goto clean_up_dlg_inst; } ptDlgInst->pfnTSPI_providerGenericDialogData = (TSPIPROC) GetProcAddress( ptDlgInst->hTsp, (LPCSTR) gaszTSPIFuncNames[SP_PROVIDERGENERICDIALOGDATA] ); ptDlgInst->dwPermanentProviderID = pParams->dwObjectID; ptDlgInst->bRemoveProvider = pParams->bRemoveProvider; break; } } RegCloseKey (hKeyProviders); if (i == iNumProviders) { LOG((TL_ERROR, "Ran out of list...")); lResult = LINEERR_INVALPARAM; } } else { // // This is a providerInstall request. Try to load the provider // and get ptrs to the relevant funcs, then retrieve & increment // the next provider ID value in the ini file (careful to wrap // next PPID at 64K-1). // TCHAR *pszProviderFilename; DWORD dwNameLength; HKEY hKeyProviders; DWORD dwDataSize; DWORD dwDataType; DWORD dwTemp; // // Verify size/offset/string params given our input buffer/size // if (IsBadStringParam( dwParamsBufferSize, pDataBuf, pParams->dwProviderFilenameOffset )) { pParams->lResult = LINEERR_OPERATIONFAILED; DereferenceObject (ghHandleTable, ptDlgInst->htDlgInst, 1); return; } pszProviderFilename = (PTSTR)(pDataBuf + pParams->dwProviderFilenameOffset); if (!(ptDlgInst->hTsp = LoadLibrary(pszProviderFilename))) { LOG((TL_ERROR, "LoadLibrary('%s') failed err=%d", pszProviderFilename, GetLastError() )); lResult = LINEERR_OPERATIONFAILED; // note: no matter if the XxxProvider call succeeds or fails, // we want this goto statement. // 16bit service providers are completely handled // in the XxxProvider call. goto clean_up_dlg_inst; } if (!(pfnTSPI_providerUIIdentify = (TSPIPROC) GetProcAddress( ptDlgInst->hTsp, (LPCSTR) gaszTSPIFuncNames[SP_PROVIDERUIIDENTIFY] ))) { lResult = LINEERR_OPERATIONUNAVAIL; goto clean_up_dlg_inst; } dwNameLength = (lstrlen(pszProviderFilename) + 1) * sizeof(TCHAR); if (!(ptDlgInst->pszProviderFilename = ServerAlloc (dwNameLength))) { lResult = LINEERR_NOMEM; goto clean_up_dlg_inst; } CopyMemory( ptDlgInst->pszProviderFilename, pszProviderFilename, dwNameLength ); ptDlgInst->pfnTSPI_providerGenericDialogData = (TSPIPROC) GetProcAddress( ptDlgInst->hTsp, (LPCSTR) gaszTSPIFuncNames[SP_PROVIDERGENERICDIALOGDATA] ); RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ); dwDataSize = sizeof (DWORD); ptDlgInst->dwPermanentProviderID = 1; RegQueryValueEx( hKeyProviders, gszNextProviderID, 0, &dwDataType, (LPBYTE) &(ptDlgInst->dwPermanentProviderID), &dwDataSize ); pParams->dwObjectID = ptDlgInst->dwPermanentProviderID; dwTemp = ((ptDlgInst->dwPermanentProviderID+1) & 0xffff0000) ? 1 : (ptDlgInst->dwPermanentProviderID + 1); RegSetValueEx( hKeyProviders, gszNextProviderID, 0, REG_DWORD, (LPBYTE) &dwTemp, sizeof(DWORD) ); RegCloseKey (hKeyProviders); } break; } if (pfnTSPI_providerUIIdentify) { if (pLookupEntry && (lstrcmpi( pLookupEntry->ptProvider->szFileName, TEXT("remotesp.tsp") ) == 0) ) { // ok - hack alert // a special case for remotesp to give it more info // we're passing the device ID and device type over to remotesp // so it can intelligently call over to the remote tapisrv // the RSP_MSG is just a key for remotesp to // check to make sure that the info is there LPDWORD lpdwHold = (LPDWORD)pDataBuf; lpdwHold[0] = RSP_MSG; lpdwHold[1] = dwObjectID; lpdwHold[2] = pParams->dwObjectType; } if ((lResult = CallSP1( pfnTSPI_providerUIIdentify, "providerUIIdentify", SP_FUNC_SYNC, (ULONG_PTR) pDataBuf )) == 0) { pParams->dwUIDllNameOffset = 0; pParams->dwUIDllNameSize = (lstrlenW((PWSTR)pDataBuf) + 1)*sizeof(WCHAR); *pdwNumBytesReturned = sizeof (TAPI32_MSG) + pParams->dwUIDllNameSize; if (ptDlgInst) { ptDlgInst->dwKey = TDLGINST_KEY; if ((ptDlgInst->pNext = ptClient->pProviderXxxDlgInsts)) { ptDlgInst->pNext->pPrev = ptDlgInst; } ptClient->pProviderXxxDlgInsts = ptDlgInst; pParams->htDlgInst = ptDlgInst->htDlgInst; } } else if (ptDlgInst) { clean_up_dlg_inst: if (ptDlgInst->hTsp) { FreeLibrary (ptDlgInst->hTsp); } if (ptDlgInst->pszProviderFilename) { ServerFree (ptDlgInst->pszProviderFilename); } DereferenceObject (ghHandleTable, ptDlgInst->htDlgInst, 1); } } GetUIDllName_return: pParams->lResult = lResult; } void WINAPI TUISPIDLLCallback( PTCLIENT ptClient, PUIDLLCALLBACK_PARAMS pParams, DWORD dwParamsBufferSize, LPBYTE pDataBuf, LPDWORD pdwNumBytesReturned ) { LONG lResult; ULONG_PTR objectID = pParams->ObjectID; TSPIPROC pfnTSPI_providerGenericDialogData = NULL; // // Verify size/offset/string params given our input buffer/size // if (ISBADSIZEOFFSET( dwParamsBufferSize, 0, pParams->dwParamsInSize, pParams->dwParamsInOffset, sizeof(DWORD), "TUISPIDLLCallback", "pParams->ParamsIn" )) { pParams->lResult = LINEERR_OPERATIONFAILED; return; } switch (pParams->dwObjectType) { case TUISPIDLL_OBJECT_LINEID: { PTLINELOOKUPENTRY pLine; #if TELE_SERVER if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { if ((DWORD) pParams->ObjectID >= ptClient->dwLineDevices) { pParams->lResult = LINEERR_OPERATIONFAILED; return; } objectID = ptClient->pLineDevices[pParams->ObjectID]; } #endif pLine = GetLineLookupEntry ((DWORD) objectID); if (!pLine) { lResult = LINEERR_INVALPARAM; } else if (!pLine->ptProvider) { lResult = LINEERR_OPERATIONFAILED; } else { pfnTSPI_providerGenericDialogData = pLine->ptProvider->apfn[SP_PROVIDERGENERICDIALOGDATA]; } break; } case TUISPIDLL_OBJECT_PHONEID: { PTPHONELOOKUPENTRY pPhone; #if TELE_SERVER if ((TapiGlobals.dwFlags & TAPIGLOBALS_SERVER) && !IS_FLAG_SET(ptClient->dwFlags, PTCLIENT_FLAG_ADMINISTRATOR)) { if ((DWORD) pParams->ObjectID >= ptClient->dwPhoneDevices) { pParams->lResult = PHONEERR_OPERATIONFAILED; return; } objectID = ptClient->pPhoneDevices[pParams->ObjectID]; } #endif pPhone = GetPhoneLookupEntry ((DWORD) objectID); if (!pPhone) { lResult = LINEERR_INVALPARAM; } else if (!pPhone->ptProvider) { lResult = LINEERR_OPERATIONFAILED; } else { pfnTSPI_providerGenericDialogData = pPhone->ptProvider->apfn[SP_PROVIDERGENERICDIALOGDATA]; } break; } case TUISPIDLL_OBJECT_PROVIDERID: { PTAPIDIALOGINSTANCE ptDlgInst = ptClient->pProviderXxxDlgInsts; while (ptDlgInst) { if ((DWORD) pParams->ObjectID == ptDlgInst->dwPermanentProviderID) { pfnTSPI_providerGenericDialogData = ptDlgInst->pfnTSPI_providerGenericDialogData; break; } ptDlgInst = ptDlgInst->pNext; } break; } case TUISPIDLL_OBJECT_DIALOGINSTANCE: { PTAPIDIALOGINSTANCE ptDlgInst; try { ptDlgInst = ReferenceObject (ghHandleTable, pParams->ObjectID, TDLGINST_KEY); if (NULL == ptDlgInst) { pfnTSPI_providerGenericDialogData = NULL; break; } objectID = (ULONG_PTR)ptDlgInst->hdDlgInst; pfnTSPI_providerGenericDialogData = ptDlgInst->ptProvider->apfn[SP_PROVIDERGENERICDIALOGDATA]; DereferenceObject (ghHandleTable, pParams->ObjectID, 1); } myexcept { // just fall thru } break; } } if (pfnTSPI_providerGenericDialogData) { if ((lResult = CallSP4( pfnTSPI_providerGenericDialogData, "providerGenericDialogData", SP_FUNC_SYNC, (ULONG_PTR) objectID, (DWORD)pParams->dwObjectType, (ULONG_PTR) (pDataBuf + pParams->dwParamsInOffset), (DWORD)pParams->dwParamsInSize )) == 0) { pParams->dwParamsOutOffset = pParams->dwParamsInOffset; pParams->dwParamsOutSize = pParams->dwParamsInSize; *pdwNumBytesReturned = sizeof (TAPI32_MSG) + pParams->dwParamsOutSize + pParams->dwParamsOutOffset; } } else { lResult = LINEERR_OPERATIONFAILED; } pParams->lResult = lResult; } void WINAPI FreeDialogInstance( PTCLIENT ptClient, PFREEDIALOGINSTANCE_PARAMS pParams, DWORD dwParamsBufferSize, LPBYTE pDataBuf, LPDWORD pdwNumBytesReturned ) { HKEY hKeyProviders; DWORD dwDataSize; DWORD dwDataType; DWORD dwTemp; PTAPIDIALOGINSTANCE ptDlgInst = ReferenceObject (ghHandleTable, pParams->htDlgInst, TDLGINST_KEY); LOG((TL_TRACE, "FreeDialogInstance: enter, pDlgInst=x%p", ptDlgInst)); try { if (ptDlgInst->dwKey != TDLGINST_KEY) { pParams->lResult = LINEERR_OPERATIONFAILED; } else { ptDlgInst->dwKey = INVAL_KEY; } } myexcept { pParams->lResult = LINEERR_OPERATIONFAILED; } if (pParams->lResult) { return; } if (ptDlgInst->hTsp) { // // This dlg inst was a client doing a providerConfig, -Install, or // -Remove // if (ptDlgInst->pszProviderFilename) { if (pParams->lUIDllResult == 0) { // // Successful provider install // DWORD iNumProviders; TCHAR szProviderXxxN[32]; TCHAR szProviderXxxNA[32]; WaitForSingleObject (ghProvRegistryMutex, INFINITE); if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ) != ERROR_SUCCESS) { ReleaseMutex (ghProvRegistryMutex); goto bail; } dwDataSize = sizeof(iNumProviders); iNumProviders = 0; RegQueryValueEx( hKeyProviders, gszNumProviders, 0, &dwDataType, (LPBYTE) &iNumProviders, &dwDataSize ); wsprintf( szProviderXxxNA, TEXT("%s%d"), gszProviderID, iNumProviders ); RegSetValueEx( hKeyProviders, szProviderXxxNA, 0, REG_DWORD, (LPBYTE) &ptDlgInst->dwPermanentProviderID, sizeof(DWORD) ); wsprintf( szProviderXxxN, TEXT("%s%d"), gszProviderFilename, iNumProviders ); RegSetValueEx( hKeyProviders, szProviderXxxN, 0, REG_SZ, (LPBYTE) ptDlgInst->pszProviderFilename, (lstrlen((PTSTR)ptDlgInst->pszProviderFilename) + 1)*sizeof(TCHAR) ); iNumProviders++; RegSetValueEx( hKeyProviders, gszNumProviders, 0, REG_DWORD, (LPBYTE) &iNumProviders, sizeof(DWORD) ); RegCloseKey( hKeyProviders ); ReleaseMutex (ghProvRegistryMutex); // // If the tapisrv is already INITed, ReInit it to load the provider // TapiEnterCriticalSection (&TapiGlobals.CritSec); if ((TapiGlobals.dwNumLineInits != 0) || (TapiGlobals.dwNumPhoneInits != 0) || (TapiGlobals.dwFlags & TAPIGLOBALS_SERVER)) { pParams->lResult = ServerInit(TRUE); } TapiLeaveCriticalSection (&TapiGlobals.CritSec); } else { // // Unsuccessful provider install. See if we can decrement // NextProviderID to free up the unused ID. // DWORD iNextProviderID; WaitForSingleObject (ghProvRegistryMutex, INFINITE); if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ) != ERROR_SUCCESS) { ReleaseMutex (ghProvRegistryMutex); goto bail; } dwDataSize = sizeof(iNextProviderID); iNextProviderID = 0; RegQueryValueEx( hKeyProviders, gszNextProviderID, 0, &dwDataType, (LPBYTE)&iNextProviderID, &dwDataSize ); if ((ptDlgInst->dwPermanentProviderID + 1) == iNextProviderID) { RegSetValueEx( hKeyProviders, gszNextProviderID, 0, REG_DWORD, (LPBYTE) &(ptDlgInst->dwPermanentProviderID), sizeof(DWORD) ); } RegCloseKey (hKeyProviders); ReleaseMutex (ghProvRegistryMutex); } ServerFree (ptDlgInst->pszProviderFilename); } else if (ptDlgInst->bRemoveProvider) { if (pParams->lUIDllResult == 0) { // // Successful provider remove. Find the index of the // provider in the list, then move all the providers // that follow up a notch. // DWORD iNumProviders, i; TCHAR szProviderXxxN[32]; TCHAR buf[MAX_PATH]; WaitForSingleObject (ghProvRegistryMutex, INFINITE); if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, gszRegKeyProviders, 0, KEY_ALL_ACCESS, &hKeyProviders ) != ERROR_SUCCESS) { ReleaseMutex (ghProvRegistryMutex); goto bail; } dwDataSize = sizeof(iNumProviders); iNumProviders = 0; RegQueryValueEx( hKeyProviders, gszNumProviders, 0, &dwDataType, (LPBYTE) &iNumProviders, &dwDataSize ); for (i = 0; i < iNumProviders; i++) { wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderID, i); dwDataSize = sizeof(dwTemp); dwTemp = 0; RegQueryValueEx( hKeyProviders, szProviderXxxN, 0, &dwDataType, (LPBYTE) &dwTemp, &dwDataSize ); if (dwTemp == ptDlgInst->dwPermanentProviderID) { break; } } for (; i < (iNumProviders - 1); i++) { wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderID, i + 1); dwDataSize = sizeof(buf); RegQueryValueEx( hKeyProviders, szProviderXxxN, 0, &dwDataType, (LPBYTE) buf, &dwDataSize ); buf[dwDataSize/sizeof(TCHAR)] = TEXT('\0'); wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderID, i); RegSetValueEx( hKeyProviders, szProviderXxxN, 0, REG_DWORD, (LPBYTE) buf, sizeof (DWORD) ); wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderFilename, i+1); dwDataSize = MAX_PATH*sizeof(TCHAR); RegQueryValueEx( hKeyProviders, szProviderXxxN, 0, &dwDataType, (LPBYTE) buf, &dwDataSize ); buf[dwDataSize/sizeof(TCHAR)] = TEXT('\0'); wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderFilename, i); RegSetValueEx( hKeyProviders, szProviderXxxN, 0, REG_SZ, (LPBYTE) buf, (lstrlen(buf) + 1) * sizeof(TCHAR) ); } // // Remove the last ProviderID# & ProviderFilename# entries // wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderID, i); RegDeleteValue(hKeyProviders, szProviderXxxN); wsprintf(szProviderXxxN, TEXT("%s%d"), gszProviderFilename, i); RegDeleteValue(hKeyProviders, szProviderXxxN); // // Decrement the total num providers to load // iNumProviders--; RegSetValueEx( hKeyProviders, gszNumProviders, 0, REG_DWORD, (LPBYTE)&iNumProviders, sizeof(DWORD) ); RegCloseKey (hKeyProviders); ReleaseMutex (ghProvRegistryMutex); // // Remove user/line association with this provider // { WCHAR * pSectionNames = NULL; WCHAR * pSectionNames2 = NULL; WCHAR * pszLinePhoneSave = NULL; DWORD dwSize, dwSize2; DWORD dwResult; WCHAR szBuf[20]; WCHAR * aszKeys[] = {gszLines, gszPhones}; // Only NT server cares about tsec.ini if (!gbNTServer) { goto Exit; } // Get the list of DomainUser names LOG((TL_INFO, "FreeDialogInstance: getting user names")); do { if (pSectionNames) { ServerFree (pSectionNames); dwSize *= 2; } else { dwSize = 256; } if (!(pSectionNames = ServerAlloc (dwSize * sizeof (WCHAR)))) { goto Exit; } pSectionNames[0] = L'\0'; dwResult = GetPrivateProfileSectionNamesW( pSectionNames, dwSize, gszFileName ); } while (dwResult >= (dwSize - 2)); pSectionNames2 = pSectionNames; dwSize = 64 * sizeof(WCHAR); pszLinePhoneSave = ServerAlloc(dwSize); if (pszLinePhoneSave == NULL) { LOG((TL_ERROR, "FreeDialogInstance: Memory failure")); goto Exit; } dwSize2 = wsprintfW (szBuf, L"%d", ptDlgInst->dwPermanentProviderID); // Remove all the devices associated with this domain/user while (*pSectionNames) { WCHAR *psz, *psz2; BOOL bWriteBack; int iasz; for (iasz = 0; iasz < sizeof(aszKeys) / sizeof(WCHAR *); ++iasz) { bWriteBack = FALSE; dwResult = MyGetPrivateProfileString( pSectionNames, aszKeys[iasz], gszEmptyString, &pszLinePhoneSave, &dwSize); if (dwResult == 0) { psz = pszLinePhoneSave; while (*psz) { if (wcsncmp(psz, szBuf, dwSize2) == 0) { bWriteBack = TRUE; psz2 = psz + dwSize2; if (*psz2 != L',') // Comma? { LOG((TL_ERROR, "FreeDialogInstance: " "Corrupted tsec.ini")); goto Exit; } ++ psz2; // Skip comma // Skip the permanent device ID while ((*psz2 != L',') && (*psz2 != 0)) { ++psz2; } if (*psz2 == 0) // Last one { if (psz > pszLinePhoneSave) *(psz - 1) = 0; else *pszLinePhoneSave = 0; break; } else { int i = 0; ++psz2; // skip the comma while (*psz2) { psz[i++] = *psz2; ++psz2; } psz[i] = 0; } } else { // Skip the provider ID while ((*psz != 0) && (*psz != L',')) { ++ psz; } if (*psz == 0) break; ++ psz; // Skip the permanent device ID while ((*psz != 0) && (*psz != L',')) { ++ psz; } if (*psz == 0) break; ++ psz; } } if (bWriteBack) { WritePrivateProfileStringW( pSectionNames, aszKeys[iasz], pszLinePhoneSave, gszFileName ); } } // dwResult == 0 } // Advance to the next domain user while (*pSectionNames != 0) { ++pSectionNames; } ++pSectionNames; } Exit: ServerFree(pSectionNames2); ServerFree(pszLinePhoneSave); } // // if tapi init'd shutdown each provider // { PTLINELOOKUPENTRY pLineEntry; PTPHONELOOKUPENTRY pPhoneEntry; DWORD dw; PTPROVIDER ptProvider; PPERMANENTIDARRAYHEADER pIDArray, *ppLastArray; PTPROVIDER *pptProvider; // // LINE_REMOVE / PHONE_REMOVE will try to enter gMgmtCritSec while in // TapiGlobals.CritSec. // Need to enter gMgmtCritSec here, to avoid deadlock // EnterCriticalSection (&gMgmtCritSec); TapiEnterCriticalSection (&TapiGlobals.CritSec); // // Find ptProvider // ptProvider = TapiGlobals.ptProviders; while (ptProvider) { if (ptProvider->dwPermanentProviderID == ptDlgInst->dwPermanentProviderID) { break; } ptProvider = ptProvider->pNext; } if (ptProvider == NULL) { LeaveCriticalSection (&gMgmtCritSec); TapiLeaveCriticalSection (&TapiGlobals.CritSec); goto bail; } // // Remove all the lines/phones belong to this provider. // for (dw = 0; dw < TapiGlobals.dwNumLines; ++dw) { pLineEntry = GetLineLookupEntry (dw); if (pLineEntry && pLineEntry->ptProvider == ptProvider && !pLineEntry->bRemoved) { LineEventProc ( 0, 0, LINE_REMOVE, dw, 0, 0 ); } } for (dw = 0; dw < TapiGlobals.dwNumPhones; ++dw) { pPhoneEntry = GetPhoneLookupEntry (dw); if (pPhoneEntry && pPhoneEntry->ptProvider == ptProvider && !pPhoneEntry->bRemoved) { PhoneEventProc ( 0, PHONE_REMOVE, dw, 0, 0 ); } } LeaveCriticalSection (&gMgmtCritSec); // // Remove the provider ID array associate with this provider // ppLastArray = &(TapiGlobals.pIDArrays); while ((*ppLastArray) != NULL && ((*ppLastArray)->dwPermanentProviderID != ptProvider->dwPermanentProviderID) ) { ppLastArray = &((*ppLastArray)->pNext); } if (pIDArray = (*ppLastArray)) { *ppLastArray = pIDArray->pNext; ServerFree (pIDArray->pLineElements); ServerFree (pIDArray->pPhoneElements); ServerFree (pIDArray); } else { // Should not be here } // // Remove ptProvider from the global link list // if (ptProvider->pNext) { ptProvider->pNext->pPrev = ptProvider->pPrev; } if (ptProvider->pPrev) { ptProvider->pPrev->pNext = ptProvider->pNext; } else { TapiGlobals.ptProviders = ptProvider->pNext; } // // Now shutdown and unload the TSP provider // CallSP2( ptProvider->apfn[SP_PROVIDERSHUTDOWN], "providerShutdown", SP_FUNC_SYNC, (DWORD)ptProvider->dwSPIVersion, (DWORD)ptProvider->dwPermanentProviderID ); // Wait for 5 seconds for ongoing calls to finish Sleep (5000); FreeLibrary (ptProvider->hDll); MyCloseMutex (ptProvider->hMutex); CloseHandle (ptProvider->hHashTableReaderEvent); DeleteCriticalSection (&ptProvider->HashTableCritSec); ServerFree (ptProvider->pHashTable); ServerFree (ptProvider); TapiLeaveCriticalSection (&TapiGlobals.CritSec); } } else { // // Unsuccessful provider remove, nothing to do // } } else { // // Nothing to do for providerConfig (success or fail) // } bail: FreeLibrary (ptDlgInst->hTsp); pParams->lResult = pParams->lUIDllResult; } else if (ptDlgInst->ptProvider->apfn[SP_PROVIDERFREEDIALOGINSTANCE]) { // // The was a provider-initiated dlg inst, so tell // the provider to free it's inst // CallSP1( ptDlgInst->ptProvider->apfn[SP_PROVIDERFREEDIALOGINSTANCE], "providerFreeDialogInstance", SP_FUNC_SYNC, (ULONG_PTR) ptDlgInst->hdDlgInst ); } // // Remove the dialog instance from the tClient's list & then free it // if (WaitForExclusiveClientAccess (ptClient)) { if (ptDlgInst->pNext) { ptDlgInst->pNext->pPrev = ptDlgInst->pPrev; } if (ptDlgInst->pPrev) { ptDlgInst->pPrev->pNext = ptDlgInst->pNext; } else if (ptDlgInst->hTsp) { ptClient->pProviderXxxDlgInsts = ptDlgInst->pNext; } else { ptClient->pGenericDlgInsts = ptDlgInst->pNext; } UNLOCKTCLIENT (ptClient); } DereferenceObject (ghHandleTable, pParams->htDlgInst, 2); } BOOL GetNewClientHandle( PTCLIENT ptClient, PTMANAGEDLLINFO pDll, HMANAGEMENTCLIENT *phClient ) { BOOL fResult = TRUE; PTCLIENTHANDLE pClientHandle, pNewClientHandle; if (!(pNewClientHandle = ServerAlloc (sizeof (TCLIENTHANDLE)))) { return FALSE; } pNewClientHandle->pNext = NULL; pNewClientHandle->fValid = TRUE; pNewClientHandle->dwID = pDll->dwID; // call init if ((pDll->aProcs[TC_CLIENTINITIALIZE])( ptClient->pszDomainName, ptClient->pszUserName, ptClient->pszComputerName, &pNewClientHandle->hClient )) { // error - zero out the handle pNewClientHandle->hClient = (HMANAGEMENTCLIENT) NULL; pNewClientHandle->fValid = FALSE; fResult = FALSE; } // save it no matter what // insert at beginning of list pClientHandle = ptClient->pClientHandles; ptClient->pClientHandles = pNewClientHandle; pNewClientHandle->pNext = pClientHandle; *phClient = pNewClientHandle->hClient; return fResult; } BOOL GetTCClient( PTMANAGEDLLINFO pDll, PTCLIENT ptClient, DWORD dwAPI, HMANAGEMENTCLIENT *phClient ) { PTCLIENTHANDLE pClientHandle; BOOL bResult; if (!pDll->aProcs[dwAPI]) { return FALSE; } pClientHandle = ptClient->pClientHandles; while (pClientHandle) { if (pClientHandle->dwID == pDll->dwID) { break; } pClientHandle = pClientHandle->pNext; } if (pClientHandle) { if (!(pClientHandle->fValid)) { return FALSE; } *phClient = pClientHandle->hClient; return TRUE; } else { // OK - it's not in the list. // get the critical section & check again EnterCriticalSection(&gClientHandleCritSec); pClientHandle = ptClient->pClientHandles; while (pClientHandle) { if (pClientHandle->dwID == pDll->dwID) { break; } pClientHandle = pClientHandle->pNext; } if (pClientHandle) { if (!(pClientHandle->fValid)) { LeaveCriticalSection(&gClientHandleCritSec); return FALSE; } *phClient = pClientHandle->hClient; LeaveCriticalSection(&gClientHandleCritSec); return TRUE; } // still not there. add it... bResult = GetNewClientHandle( ptClient, pDll, phClient ); LeaveCriticalSection(&gClientHandleCritSec); return bResult; } } //#pragma warning (default:4028) #if DBG char szBeforeSync[] = "Calling TSPI_%s"; char szBeforeAsync[] = "Calling TSPI_%s, dwReqID=x%x"; char szAfter[] = "TSPI_%s result=%s"; VOID DbgPrt( IN DWORD dwDbgLevel, IN PUCHAR lpszFormat, IN ... ) /*++ Routine Description: Formats the incoming debug message & calls DbgPrint Arguments: DbgLevel - level of message verboseness DbgMessage - printf-style format string, followed by appropriate list of arguments Return Value: --*/ { if (dwDbgLevel <= gdwDebugLevel) { char buf[1024] = "TAPISRV (0x--------): "; va_list ap; wsprintfA( &buf[11], "%08lx", GetCurrentThreadId() ); buf[19] = ')'; va_start(ap, lpszFormat); wvsprintfA( &buf[22], lpszFormat, ap ); lstrcatA(buf, "\n"); OutputDebugStringA (buf); va_end(ap); } return; } char *aszLineErrors[] = { NULL, "ALLOCATED", "BADDEVICEID", "BEARERMODEUNAVAIL", "inval err value (0x80000004)", // 0x80000004 isn't valid err code "CALLUNAVAIL", "COMPLETIONOVERRUN", "CONFERENCEFULL", "DIALBILLING", "DIALDIALTONE", "DIALPROMPT", "DIALQUIET", "INCOMPATIBLEAPIVERSION", "INCOMPATIBLEEXTVERSION", "INIFILECORRUPT", "INUSE", "INVALADDRESS", // 0x80000010 "INVALADDRESSID", "INVALADDRESSMODE", "INVALADDRESSSTATE", "INVALAPPHANDLE", "INVALAPPNAME", "INVALBEARERMODE", "INVALCALLCOMPLMODE", "INVALCALLHANDLE", "INVALCALLPARAMS", "INVALCALLPRIVILEGE", "INVALCALLSELECT", "INVALCALLSTATE", "INVALCALLSTATELIST", "INVALCARD", "INVALCOMPLETIONID", "INVALCONFCALLHANDLE", // 0x80000020 "INVALCONSULTCALLHANDLE", "INVALCOUNTRYCODE", "INVALDEVICECLASS", "INVALDEVICEHANDLE", "INVALDIALPARAMS", "INVALDIGITLIST", "INVALDIGITMODE", "INVALDIGITS", "INVALEXTVERSION", "INVALGROUPID", "INVALLINEHANDLE", "INVALLINESTATE", "INVALLOCATION", "INVALMEDIALIST", "INVALMEDIAMODE", "INVALMESSAGEID", // 0x80000030 "inval err value (0x80000031)", // 0x80000031 isn't valid err code "INVALPARAM", "INVALPARKID", "INVALPARKMODE", "INVALPOINTER", "INVALPRIVSELECT", "INVALRATE", "INVALREQUESTMODE", "INVALTERMINALID", "INVALTERMINALMODE", "INVALTIMEOUT", "INVALTONE", "INVALTONELIST", "INVALTONEMODE", "INVALTRANSFERMODE", "LINEMAPPERFAILED", // 0x80000040 "NOCONFERENCE", "NODEVICE", "NODRIVER", "NOMEM", "NOREQUEST", "NOTOWNER", "NOTREGISTERED", "OPERATIONFAILED", "OPERATIONUNAVAIL", "RATEUNAVAIL", "RESOURCEUNAVAIL", "REQUESTOVERRUN", "STRUCTURETOOSMALL", "TARGETNOTFOUND", "TARGETSELF", "UNINITIALIZED", // 0x80000050 "USERUSERINFOTOOBIG", "REINIT", "ADDRESSBLOCKED", "BILLINGREJECTED", "INVALFEATURE", "NOMULTIPLEINSTANCE", "INVALAGENTID", "INVALAGENTGROUP", "INVALPASSWORD", "INVALAGENTSTATE", "INVALAGENTACTIVITY", "DIALVOICEDETECT" }; char *aszPhoneErrors[] = { "SUCCESS", "ALLOCATED", "BADDEVICEID", "INCOMPATIBLEAPIVERSION", "INCOMPATIBLEEXTVERSION", "INIFILECORRUPT", "INUSE", "INVALAPPHANDLE", "INVALAPPNAME", "INVALBUTTONLAMPID", "INVALBUTTONMODE", "INVALBUTTONSTATE", "INVALDATAID", "INVALDEVICECLASS", "INVALEXTVERSION", "INVALHOOKSWITCHDEV", "INVALHOOKSWITCHMODE", // 0x90000010 "INVALLAMPMODE", "INVALPARAM", "INVALPHONEHANDLE", "INVALPHONESTATE", "INVALPOINTER", "INVALPRIVILEGE", "INVALRINGMODE", "NODEVICE", "NODRIVER", "NOMEM", "NOTOWNER", "OPERATIONFAILED", "OPERATIONUNAVAIL", "inval err value (0x9000001e)", // 0x9000001e isn't valid err code "RESOURCEUNAVAIL", "REQUESTOVERRUN", // 0x90000020 "STRUCTURETOOSMALL", "UNINITIALIZED", "REINIT" }; char *aszTapiErrors[] = { "SUCCESS", "DROPPED", "NOREQUESTRECIPIENT", "REQUESTQUEUEFULL", "INVALDESTADDRESS", "INVALWINDOWHANDLE", "INVALDEVICECLASS", "INVALDEVICEID", "DEVICECLASSUNAVAIL", "DEVICEIDUNAVAIL", "DEVICEINUSE", "DESTBUSY", "DESTNOANSWER", "DESTUNAVAIL", "UNKNOWNWINHANDLE", "UNKNOWNREQUESTID", "REQUESTFAILED", "REQUESTCANCELLED", "INVALPOINTER" }; char * PASCAL MapResultCodeToText( LONG lResult, char *pszResult ) { if (lResult == 0) { wsprintfA (pszResult, "SUCCESS"); } else if (lResult > 0) { wsprintfA (pszResult, "x%x (completing async)", lResult); } else if (((DWORD) lResult) <= LINEERR_DIALVOICEDETECT) { lResult &= 0x0fffffff; wsprintfA (pszResult, "LINEERR_%s", aszLineErrors[lResult]); } else if (((DWORD) lResult) <= PHONEERR_REINIT) { if (((DWORD) lResult) >= PHONEERR_ALLOCATED) { lResult &= 0x0fffffff; wsprintfA (pszResult, "PHONEERR_%s", aszPhoneErrors[lResult]); } else { goto MapResultCodeToText_badErrorCode; } } else if (((DWORD) lResult) <= ((DWORD) TAPIERR_DROPPED) && ((DWORD) lResult) >= ((DWORD) TAPIERR_INVALPOINTER)) { lResult = ~lResult + 1; wsprintfA (pszResult, "TAPIERR_%s", aszTapiErrors[lResult]); } else { MapResultCodeToText_badErrorCode: wsprintfA (pszResult, "inval error value (x%x)"); } return pszResult; } VOID PASCAL ValidateSyncSPResult( LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, LONG lResult ) { char szResult[32]; LOG((TL_INFO, szAfter, lpszFuncName, MapResultCodeToText (lResult, szResult) )); if (dwFlags & SP_FUNC_ASYNC) { assert (lResult != 0); if (lResult > 0) { assert (lResult == PtrToLong (Arg1) || PtrToLong (Arg1) == 0xfeeefeee || // pAsyncRequestInfo freed PtrToLong (Arg1) == 0xa1a1a1a1); } } else { assert (lResult <= 0); } } LONG WINAPI CallSP1( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1 ) { LONG lResult; LOG((TL_INFO, szBeforeSync, lpszFuncName)); lResult = (*pfn)(Arg1); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP2( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP3( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP4( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP5( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4, Arg5); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP6( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5, ULONG_PTR Arg6 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP7( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5, ULONG_PTR Arg6, ULONG_PTR Arg7 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP8( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5, ULONG_PTR Arg6, ULONG_PTR Arg7, ULONG_PTR Arg8 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP9( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5, ULONG_PTR Arg6, ULONG_PTR Arg7, ULONG_PTR Arg8, ULONG_PTR Arg9 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } LONG WINAPI CallSP12( TSPIPROC pfn, LPCSTR lpszFuncName, DWORD dwFlags, ULONG_PTR Arg1, ULONG_PTR Arg2, ULONG_PTR Arg3, ULONG_PTR Arg4, ULONG_PTR Arg5, ULONG_PTR Arg6, ULONG_PTR Arg7, ULONG_PTR Arg8, ULONG_PTR Arg9, ULONG_PTR Arg10, ULONG_PTR Arg11, ULONG_PTR Arg12 ) { LONG lResult; if (dwFlags & SP_FUNC_ASYNC) { LOG((TL_INFO, szBeforeAsync, lpszFuncName, Arg1)); } else { LOG((TL_INFO, szBeforeSync, lpszFuncName)); } lResult = (*pfn)( Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12 ); ValidateSyncSPResult (lpszFuncName, dwFlags, Arg1, lResult); return lResult; } #endif // DBG /*************************************************************************\ * BOOL InitPerf() * * Initialize global performance data * \**************************************************************************/ BOOL InitPerf() { FillMemory(&PerfBlock, sizeof(PerfBlock), 0); return(TRUE); } BOOL VerifyDomainName (HKEY hKey) { #define MAX_DNS_NAME_LENGTH 255 DWORD dwType; DWORD dwSize; BOOL bReturn = TRUE; LPTSTR pOldName = NULL; LPTSTR pNewName = NULL; do { // // Get the old domain name from registry // dwSize = 0; if (ERROR_SUCCESS == RegQueryValueEx( hKey, gszDomainName, NULL, &dwType, NULL, &dwSize) ) { pOldName = ServerAlloc (dwSize); if(!pOldName) { bReturn = FALSE; break; } if (ERROR_SUCCESS != RegQueryValueEx( hKey, gszDomainName, NULL, &dwType, (LPBYTE)pOldName, &dwSize) ) { bReturn = FALSE; break; } } // // Get the current domain name // dwSize = MAX_DNS_NAME_LENGTH + 1; pNewName = ServerAlloc ( dwSize * sizeof (TCHAR)); if (!pNewName) { bReturn = FALSE; break; } if (!GetComputerNameEx (ComputerNameDnsDomain, pNewName, &dwSize)) { bReturn = FALSE; LOG((TL_INFO, "VerifyDomainName: GetComputerNameEx failed - error x%x", GetLastError())); break; } if (dwSize == 0) { // no domain name, save as empty string pNewName [0] = TEXT('\0'); dwSize = 1; } if (!pOldName || _tcscmp(pOldName, pNewName)) { // // The domain has changed, save the new domain name // We also need to discard the old SCP // if (ERROR_SUCCESS != RegSetValueEx ( hKey, gszDomainName, 0, REG_SZ, (LPBYTE)pNewName, dwSize * sizeof(TCHAR) )) { LOG((TL_INFO, "VerifyDomainName:RegSetValueEx (%S) failed", pNewName)); } RegDeleteValue ( hKey, gszRegTapisrvSCPGuid ); } } while (0); ServerFree(pOldName); ServerFree(pNewName); return bReturn; }
27.061642
149
0.475353
[ "object" ]
23fe1c9c80193952b643d9f8da2bcdfc7f3de873
417
h
C
OnyxEngine/Engine/pch.h
MathiasZillo/OnyxEngine
40c678ad396a13ff32ca0cf7ad1568ec9a0559cd
[ "MIT" ]
null
null
null
OnyxEngine/Engine/pch.h
MathiasZillo/OnyxEngine
40c678ad396a13ff32ca0cf7ad1568ec9a0559cd
[ "MIT" ]
null
null
null
OnyxEngine/Engine/pch.h
MathiasZillo/OnyxEngine
40c678ad396a13ff32ca0cf7ad1568ec9a0559cd
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <algorithm> #include <vector> #include <memory> #include <cmath> #include <Windows.h> #define U8 uint_fast8_t #define U16 uint_fast16_t #define U32 uint_fast32_t #define U64 uint_fast64_t #define I8 int_fast8_t #define I16 int_fast16_t #define I32 int_fast32_t #define I64 int_fast64_t #define F32 float #define F64 double
18.954545
27
0.729017
[ "vector" ]
9b00aed45f18635f86245bad5db7013b8746472f
788
c
C
nitan/d/kunlun/npc/obj/bag1.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/d/kunlun/npc/obj/bag1.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/d/kunlun/npc/obj/bag1.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// bag.c #include <ansi.h>; inherit ITEM; void create() { set_name("油布包", ({ "bag", "bao" })); set_weight(200); if( clonep() ) set_default_object(__FILE__); else { set("unit", "個"); set("long", "這是一個油布包裹。\n"); set("value", 500); set("material", "cloth"); } set("book_count", 1); } void init() { if( this_player() == environment() ) { add_action("do_open", "open"); add_action("do_open", "unpack"); add_action("do_open", "dakai"); } } int do_open(string arg) { object me, book; object where; if ( !arg ) return 0; return notify_fail("油布包裏面什麼也沒有了。\n"); }
21.297297
48
0.445431
[ "object" ]
9b0521af257d169b0628753b24451acb1762c227
533
h
C
include/vrk/image_view.h
WilliamLewww/vulkan_research_kit
7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc
[ "Apache-2.0" ]
null
null
null
include/vrk/image_view.h
WilliamLewww/vulkan_research_kit
7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc
[ "Apache-2.0" ]
2
2021-12-06T01:56:35.000Z
2022-03-07T06:47:38.000Z
include/vrk/image_view.h
WilliamLewww/vulkan_research_kit
7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc
[ "Apache-2.0" ]
null
null
null
#pragma once #include "vrk/helper.h" #include <vulkan/vulkan.h> #include <vector> class ImageView { public: ImageView(VkDevice &deviceHandleRef, VkImage &imageHandleRef, VkImageViewCreateFlags imageViewCreateFlags, VkImageViewType imageViewType, VkFormat format, VkComponentMapping componentMapping, VkImageSubresourceRange imageSubresourceRange); ~ImageView(); VkImageView &getImageViewHandleRef(); private: VkImageView imageViewHandle; VkDevice &deviceHandleRef; };
21.32
63
0.73546
[ "vector" ]
9b06b6eb6c468b45ed1d240c91cc2390d0b5dd75
14,623
h
C
include/gazebo_custom_mavlink_interface.h
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-05-23T02:52:14.000Z
2021-05-23T02:52:14.000Z
include/gazebo_custom_mavlink_interface.h
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T18:52:15.000Z
2021-06-15T18:52:15.000Z
include/gazebo_custom_mavlink_interface.h
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T03:25:12.000Z
2021-06-15T03:25:12.000Z
/* * Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland * Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland * Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland * Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland * Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland * Copyright 2015-2018 PX4 Pro Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <regex> #include <thread> #include <mutex> #include <condition_variable> #include <deque> #include <atomic> #include <chrono> #include <memory> #include <sstream> #include <cassert> #include <stdexcept> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_array.hpp> #include <boost/system/system_error.hpp> #include <iostream> #include <random> #include <stdio.h> #include <math.h> #include <cstdlib> #include <string> #include <sys/socket.h> #include <netinet/in.h> #include <Eigen/Eigen> #include <gazebo/gazebo.hh> #include <gazebo/common/common.hh> #include <gazebo/common/Plugin.hh> #include <gazebo/physics/physics.hh> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <ignition/math.hh> #include <sdf/sdf.hh> #include <common.h> #include <Airspeed.pb.h> #include <CommandMotorSpeed.pb.h> #include <MotorSpeed.pb.h> #include <Imu.pb.h> //#include <OpticalFlow.pb.h> #include <Range.pb.h> #include <SITLGps.pb.h> #include <IRLock.pb.h> #include <Groundtruth.pb.h> #include <Odometry.pb.h> #include <MagneticField.pb.h> #include <Pressure.pb.h> #include <Wind.pb.h> // custom compiled messages ---------------------------------------------------- #include "TVCStatus.pb.h" #include "TVCTarget.pb.h" #include "NewXYStatus.pb.h" #include "RollPitchStatus.pb.h" #include "RollPitchSetpoint.pb.h" #include "ThrusterStatus.pb.h" #include "VehicleAngularRates.pb.h" // ----------------------------------------------------------------------------- #include "mavlink_interface.h" #include "msgbuffer.h" #include <fstream> //! Default distance sensor model joint naming static const std::regex kDefaultLidarModelJointNaming(".*(lidar|sf10a)(.*_joint)"); static const std::regex kDefaultSonarModelJointNaming(".*(sonar|mb1240-xl-ez4)(.*_joint)"); static const std::regex kDefaultGPSModelJointNaming(".*(gps|ublox-neo-7M)(.*_joint)"); namespace gazebo { typedef const boost::shared_ptr<const mav_msgs::msgs::CommandMotorSpeed> CommandMotorSpeedPtr; typedef const boost::shared_ptr<const nav_msgs::msgs::Odometry> OdomPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Airspeed> AirspeedPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Groundtruth> GtPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Imu> ImuPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::IRLock> IRLockPtr; //typedef const boost::shared_ptr<const sensor_msgs::msgs::OpticalFlow> OpticalFlowPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Range> SonarPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Range> LidarPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::SITLGps> GpsPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::MagneticField> MagnetometerPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::Pressure> BarometerPtr; typedef const boost::shared_ptr<const physics_msgs::msgs::Wind> WindPtr; // custom types ---------------------------------------------------------------- typedef const boost::shared_ptr<const sensor_msgs::msgs::TVCStatus> TVCStatusPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::NewXYStatus> NewXYStatusPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::RollPitchStatus> RollPitchStatusPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::RollPitchSetpoint> RollPitchSetpointPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::ThrusterStatus> ThrusterStatusPtr; typedef const boost::shared_ptr<const sensor_msgs::msgs::VehicleAngularRates> VehicleAngularRatesPtr; // ----------------------------------------------------------------------------- typedef std::pair<const int, const ignition::math::Quaterniond> SensorIdRot_P; typedef std::map<transport::SubscriberPtr, SensorIdRot_P > Sensor_M; // Default values static const std::string kDefaultNamespace = ""; // This just proxies the motor commands from command/motor_speed to the single motors via internal // ConsPtr passing, such that the original commands don't have to go n_motors-times over the wire. static const std::string kDefaultMotorVelocityReferencePubTopic = "/gazebo/command/motor_speed"; static const std::string kDefaultImuTopic = "/imu"; //static const std::string kDefaultOpticalFlowTopic = "/px4flow/link/opticalFlow"; static const std::string kDefaultIRLockTopic = "/camera/link/irlock"; static const std::string kDefaultVisionTopic = "/vision_odom"; static const std::string kDefaultMagTopic = "/mag"; static const std::string kDefaultAirspeedTopic = "/airspeed"; static const std::string kDefaultBarometerTopic = "/baro"; static const std::string kDefaultWindTopic = "/world_wind"; //! OR operation for the enumeration and unsigned types that returns the bitmask template<typename A, typename B> static inline uint32_t operator |(A lhs, B rhs) { // make it type safe static_assert((std::is_same<A, uint32_t>::value || std::is_same<A, SensorSource>::value), "first argument is not uint32_t or SensorSource enum type"); static_assert((std::is_same<B, uint32_t>::value || std::is_same<B, SensorSource>::value), "second argument is not uint32_t or SensorSource enum type"); return static_cast<uint32_t> ( static_cast<std::underlying_type<SensorSource>::type>(lhs) | static_cast<std::underlying_type<SensorSource>::type>(rhs) ); } class GazeboMavlinkInterface : public ModelPlugin { public: GazeboMavlinkInterface(); ~GazeboMavlinkInterface(); void Publish(); protected: void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf); void OnUpdate(const common::UpdateInfo& /*_info*/); private: // Additional Variables ----------------------------------------------------- std::vector<std::string> link_names; // -------------------------------------------------------------------------- int thisVariableIsNotUsed = 0; bool my_switch = true; bool received_first_actuator_; Eigen::VectorXd input_reference_; float protocol_version_; std::unique_ptr<MavlinkInterface> mavlink_interface_; std::string namespace_; std::string motor_velocity_reference_pub_topic_; std::string mavlink_control_sub_topic_; std::string link_name_; transport::NodePtr node_handle_; transport::PublisherPtr motor_velocity_reference_pub_; transport::SubscriberPtr mav_control_sub_; physics::ModelPtr model_; physics::WorldPtr world_; physics::JointPtr left_elevon_joint_; physics::JointPtr right_elevon_joint_; physics::JointPtr elevator_joint_; physics::JointPtr propeller_joint_; physics::JointPtr gimbal_yaw_joint_; physics::JointPtr gimbal_pitch_joint_; physics::JointPtr gimbal_roll_joint_; common::PID propeller_pid_; common::PID elevator_pid_; common::PID left_elevon_pid_; common::PID right_elevon_pid_; bool use_propeller_pid_; bool use_elevator_pid_; bool use_left_elevon_pid_; bool use_right_elevon_pid_; bool send_vision_estimation_; bool send_odometry_; std::vector<physics::JointPtr> joints_; std::vector<common::PID> pids_; std::vector<double> joint_max_errors_; /// \brief Pointer to the update event connection. event::ConnectionPtr updateConnection_; event::ConnectionPtr sigIntConnection_; void ImuCallback(ImuPtr& imu_msg); void GpsCallback(GpsPtr& gps_msg, const int& id); void GroundtruthCallback(GtPtr& groundtruth_msg); void LidarCallback(LidarPtr& lidar_msg); void SonarCallback(SonarPtr& sonar_msg, const int& id); //void OpticalFlowCallback(OpticalFlowPtr& opticalFlow_msg); void IRLockCallback(IRLockPtr& irlock_msg); void VisionCallback(OdomPtr& odom_msg); void MagnetometerCallback(MagnetometerPtr& mag_msg); void AirspeedCallback(AirspeedPtr& airspeed_msg); void BarometerCallback(BarometerPtr& baro_msg); void WindVelocityCallback(WindPtr& msg); void SendSensorMessages(); void SendGroundTruth(); void handle_actuator_controls(); void handle_control(double _dt); bool IsRunning(); void onSigInt(); // --------------------------------------------------------------------------- // Custom Mesage callbacks void TVCStatusCallback(TVCStatusPtr &msg); void NewXYStatusCallback(NewXYStatusPtr &msg); void RollPitchStatusCallback(RollPitchStatusPtr &msg); void RollPitchSetpointCallback(RollPitchSetpointPtr &msg); void ThrusterStatusCallback(ThrusterStatusPtr &msg); void VehicleAngularRatesCallback(VehicleAngularRatesPtr &msg); // send messages across plugins void sendTVCTarget(); void SendTVCStatus(); // send status as mavlink messages void SendActuatorStatus(); void SendNewXYStatus(); void SendRollPitchStatus(); void SendRollPitchSetpoint(); void SendThrusterStatus(); void SendThrusterYawStatus(); void SendVehicleAngularRates(); // status variables to store new parameters to send std::vector<double> _linear_actuator_target = {0, 0}; double _actuator_status_1; double _actuator_target_1; double _actuator_current_1; double _actuator_velocity_1; double _actuator_status_2; double _actuator_target_2; double _actuator_current_2; double _actuator_velocity_2; double _newX; double _newY; double _rollTarget; double _pitchTarget; double _rollSetpoint; double _pitchSetpoint; std::vector<double> _thrusterStatus = {0, 0, 0, 0}; std::vector<double> _thruster_yaw_status = {0, 0}; double _rates_roll; double _rates_pitch; double _rates_yaw; // --------------------------------------------------------------------------- /** * @brief Set the MAV_SENSOR_ORIENTATION enum value based on the sensor orientation * * @param[in] rootModel The root model where the sensor is attached * @param[in] u_Xs Unit vector of X-axis sensor in `base_link` frame * @param[in] sensor_msg The Mavlink DISTANCE_SENSOR message struct */ template <class T> void setMavlinkSensorOrientation(const ignition::math::Vector3d& u_Xs, T& sensor_msg); /** * @brief A helper class that allows the creation of multiple subscriptions to sensors. * It gets the sensor link/joint and creates the subscriptions based on those. * It also allows to set the initial rotation of the sensor, to allow computing * the sensor orientation quaternion. * @details GazeboMsgT The type of the message that will be subscribed to the Gazebo framework. */ template <typename GazeboMsgT> void CreateSensorSubscription( void (GazeboMavlinkInterface::*fp)(const boost::shared_ptr<GazeboMsgT const>&, const int&), GazeboMavlinkInterface* ptr, const physics::Joint_V& joints, const std::regex& model); static const unsigned n_out_max = 16; double input_offset_[n_out_max]; double input_scaling_[n_out_max]; std::string joint_control_type_[n_out_max]; std::string gztopic_[n_out_max]; double zero_position_disarmed_[n_out_max]; double zero_position_armed_[n_out_max]; int input_index_[n_out_max]; transport::PublisherPtr joint_control_pub_[n_out_max]; transport::SubscriberPtr imu_sub_; //transport::SubscriberPtr opticalFlow_sub_; transport::SubscriberPtr irlock_sub_; transport::SubscriberPtr groundtruth_sub_; transport::SubscriberPtr vision_sub_; transport::SubscriberPtr mag_sub_; transport::SubscriberPtr airspeed_sub_; transport::SubscriberPtr baro_sub_; transport::SubscriberPtr wind_sub_; // custom subscribers -------------------------------------------------------- transport::SubscriberPtr new_xy_status_sub_; transport::SubscriberPtr roll_pitch_status_sub_; transport::SubscriberPtr roll_pitch_setpoint_sub_; transport::SubscriberPtr thruster_status_sub_; transport::SubscriberPtr tvc_status_sub_; transport::SubscriberPtr vehicle_angular_rates_sub_; transport::SubscriberPtr lidar_sub_; // --------------------------------------------------------------------------- // TVC Target publisher transport::PublisherPtr tvc_target_pub_; Sensor_M sensor_map_; // Map of sensor SubscriberPtr, IDs and orientations std::string imu_sub_topic_; //std::string opticalFlow_sub_topic_; std::string irlock_sub_topic_; std::string groundtruth_sub_topic_; std::string vision_sub_topic_; std::string mag_sub_topic_; std::string airspeed_sub_topic_; std::string baro_sub_topic_; std::string wind_sub_topic_; // custom topic names -------------------------------------------------------- std::string tvc_status_sub_topic_; std::string thruster_sub_topic_; std::string roll_pitch_sub_topic_; std::string roll_pitch_setpoint_sub_topic_; std::string new_xy_sub_topic_; std::string vehicle_angular_rates_topic_; std::string tvc_target_pub_topic_; std::string lidar_sub_topic_; // --------------------------------------------------------------------------- std::mutex last_imu_message_mutex_ {}; std::condition_variable last_imu_message_cond_ {}; sensor_msgs::msgs::Imu last_imu_message_; common::Time last_time_; common::Time last_imu_time_; common::Time last_actuator_time_; bool mag_updated_; bool baro_updated_; bool diff_press_updated_; double groundtruth_lat_rad; double groundtruth_lon_rad; double groundtruth_altitude; double imu_update_interval_ = 0.004; ///< Used for non-lockstep ignition::math::Vector3d velocity_prev_W_; ignition::math::Vector3d mag_n_; ignition::math::Vector3d wind_vel_; double temperature_; double pressure_alt_; double abs_pressure_; bool close_conn_ = false; double optflow_distance; double sonar_distance; double diff_pressure_; bool enable_lockstep_ = false; double speed_factor_ = 1.0; int64_t previous_imu_seq_ = 0; unsigned update_skip_factor_ = 1; bool hil_mode_; bool hil_state_level_; }; }
35.753056
98
0.729946
[ "vector", "model" ]
9b0f00a2b45f55dc7654713165fff8699750c288
14,644
h
C
components/autofill/core/browser/form_data_importer.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
components/autofill/core/browser/form_data_importer.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
components/autofill/core/browser/form_data_importer.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2017 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 COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_DATA_IMPORTER_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_DATA_IMPORTER_H_ #include <map> #include <memory> #include <string> #include <utility> #include "base/gtest_prod_util.h" #include "build/build_config.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/payments/credit_card_save_manager.h" #include "components/autofill/core/browser/payments/local_card_migration_manager.h" #include "components/autofill/core/browser/payments/payments_client.h" #include "components/autofill/core/browser/payments/upi_vpa_save_manager.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "third_party/abseil-cpp/absl/types/optional.h" class SaveCardOfferObserver; namespace autofill { class AddressProfileSaveManager; // Manages logic for importing address profiles and credit card information from // web forms into the user's Autofill profile via the PersonalDataManager. // Owned by BrowserAutofillManager. class FormDataImporter { public: // Record type of the credit card imported from the form, if one exists. enum ImportedCreditCardRecordType { // No card was successfully imported from the form. NO_CARD, // The imported card is already stored locally on the device. LOCAL_CARD, // The imported card is already known to be a server card (either masked or // unmasked). SERVER_CARD, // The imported card is not currently stored with the browser. NEW_CARD, }; // The parameters should outlive the FormDataImporter. FormDataImporter(AutofillClient* client, payments::PaymentsClient* payments_client, PersonalDataManager* personal_data_manager, const std::string& app_locale); FormDataImporter(const FormDataImporter&) = delete; FormDataImporter& operator=(const FormDataImporter&) = delete; ~FormDataImporter(); // Imports the form data, submitted by the user, into // |personal_data_manager_|. If a new credit card was detected and // |credit_card_autofill_enabled| is set to |true|, also begins the process to // offer local or upload credit card save. void ImportFormData(const FormStructure& submitted_form, bool profile_autofill_enabled, bool credit_card_autofill_enabled); // Extract credit card from the form structure. This function allows for // duplicated field types in the form. CreditCard ExtractCreditCardFromForm(const FormStructure& form); // Checks suitability of |profile| for adding to the user's set of profiles. static bool IsValidLearnableProfile(const AutofillProfile& profile, const std::string& finch_country_code, const std::string& app_locale, LogBuffer* import_log_buffer); // Cache the last four of the fetched virtual card so we don't offer saving // them. void CacheFetchedVirtualCard(const std::u16string& last_four); #if !defined(OS_ANDROID) && !defined(OS_IOS) LocalCardMigrationManager* local_card_migration_manager() { return local_card_migration_manager_.get(); } #endif // #if !defined(OS_ANDROID) && !defined(OS_IOS) protected: // Exposed for testing. void set_credit_card_save_manager( std::unique_ptr<CreditCardSaveManager> credit_card_save_manager) { credit_card_save_manager_ = std::move(credit_card_save_manager); } #if !defined(OS_ANDROID) && !defined(OS_IOS) // Exposed for testing. void set_local_card_migration_manager( std::unique_ptr<LocalCardMigrationManager> local_card_migration_manager) { local_card_migration_manager_ = std::move(local_card_migration_manager); } #endif // #if !defined(OS_ANDROID) && !defined(OS_IOS) private: // Defines a candidate for address profile import. struct AddressProfileImportCandidate { // The profile that was extracted from the form. AutofillProfile profile; // The URL the profile was extracted from. GURL url; // Indicates if all import requirements have been fulfilled. bool all_requirements_fulfilled; AddressProfileImportCandidate(AddressProfileImportCandidate&& other) = default; AddressProfileImportCandidate& operator=( AddressProfileImportCandidate&& other) = default; }; // Scans the given |form| for importable Autofill data. If the form includes // sufficient address data for a new profile, it is immediately imported. If // the form includes sufficient credit card data for a new credit card and // |credit_card_autofill_enabled| is set to |true|, it is stored into // |imported_credit_card| so that we can prompt the user whether to save this // data. If the form contains credit card data already present in a local // credit card entry *and* |should_return_local_card| is true, the data is // stored into |imported_credit_card| so that we can prompt the user whether // to upload it. If the form contains UPI data and // |credit_card_autofill_enabled| is true, the UPI ID will be stored into // |imported_upi_id|. Returns |true| if sufficient address or credit card data // was found. Exposed for testing. bool ImportFormData(const FormStructure& form, bool profile_autofill_enabled, bool credit_card_autofill_enabled, bool should_return_local_card, std::unique_ptr<CreditCard>* imported_credit_card, std::vector<AddressProfileImportCandidate>& address_profile_import_candidates, absl::optional<std::string>* imported_upi_id); // Go through the |form| fields and attempt to extract and import valid // address profiles. Returns true on extraction success of at least one // profile. There are many reasons that extraction may fail (see // implementation). The function returns true if at least one complete // address profile was found. bool ImportAddressProfiles( const FormStructure& form, std::vector<AddressProfileImportCandidate>& import_candidates); // Helper method for ImportAddressProfiles which only considers the fields for // a specified |section|. If |section| is the empty string, the import is // performed on the union of all sections. bool ImportAddressProfileForSection( const FormStructure& form, const std::string& section, std::vector<AddressProfileImportCandidate>& import_candidates, LogBuffer* import_log_buffer); // Go through the |form| fields and attempt to extract a new credit card in // |imported_credit_card|, or update an existing card. // |should_return_local_card| will indicate whether |imported_credit_card| is // filled even if an existing card was updated. Success is defined as having // a new card to import, or having merged with an existing card. bool ImportCreditCard(const FormStructure& form, bool should_return_local_card, std::unique_ptr<CreditCard>* imported_credit_card); // Tries to initiate the saving of |imported_credit_card| if applicable. // |submitted_form| is the form from which the card was imported. // If a UPI id was found it is stored in |detected_upi_id|. // |credit_card_autofill_enabled| indicates if credit card filling is enabled // and |is_credit_card_upstream_enabled| indicates if server card storage is // enabled. Returns true if a save is initiated. bool ProcessCreditCardImportCandidate( const FormStructure& submitted_form, std::unique_ptr<CreditCard> imported_credit_card, absl::optional<std::string> detected_upi_id, bool credit_card_autofill_enabled, bool is_credit_card_upstream_enabled); // Processes the address profile import candidates. // |import_candidates| contains the addresses extracted from the form. // |allow_prompt| denotes if a prompt can be shown. // Returns true if the import of a complete profile is initiated. bool ProcessAddressProfileImportCandidates( const std::vector<AddressProfileImportCandidate>& import_candidates, bool allow_prompt = true); // Extracts credit card from the form structure. |hasDuplicateFieldType| will // be set as true if there are duplicated field types in the form. CreditCard ExtractCreditCardFromForm(const FormStructure& form, bool* hasDuplicateFieldType); // Go through the |form| fields and find a UPI ID to import. The return value // will be empty if no UPI ID was found. absl::optional<std::string> ImportUpiId(const FormStructure& form); // Whether a dynamic change form is imported. bool from_dynamic_change_form_ = false; // Whether the form imported has non-focusable fields after user entered // information into it. bool has_non_focusable_field_ = false; // The associated autofill client. Weak reference. AutofillClient* client_; // Responsible for managing credit card save flows (local or upload). std::unique_ptr<CreditCardSaveManager> credit_card_save_manager_; // Responsible for managing address profiles save flows. std::unique_ptr<AddressProfileSaveManager> address_profile_save_manager_; #if !defined(OS_ANDROID) && !defined(OS_IOS) // Responsible for migrating locally saved credit cards to Google Pay. std::unique_ptr<LocalCardMigrationManager> local_card_migration_manager_; // Responsible for managing UPI/VPA save flows. std::unique_ptr<UpiVpaSaveManager> upi_vpa_save_manager_; #endif // #if !defined(OS_ANDROID) && !defined(OS_IOS) // The personal data manager, used to save and load personal data to/from the // web database. This is overridden by the BrowserAutofillManagerTest. // Weak reference. // May be NULL. NULL indicates OTR. PersonalDataManager* personal_data_manager_; // Represents the type of the imported credit card from the submitted form. // It will be used to determine whether to offer Upstream or card migration. // Will be passed to |credit_card_save_manager_| for metrics. ImportedCreditCardRecordType imported_credit_card_record_type_; std::string app_locale_; // Used to store the last four digits of the fetched virtual cards. base::flat_set<std::u16string> fetched_virtual_cards_; friend class AutofillMergeTest; friend class FormDataImporterTest; friend class FormDataImporterTestBase; friend class LocalCardMigrationBrowserTest; friend class SaveCardBubbleViewsFullFormBrowserTest; friend class SaveCardInfobarEGTestHelper; friend class ::SaveCardOfferObserver; FRIEND_TEST_ALL_PREFIXES(AutofillMergeTest, MergeProfiles); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, AllowDuplicateMaskedServerCardIfFlagEnabled); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, DontDuplicateFullServerCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, DontDuplicateMaskedServerCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_AddressesDisabledOneCreditCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_AddressCreditCardDisabled); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_HiddenCreditCardFormAfterEntered); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_FullServerCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_LocalCard); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_MaskedServerCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NewCard); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NoCard_ExpiredCard_EditableExpDateOff); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NewCard_ExpiredCard_WithExpDateFixFlow); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NoCard_InvalidCardNumber); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NoCard_VirtualCard); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_ImportCreditCardRecordType_NoCard_NoCardOnForm); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_OneAddressCreditCardDisabled); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_OneAddressOneCreditCard); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, ImportFormData_SecondImportResetsCreditCardRecordType); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_TwoAddressesOneCreditCard); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportFormData_DontSetUpiIdWhenOnlyCreditCardExists); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_FullServerCardMatch); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_FullServerCardMismatch); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_MaskedServerCardMatch); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_MaskedServerCardMismatch); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_EmptyExpirationMonth); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedServerCardExpirationStatus_EmptyExpirationYear); FRIEND_TEST_ALL_PREFIXES( FormDataImporterTest, Metrics_SubmittedDifferentServerCardExpirationStatus_EmptyExpirationYear); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportUpiId); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportUpiIdDisabled); FRIEND_TEST_ALL_PREFIXES(FormDataImporterTest, ImportUpiIdIgnoreNonUpiId); }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_FORM_DATA_IMPORTER_H_
46.050314
88
0.75799
[ "vector" ]
9b0f2cf3ce0496e96c420ac57ffea3d462fccf5f
195
h
C
library/blockchainV1/contrib/xrjv1-seeder-master/xrjv1.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
library/blockchainV1/contrib/xrjv1-seeder-master/xrjv1.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
library/blockchainV1/contrib/xrjv1-seeder-master/xrjv1.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
#ifndef _XRJV1_H_ #define _XRJV1_H_ 1 #include "protocol.h" bool TestNode(const CService &cip, int &ban, int &client, std::string &clientSV, int &blocks, std::vector<CAddress>* vAddr); #endif
21.666667
124
0.733333
[ "vector" ]
9b172b5a4a18df4b5bde3f7b86eaa6d892ac794f
1,275
h
C
ffm/chunk_editor/src/tools/tool_monsters.h
TSAVideoGame/Skidibidipop
62a8f949266df13cd759e3b98e36e16e05aabd11
[ "Zlib" ]
1
2020-12-26T21:52:59.000Z
2020-12-26T21:52:59.000Z
ffm/chunk_editor/src/tools/tool_monsters.h
TSAVideoGame/Skidibidipop
62a8f949266df13cd759e3b98e36e16e05aabd11
[ "Zlib" ]
2
2021-01-15T04:05:00.000Z
2021-03-03T18:37:08.000Z
ffm/chunk_editor/src/tools/tool_monsters.h
TSAVideoGame/Skidibidipop
62a8f949266df13cd759e3b98e36e16e05aabd11
[ "Zlib" ]
null
null
null
#ifndef SKIDIBIDIBOP_FFM_CHUNK_EDITOR_TOOLS_TOOL_MONSTERS #define SKIDIBIDIBOP_FFM_CHUNK_EDITOR_TOOLS_TOOL_MONSTERS #include "tool.h" #include <vector> namespace FFM { namespace ChunkEditor { namespace Tools { namespace Monsters { namespace Edit { class Main : public Base { public: Main(SDLW::Renderer*, int x, int y); ~Main(); void update(MouseState); void draw(); Base* selected_tool; int selected_monster; // The index of it private: std::vector<Base*> tools; }; class Id : public Numeric<std::uint16_t> { public: Id(SDLW::Renderer*, int x, int y); void update(MouseState); }; class Delete : public Base { public: Delete(SDLW::Renderer*, int x, int y); void update(MouseState); private: bool is_selected; }; }; class Add : public Base { public: Add(SDLW::Renderer*, int x, int y); void update(MouseState); void draw(); }; }; }; }; }; #endif
19.318182
57
0.48549
[ "vector" ]
9b182f83d0b96382ced3bfa16c62586f60589db0
28,000
h
C
include/picolibrary/testing/unit/ip/tcp.h
apcountryman/picolibrary
81349bd1b72874afead7d66004415e517a5da5f1
[ "Apache-2.0" ]
3
2021-02-12T04:05:42.000Z
2022-02-15T19:23:52.000Z
include/picolibrary/testing/unit/ip/tcp.h
apcountryman/picolibrary
81349bd1b72874afead7d66004415e517a5da5f1
[ "Apache-2.0" ]
633
2019-08-31T20:58:26.000Z
2022-03-31T22:23:36.000Z
include/picolibrary/testing/unit/ip/tcp.h
apcountryman/picolibrary
81349bd1b72874afead7d66004415e517a5da5f1
[ "Apache-2.0" ]
1
2021-02-17T20:40:49.000Z
2021-02-17T20:40:49.000Z
/** * picolibrary * * Copyright 2020-2021, Andrew Countryman <apcountryman@gmail.com> and the picolibrary * contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * \file * \brief picolibrary::Testing::Unit::IP::TCP interface. */ #ifndef PICOLIBRARY_TESTING_UNIT_IP_TCP_H #define PICOLIBRARY_TESTING_UNIT_IP_TCP_H #include <cstddef> #include <cstdint> #include "gmock/gmock.h" #include "picolibrary/error.h" #include "picolibrary/ip/tcp.h" #include "picolibrary/result.h" #include "picolibrary/testing/unit/ip.h" #include "picolibrary/void.h" /** * \brief Transmission Control Protocol (TCP) over IP unit testing facilities. */ namespace picolibrary::Testing::Unit::IP::TCP { /** * \brief Mock client socket. */ class Mock_Client { public: /** * \brief Endpoint. */ using Endpoint = ::picolibrary::IP::TCP::Endpoint; /** * \brief The unsigned integral type used to report transmit/receive buffer * information. */ using Size = std::size_t; /** * \brief Movable mock client socket handle. */ class Handle { public: /** * \brief The unsigned integral type used to report transmit/receive buffer * information. */ using Size = std::size_t; /** * \brief Constructor. */ Handle() noexcept = default; /** * \brief Constructor. * * \param[in] mock_client The mock client socket. */ Handle( Mock_Client & mock_client ) noexcept : m_mock_client{ &mock_client } { } /** * \brief Constructor. * * \param[in] source The source of the move. */ Handle( Handle && source ) noexcept : m_mock_client{ source.m_mock_client } { source.m_mock_client = nullptr; } Handle( Handle const & ) = delete; /** * \brief Destructor. */ ~Handle() noexcept = default; /** * \brief Assignment operator. * * \param[in] expression The expression to be assigned. * * \return The assigned to object. */ auto & operator=( Handle && expression ) noexcept { if ( &expression != this ) { m_mock_client = expression.m_mock_client; expression.m_mock_client = nullptr; } // if return *this; } /** * \brief Get the mock client socket. * * \return The mock client socket. */ auto & mock() noexcept { return *m_mock_client; } /** * \brief Bind the socket to a specific local endpoint. * * \param[in] endpoint The local endpoint to bind the socket to. * * \return Nothing if binding the socket to the local endpoint succeeded. * \return An error code if binding the socket to the local endpoint failed. */ auto bind( Endpoint const & endpoint = Endpoint{} ) { return m_mock_client->bind( endpoint ); } /** * \brief Connect to a remote endpoint. * * \param[in] endpoint The remote endpoint to connect to. * * \return Nothing if connecting to the remote endpoint succeeded. * \return An error code if connecting to the remote endpoint failed. */ auto connect( Endpoint const & endpoint ) { return m_mock_client->connect( endpoint ); } /** * \brief Check if the socket is connected to a remote endpoint. * * \return true if getting the socket's connection state succeeded and the socket * is connected to a remote endpoint. * \return false if getting the socket's connection state succeeded and the socket * is not connected to a remote endpoint. * \return An error code if getting the socket's connection state failed. */ auto is_connected() const { return m_mock_client->is_connected(); } /** * \brief Get the connection's remote endpoint. * * \return The connection's remote endpoint if getting the connection's remote * endpoint succeeded. * \return An error code if getting the connection's remote endpoint failed. */ auto remote_endpoint() const { return m_mock_client->remote_endpoint(); } /** * \brief Get the connection's local endpoint. * * \return The connection's local endpoint if getting the connection's local * endpoint succeeded. * \return An error code if getting the connection's local endpoint failed. */ auto local_endpoint() const { return m_mock_client->local_endpoint(); } /** * \brief Get the amount of data that has yet to be transmitted to the remote * endpoint. * * \return The amount of data that has yet to be transmitted to the remote * endpoint if getting the amount of data that has yet to be transmitted * to the remote endpoint succeeded. * \return An error code if getting the amount of data that has yet to be * transmitted to the remote endpoint failed. */ auto outstanding() const { return m_mock_client->outstanding(); } /** * \brief Transmit data to the remote endpoint. * * \param[in] begin The beginning of the block of data to write to the socket's * transmit buffer. * \param[in] end The end of the block of data to write to the socket's transmit * buffer. * * \return The end of the data that was written to the socket's transmit buffer if * writing data to the socket's transmit buffer succeeded. * \return An error code if writing data to the socket's transmit buffer failed. */ auto transmit( std::uint8_t const * begin, std::uint8_t const * end ) { return m_mock_client->transmit( begin, end ); } /** * \brief Get the amount of data that is immediately available to be received from * the remote endpoint. * * \return The amount of data that is immediately available to be received from * the remote endpoint if getting the amount of data that is immediately * available to be received from the remote endpoint succeeded. * \return An error code if getting the amount of data that is immediately * available to be received from the remote endpoint failed. */ auto available() const { return m_mock_client->available(); } /** * \brief Receive data from the remote endpoint. * * \param[out] begin The beginning of the block of data read from the socket's * receive buffer. * \param[out] end The end of the block of data read from the socket's receive * buffer. * * \return The end of the data that was read from the socket's receive buffer if * reading data from the socket's receive buffer succeeded. * \return An error code if reading data from the socket's receive buffer failed. */ auto receive( std::uint8_t * begin, std::uint8_t * end ) { return m_mock_client->receive( begin, end ); } /** * \brief Disable further data transmission and reception. * * \return Nothing if disabling further data transmission and reception succeeded. * \return An error code if disabling further data transmission and reception * failed. */ auto shutdown() { return m_mock_client->shutdown(); } /** * \brief Close the socket. * * \return Nothing if closing the socket succeeded. * \return An error code if closing the socket failed. */ auto close() { return m_mock_client->close(); } private: /** * \brief The mock client socket. */ Mock_Client * m_mock_client{}; }; /** * \brief Constructor. */ Mock_Client() = default; Mock_Client( Mock_Client && ) = delete; Mock_Client( Mock_Client const & ) = delete; /** * \brief Destructor. */ ~Mock_Client() noexcept = default; auto operator=( Mock_Client && ) = delete; auto operator=( Mock_Client const & ) = delete; MOCK_METHOD( (Result<Void, Error_Code>), bind, () ); MOCK_METHOD( (Result<Void, Error_Code>), bind, (Endpoint const &)); MOCK_METHOD( (Result<Void, Error_Code>), connect, (Endpoint const &)); MOCK_METHOD( (Result<bool, Error_Code>), is_connected, (), ( const ) ); MOCK_METHOD( (Result<Endpoint, Error_Code>), remote_endpoint, (), ( const ) ); MOCK_METHOD( (Result<Endpoint, Error_Code>), local_endpoint, (), ( const ) ); MOCK_METHOD( (Result<Size, Error_Code>), outstanding, (), ( const ) ); MOCK_METHOD( (Result<std::uint8_t const *, Error_Code>), transmit, (std::vector<std::uint8_t>)); /** * \brief Transmit data to the remote endpoint. * * \param[in] begin The beginning of the block of data to write to the socket's * transmit buffer. * \param[in] end The end of the block of data to write to the socket's transmit * buffer. * * \return The end of the data that was written to the socket's transmit buffer if * writing data to the socket's transmit buffer succeeded. * \return An error code if writing data to the socket's transmit buffer failed. */ auto transmit( std::uint8_t const * begin, std::uint8_t const * end ) -> Result<std::uint8_t const *, Error_Code> { return transmit( std::vector<std::uint8_t>{ begin, end } ); } MOCK_METHOD( (Result<Size, Error_Code>), available, (), ( const ) ); MOCK_METHOD( (Result<std::vector<std::uint8_t>, Error_Code>), receive, () ); /** * \brief Receive data from the remote endpoint. * * \param[out] begin The beginning of the block of data read from the socket's receive * buffer. * \param[out] end The end of the block of data read from the socket's receive buffer. * * \return The end of the data that was read from the socket's receive buffer if * reading data from the socket's receive buffer succeeded. * \return An error code if reading data from the socket's receive buffer failed. */ auto receive( std::uint8_t * begin, std::uint8_t * end ) -> Result<std::uint8_t *, Error_Code> { static_cast<void>( end ); auto const result = receive(); if ( result.is_error() ) { return result.error(); } // if std::for_each( result.value().begin(), result.value().end(), [ &begin ]( auto data ) { *begin = data; ++begin; } ); return begin; } MOCK_METHOD( (Result<Void, Error_Code>), shutdown, () ); MOCK_METHOD( (Result<Void, Error_Code>), close, () ); }; /** * \brief Mock server socket. */ class Mock_Server { public: /** * \brief Endpoint. */ using Endpoint = ::picolibrary::IP::TCP::Endpoint; /** * \brief The unsigned integral type used to report transmit/receive buffer * information. */ using Size = std::size_t; /** * \brief Movable mock server socket handle. */ class Handle { public: /** * \brief The unsigned integral type used to report transmit/receive buffer * information. */ using Size = std::size_t; /** * \brief Constructor. */ Handle() noexcept = default; /** * \brief Constructor. * * \param[in] mock_server The mock server socket. */ Handle( Mock_Server & mock_server ) noexcept : m_mock_server{ &mock_server } { } /** * \brief Constructor. * * \param[in] source The source of the move. */ Handle( Handle && source ) noexcept : m_mock_server{ source.m_mock_server } { source.m_mock_server = nullptr; } Handle( Handle const & ) = delete; /** * \brief Destructor. */ ~Handle() noexcept = default; /** * \brief Assignment operator. * * \param[in] expression The expression to be assigned. * * \return The assigned to object. */ auto & operator=( Handle && expression ) noexcept { if ( &expression != this ) { m_mock_server = expression.m_mock_server; expression.m_mock_server = nullptr; } // if return *this; } /** * \brief Get the mock server socket. * * \return The mock server socket. */ auto & mock() noexcept { return *m_mock_server; } /** * \brief Check if the socket is connected to a remote endpoint. * * \return true if getting the socket's connection state succeeded and the socket * is connected to a remote endpoint. * \return false if getting the socket's connection state succeeded and the socket * is not connected to a remote endpoint. * \return An error code if getting the socket's connection state failed. */ auto is_connected() const { return m_mock_server->is_connected(); } /** * \brief Get the connection's remote endpoint. * * \return The connection's remote endpoint if getting the connection's remote * endpoint succeeded. * \return An error code if getting the connection's remote endpoint failed. */ auto remote_endpoint() const { return m_mock_server->remote_endpoint(); } /** * \brief Get the connection's local endpoint. * * \return The connection's local endpoint if getting the connection's local * endpoint succeeded. * \return An error code if getting the connection's local endpoint failed. */ auto local_endpoint() const { return m_mock_server->local_endpoint(); } /** * \brief Get the amount of data that has yet to be transmitted to the remote * endpoint. * * \return The amount of data that has yet to be transmitted to the remote * endpoint if getting the amount of data that has yet to be transmitted * to the remote endpoint succeeded. * \return An error code if getting the amount of data that has yet to be * transmitted to the remote endpoint failed. */ auto outstanding() const { return m_mock_server->outstanding(); } /** * \brief Transmit data to the remote endpoint. * * \param[in] begin The beginning of the block of data to write to the socket's * transmit buffer. * \param[in] end The end of the block of data to write to the socket's transmit * buffer. * * \return The end of the data that was written to the socket's transmit buffer if * writing data to the socket's transmit buffer succeeded. * \return An error code if writing data to the socket's transmit buffer failed. */ auto transmit( std::uint8_t const * begin, std::uint8_t const * end ) { return m_mock_server->transmit( begin, end ); } /** * \brief Get the amount of data that is immediately available to be received from * the remote endpoint. * * \return The amount of data that is immediately available to be received from * the remote endpoint if getting the amount of data that is immediately * available to be received from the remote endpoint succeeded. * \return An error code if getting the amount of data that is immediately * available to be received from the remote endpoint failed. */ auto available() const { return m_mock_server->available(); } /** * \brief Receive data from the remote endpoint. * * \param[out] begin The beginning of the block of data read from the socket's * receive buffer. * \param[out] end The end of the block of data read from the socket's receive * buffer. * * \return The end of the data that was read from the socket's receive buffer if * reading data from the socket's receive buffer succeeded. * \return An error code if reading data from the socket's receive buffer failed. */ auto receive( std::uint8_t * begin, std::uint8_t * end ) { return m_mock_server->receive( begin, end ); } /** * \brief Disable further data transmission and reception. * * \return Nothing if disabling further data transmission and reception succeeded. * \return An error code if disabling further data transmission and reception * failed. */ auto shutdown() { return m_mock_server->shutdown(); } /** * \brief Close the socket. * * \return Nothing if closing the socket succeeded. * \return An error code if closing the socket failed. */ auto close() { return m_mock_server->close(); } private: /** * \brief The mock server socket. */ Mock_Server * m_mock_server{}; }; /** * \brief Constructor. */ Mock_Server() = default; Mock_Server( Mock_Server && ) = delete; Mock_Server( Mock_Server const & ) = delete; /** * \brief Destructor. */ ~Mock_Server() noexcept = default; auto operator=( Mock_Server && ) = delete; auto operator=( Mock_Server const & ) = delete; MOCK_METHOD( (Result<bool, Error_Code>), is_connected, (), ( const ) ); MOCK_METHOD( (Result<Endpoint, Error_Code>), remote_endpoint, (), ( const ) ); MOCK_METHOD( (Result<Endpoint, Error_Code>), local_endpoint, (), ( const ) ); MOCK_METHOD( (Result<Size, Error_Code>), outstanding, (), ( const ) ); MOCK_METHOD( (Result<std::uint8_t const *, Error_Code>), transmit, (std::vector<std::uint8_t>)); /** * \brief Transmit data to the remote endpoint. * * \param[in] begin The beginning of the block of data to write to the socket's * transmit buffer. * \param[in] end The end of the block of data to write to the socket's transmit * buffer. * * \return The end of the data that was written to the socket's transmit buffer if * writing data to the socket's transmit buffer succeeded. * \return An error code if writing data to the socket's transmit buffer failed. */ auto transmit( std::uint8_t const * begin, std::uint8_t const * end ) -> Result<std::uint8_t const *, Error_Code> { return transmit( std::vector<std::uint8_t>{ begin, end } ); } MOCK_METHOD( (Result<Size, Error_Code>), available, (), ( const ) ); MOCK_METHOD( (Result<std::vector<std::uint8_t>, Error_Code>), receive, () ); /** * \brief Receive data from the remote endpoint. * * \param[out] begin The beginning of the block of data read from the socket's receive * buffer. * \param[out] end The end of the block of data read from the socket's receive buffer. * * \return The end of the data that was read from the socket's receive buffer if * reading data from the socket's receive buffer succeeded. * \return An error code if reading data from the socket's receive buffer failed. */ auto receive( std::uint8_t * begin, std::uint8_t * end ) -> Result<std::uint8_t *, Error_Code> { static_cast<void>( end ); auto const result = receive(); if ( result.is_error() ) { return result.error(); } // if std::for_each( result.value().begin(), result.value().end(), [ &begin ]( auto data ) { *begin = data; ++begin; } ); return begin; } MOCK_METHOD( (Result<Void, Error_Code>), shutdown, () ); MOCK_METHOD( (Result<Void, Error_Code>), close, () ); }; /** * \brief Mock acceptor socket. */ class Mock_Acceptor { public: /** * \brief Endpoint. */ using Endpoint = ::picolibrary::IP::TCP::Endpoint; /** * \brief The type of server socket produced by the acceptor socket. */ using Server = Mock_Server::Handle; /** * \brief Movable mock acceptor socket handle. */ class Handle { public: /** * \brief The type of server socket produced by the acceptor socket. */ using Server = Mock_Server::Handle; /** * \brief Constructor. */ Handle() noexcept = default; /** * \brief Constructor. * * \param[in] mock_acceptor The mock acceptor socket. */ Handle( Mock_Acceptor & mock_acceptor ) noexcept : m_mock_acceptor{ &mock_acceptor } { } /** * \brief Constructor. * * \param[in] source The source of the move. */ Handle( Handle && source ) noexcept : m_mock_acceptor{ source.m_mock_acceptor } { source.m_mock_acceptor = nullptr; } Handle( Handle const & ) = delete; /** * \brief Destructor. */ ~Handle() noexcept = default; /** * \brief Assignment operator. * * \param[in] expression The expression to be assigned. * * \return The assigned to object. */ auto & operator=( Handle && expression ) noexcept { if ( &expression != this ) { m_mock_acceptor = expression.m_mock_acceptor; expression.m_mock_acceptor = nullptr; } // if return *this; } /** * \brief Get the mock acceptor socket. * * \return The mock acceptor socket. */ auto & mock() noexcept { return *m_mock_acceptor; } /** * \brief Bind the socket to a specific local endpoint. * * \param[in] endpoint The local endpoint to bind the socket to. * * \return Nothing if binding the socket to the local endpoint succeeded. * \return An error code if binding the socket to the local endpoint failed. */ auto bind( Endpoint const & endpoint = Endpoint{} ) { return m_mock_acceptor->bind( endpoint ); } /** * \brief Listen for incoming connection requests. * * \param[in] backlog The maximum number of simultaneously connected clients. * * \return Nothing if listening for incoming connection requests succeeded. * \return An error code if listening for incoming connection requests failed. */ auto listen( std::uint_fast8_t backlog ) { return m_mock_acceptor->listen( backlog ); } /** * \brief Check if the socket is listening for incoming connection requests. * * \return true if getting the socket's listening state succeeded and the socket * is listening for incoming connection requests. * \return false if getting the socket's listening state succeeded and the socket * is not listening for incoming connection requests. * \return An error code if getting the socket's listening state failed. */ auto is_listening() const { return m_mock_acceptor->is_listening(); } /** * \brief Get the endpoint on which the socket is listening for incoming * connection requests. * * \return The endpoint on which the socket is listening for incoming connection * requests if getting the endpoint on which the socket is listening for * incoming connection requests succeeded. * \return An error code if getting the endpoint on which the socket is listening * for incoming connection requests failed. */ auto local_endpoint() const { return m_mock_acceptor->local_endpoint(); } /** * \brief Accept an incoming connection request. * * \return A server socket for handling the connection if accepting an incoming * connection request succeeded. * \return An error code if accepting an incoming connection request failed. */ auto accept() { return m_mock_acceptor->accept(); } /** * \brief Close the socket. * * \return Nothing if closing the socket succeeded. * \return An error code if closing the socket failed. */ auto close() { return m_mock_acceptor->close(); } private: /** * \brief The mock acceptor socket. */ Mock_Acceptor * m_mock_acceptor{}; }; /** * \brief Constructor. */ Mock_Acceptor() = default; Mock_Acceptor( Mock_Acceptor && ) = delete; Mock_Acceptor( Mock_Acceptor const & ) = delete; /** * \brief Destructor. */ ~Mock_Acceptor() noexcept = default; auto operator=( Mock_Acceptor && ) = delete; auto operator=( Mock_Acceptor const & ) = delete; MOCK_METHOD( (Result<Void, Error_Code>), bind, () ); MOCK_METHOD( (Result<Void, Error_Code>), bind, (Endpoint const &)); MOCK_METHOD( (Result<Void, Error_Code>), listen, ( std::uint_fast8_t ) ); MOCK_METHOD( (Result<bool, Error_Code>), is_listening, (), ( const ) ); MOCK_METHOD( (Result<Endpoint, Error_Code>), local_endpoint, (), ( const ) ); MOCK_METHOD( (Result<Server, Error_Code>), accept, () ); MOCK_METHOD( (Result<Void, Error_Code>), close, () ); }; } // namespace picolibrary::Testing::Unit::IP::TCP #endif // PICOLIBRARY_TESTING_UNIT_IP_TCP_H
31.638418
100
0.566179
[ "object", "vector" ]
9b1a660e800c63e4a7dd11a35705b9c4ef889757
3,119
h
C
Userland/Libraries/LibCore/EventLoop.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibCore/EventLoop.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibCore/EventLoop.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Forward.h> #include <AK/Function.h> #include <AK/HashMap.h> #include <AK/Noncopyable.h> #include <AK/NonnullOwnPtr.h> #include <AK/NonnullRefPtr.h> #include <AK/Time.h> #include <AK/Vector.h> #include <AK/WeakPtr.h> #include <LibCore/DeferredInvocationContext.h> #include <LibCore/Event.h> #include <LibCore/Forward.h> #include <sys/time.h> #include <sys/types.h> namespace Core { class EventLoop { public: enum class MakeInspectable { No, Yes, }; explicit EventLoop(MakeInspectable = MakeInspectable::No); ~EventLoop(); int exec(); enum class WaitMode { WaitForEvents, PollForEvents, }; // processe events, generally called by exec() in a loop. // this should really only be used for integrating with other event loops void pump(WaitMode = WaitMode::WaitForEvents); void spin_until(Function<bool()>); void post_event(Object& receiver, NonnullOwnPtr<Event>&&); static EventLoop& main(); static EventLoop& current(); bool was_exit_requested() const { return m_exit_requested; } static int register_timer(Object&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible); static bool unregister_timer(int timer_id); static void register_notifier(Badge<Notifier>, Notifier&); static void unregister_notifier(Badge<Notifier>, Notifier&); void quit(int); void unquit(); void take_pending_events_from(EventLoop& other) { m_queued_events.extend(move(other.m_queued_events)); } static void wake(); static int register_signal(int signo, Function<void(int)> handler); static void unregister_signal(int handler_id); // Note: Boost uses Parent/Child/Prepare, but we don't really have anything // interesting to do in the parent or before forking. enum class ForkEvent { Child, }; static void notify_forked(ForkEvent); static bool has_been_instantiated(); void deferred_invoke(Function<void()> invokee) { auto context = DeferredInvocationContext::construct(); post_event(context, make<Core::DeferredInvocationEvent>(context, move(invokee))); } private: void wait_for_event(WaitMode); Optional<Time> get_next_timer_expiration(); static void dispatch_signal(int); static void handle_signal(int); struct QueuedEvent { AK_MAKE_NONCOPYABLE(QueuedEvent); public: QueuedEvent(Object& receiver, NonnullOwnPtr<Event>); QueuedEvent(QueuedEvent&&); ~QueuedEvent(); WeakPtr<Object> receiver; NonnullOwnPtr<Event> event; }; Vector<QueuedEvent, 64> m_queued_events; static pid_t s_pid; bool m_exit_requested { false }; int m_exit_code { 0 }; static int s_wake_pipe_fds[2]; struct Private; NonnullOwnPtr<Private> m_private; }; inline void deferred_invoke(Function<void()> invokee) { EventLoop::current().deferred_invoke(move(invokee)); } }
24.753968
108
0.690285
[ "object", "vector" ]
9b1b1efc65ad9c3ae5b3d0e9e4e31cf3762fd1a1
287
h
C
RaiLight/Utilities/MemoryFan.h
CathalT/Rail
4c5623c9c69eca67e46beb554bdfc71d44627f73
[ "MIT" ]
null
null
null
RaiLight/Utilities/MemoryFan.h
CathalT/Rail
4c5623c9c69eca67e46beb554bdfc71d44627f73
[ "MIT" ]
21
2018-03-08T12:17:34.000Z
2018-07-18T21:11:33.000Z
RaiLight/Utilities/MemoryFan.h
CathalT/Rail
4c5623c9c69eca67e46beb554bdfc71d44627f73
[ "MIT" ]
null
null
null
#pragma once #include "RaiLight\Model\BasicTypes.h" namespace rail { class MemoryFan { public: MemoryFan(ByteArray32 & key, const size_t count_a); ByteArray32 getValue(); private: std::vector< std::unique_ptr< ByteArray32 > > values; }; }
15.944444
61
0.627178
[ "vector", "model" ]
9b28d30e33c362ac23b8bd4f3fc538e8e72eea43
203,040
c
C
fontforge/problems.c
letolabs/fontforge
719e5b5fab1384ce625306146daf5c709d625d30
[ "BSD-3-Clause" ]
2
2015-05-15T16:19:41.000Z
2017-09-26T10:21:41.000Z
fontforge/problems.c
Distrotech/fontforge
dc5514f4d56ea523d0677cc77d0ad6ff822363f8
[ "BSD-3-Clause" ]
null
null
null
fontforge/problems.c
Distrotech/fontforge
dc5514f4d56ea523d0677cc77d0ad6ff822363f8
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2000-2012 by George Williams */ /* * 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. * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "fontforgeui.h" #include "ttf.h" #include <gwidget.h> #include <ustring.h> #include <math.h> #include <gkeysym.h> /* ************************************************************************** */ /* ***************************** Problems Dialog **************************** */ /* ************************************************************************** */ struct problems { FontView *fv; CharView *cv; SplineChar *sc; SplineChar *msc; int layer; unsigned int openpaths: 1; unsigned int intersectingpaths: 1; unsigned int nonintegral: 1; unsigned int pointstooclose: 1; unsigned int pointstoofar: 1; unsigned int xnearval: 1; unsigned int ynearval: 1; unsigned int ynearstd: 1; /* baseline, xheight, cap, ascent, descent, etc. */ unsigned int linenearstd: 1; /* horizontal, vertical, italicangle */ unsigned int cpnearstd: 1; /* control points near: horizontal, vertical, italicangle */ unsigned int cpodd: 1; /* control points beyond points on spline */ unsigned int hintwithnopt: 1; unsigned int ptnearhint: 1; unsigned int hintwidthnearval: 1; unsigned int missingextrema: 1; unsigned int direction: 1; unsigned int flippedrefs: 1; unsigned int cidmultiple: 1; unsigned int cidblank: 1; unsigned int bitmaps: 1; unsigned int bitmapwidths: 1; unsigned int advancewidth: 1; unsigned int vadvancewidth: 1; unsigned int stem3: 1; unsigned int showexactstem3: 1; unsigned int irrelevantcontrolpoints: 1; unsigned int multuni: 1; unsigned int multname: 1; unsigned int uninamemismatch: 1; unsigned int missinganchor: 1; unsigned int badsubs: 1; unsigned int missingglyph: 1; unsigned int missingscriptinfeature: 1; unsigned int toomanypoints: 1; unsigned int toomanyhints: 1; unsigned int toodeeprefs: 1; unsigned int ptmatchrefsoutofdate: 1; unsigned int multusemymetrics: 1; unsigned int refsbadtransformttf: 1; unsigned int refsbadtransformps: 1; unsigned int mixedcontoursrefs: 1; unsigned int bbymax: 1; unsigned int bbymin: 1; unsigned int bbxmax: 1; unsigned int bbxmin: 1; unsigned int overlappedhints: 1; unsigned int explain: 1; unsigned int done: 1; unsigned int doneexplain: 1; unsigned int finish: 1; unsigned int ignorethis: 1; double near, xval, yval, widthval; char *explaining; double found, expected; double xheight, caph, ascent, descent; double irrelevantfactor; int advancewidthval, vadvancewidthval; int bbymax_val, bbymin_val, bbxmax_val, bbxmin_val; int pointsmax, hintsmax, refdepthmax; GWindow explainw; GGadget *explaintext, *explainvals, *ignoregadg, *topbox; SplineChar *lastcharopened; CharView *cvopened; char *badsubsname; struct lookup_subtable *badsubs_lsubtable; AnchorClass *missinganchor_class; int rpl_cnt, rpl_max; struct mgrpl { char *search; char *rpl; /* a rpl of "" means delete (NULL means not found) */ } *mg; struct mlrpl { uint32 search; uint32 rpl; } *mlt; char *glyphname; int glyphenc; EncMap *map; }; static int openpaths=0, pointstooclose=0/*, missing=0*/, doxnear=0, doynear=0; static int nonintegral=0, pointstoofar=0; static int intersectingpaths=0, missingextrema=0; static int doynearstd=0, linestd=0, cpstd=0, cpodd=0, hintnopt=0, ptnearhint=0; static int hintwidth=0, direction=0, flippedrefs=0, bitmaps=0, bitmapwidths=0; static int cidblank=0, cidmultiple=0, advancewidth=0, vadvancewidth=0; static int bbymax=0, bbymin=0, bbxmax=0, bbxmin=0; static int irrelevantcp=0, missingglyph=0, missingscriptinfeature=0; static int badsubs=0, missinganchor=0, toomanypoints=0, pointsmax = 1500; static int multuni=0, multname=0, uninamemismatch=0, overlappedhints=0; static int toomanyhints=0, hintsmax=96, toodeeprefs=0, refdepthmax=9; static int ptmatchrefsoutofdate=0, refsbadtransformttf=0, refsbadtransformps=0; static int mixedcontoursrefs=0, multusemymetrics=0; static int stem3=0, showexactstem3=0; static double near=3, xval=0, yval=0, widthval=50, advancewidthval=0, vadvancewidthval=0; static double bbymax_val=0, bbymin_val=0, bbxmax_val=0, bbxmin_val=0; static double irrelevantfactor = .005; static SplineFont *lastsf=NULL; #define CID_Stop 2001 #define CID_Next 2002 #define CID_Fix 2003 #define CID_ClearAll 2004 #define CID_SetAll 2005 #define CID_OpenPaths 1001 #define CID_IntersectingPaths 1002 #define CID_PointsTooClose 1003 #define CID_XNear 1004 #define CID_YNear 1005 #define CID_YNearStd 1006 #define CID_HintNoPt 1007 #define CID_PtNearHint 1008 #define CID_HintWidthNear 1009 #define CID_HintWidth 1010 #define CID_Near 1011 #define CID_XNearVal 1012 #define CID_YNearVal 1013 #define CID_LineStd 1014 #define CID_Direction 1015 #define CID_CpStd 1016 #define CID_CpOdd 1017 #define CID_CIDMultiple 1018 #define CID_CIDBlank 1019 #define CID_FlippedRefs 1020 #define CID_Bitmaps 1021 #define CID_AdvanceWidth 1022 #define CID_AdvanceWidthVal 1023 #define CID_VAdvanceWidth 1024 #define CID_VAdvanceWidthVal 1025 #define CID_Stem3 1026 #define CID_ShowExactStem3 1027 #define CID_IrrelevantCP 1028 #define CID_IrrelevantFactor 1029 #define CID_BadSubs 1030 #define CID_MissingGlyph 1031 #define CID_MissingScriptInFeature 1032 #define CID_TooManyPoints 1033 #define CID_PointsMax 1034 #define CID_TooManyHints 1035 #define CID_HintsMax 1036 #define CID_TooDeepRefs 1037 #define CID_RefDepthMax 1038 #define CID_MultUni 1040 #define CID_MultName 1041 #define CID_PtMatchRefsOutOfDate 1042 #define CID_RefBadTransformTTF 1043 #define CID_RefBadTransformPS 1044 #define CID_MixedContoursRefs 1045 #define CID_MissingExtrema 1046 #define CID_UniNameMisMatch 1047 #define CID_BBYMax 1048 #define CID_BBYMin 1049 #define CID_BBXMax 1050 #define CID_BBXMin 1051 #define CID_BBYMaxVal 1052 #define CID_BBYMinVal 1053 #define CID_BBXMaxVal 1054 #define CID_BBXMinVal 1055 #define CID_NonIntegral 1056 #define CID_PointsTooFar 1057 #define CID_BitmapWidths 1058 #define CID_MissingAnchor 1059 #define CID_MultUseMyMetrics 1060 #define CID_OverlappedHints 1061 static void FixIt(struct problems *p) { SplinePointList *spl; SplinePoint *sp; /*StemInfo *h;*/ RefChar *r; int ncp_changed, pcp_changed; #if 0 /* The ultimate cause (the thing we need to fix) for these two errors */ /* is that the stem is wrong, it's too hard to fix that here, so best */ /* not to attempt to fix the proximal cause */ if ( p->explaining==_("This glyph contains a horizontal hint near the specified width") ) { for ( h=p->sc->hstem; h!=NULL && !h->active; h=h->next ); if ( h!=NULL ) { h->width = p->widthval; SCOutOfDateBackground(p->sc); SCUpdateAll(p->sc); } else IError("Could not find hint"); return; } if ( p->explaining==_("This glyph contains a vertical hint near the specified width") ) { for ( h=p->sc->vstem; h!=NULL && !h->active; h=h->next ); if ( h!=NULL ) { h->width = p->widthval; SCOutOfDateBackground(p->sc); SCUpdateAll(p->sc); } else IError("Could not find hint"); return; } #endif if ( p->explaining==_("This reference has been flipped, so the paths in it are drawn backwards") ) { for ( r=p->sc->layers[p->layer].refs; r!=NULL && !r->selected; r = r->next ); if ( r!=NULL ) { SplineSet *ss, *spl; SCPreserveLayer(p->sc,p->layer,false); ss = p->sc->layers[p->layer].splines; p->sc->layers[p->layer].splines = NULL; SCRefToSplines(p->sc,r,p->layer); for ( spl = p->sc->layers[p->layer].splines; spl!=NULL; spl=spl->next ) SplineSetReverse(spl); if ( p->sc->layers[p->layer].splines!=NULL ) { for ( spl = p->sc->layers[p->layer].splines; spl->next!=NULL; spl=spl->next ); spl->next = ss; } else p->sc->layers[p->layer].splines = ss; SCCharChangedUpdate(p->sc,p->layer); } else IError("Could not find referenc"); return; } else if ( p->explaining==_("This glyph's advance width is different from the standard width") ) { SCSynchronizeWidth(p->sc,p->advancewidthval,p->sc->width,NULL); return; } else if ( p->explaining==_("This glyph's vertical advance is different from the standard width") ) { p->sc->vwidth=p->vadvancewidthval; return; } if ( p->explaining==_("This glyph is not mapped to any unicode code point, but its name should be.") || p->explaining==_("This glyph is mapped to a unicode code point which is different from its name.") ) { char buf[100]; const char *newname; SplineChar *foundsc; newname = StdGlyphName(buf,p->sc->unicodeenc,p->sc->parent->uni_interp,p->sc->parent->for_new_glyphs); foundsc = SFHashName(p->sc->parent,newname); if ( foundsc==NULL ) { free(p->sc->name); p->sc->name = copy(newname); } else { ff_post_error(_("Can't fix"), _("The name FontForge would like to assign to this glyph, %.30s, is already used by a different glyph."), newname ); } return; } sp = NULL; for ( spl=p->sc->layers[p->layer].splines; spl!=NULL; spl=spl->next ) { for ( sp = spl->first; ; ) { if ( sp->selected ) break; if ( sp->next==NULL ) break; sp = sp->next->to; if ( sp==spl->first ) break; } if ( sp->selected ) break; } if ( sp==NULL ) { IError("Nothing selected"); return; } /* I do not handle: _("The two selected points are the endpoints of an open path") _("The paths that make up this glyph intersect one another") _("The selected points are too close to each other") _("The selected line segment is near the italic angle"), _("The control point above the selected point is near the italic angle"), _("The control point below the selected point is near the italic angle"), _("The control point right of the selected point is near the italic angle"), _("The control point left of the selected point is near the italic angle") _("The control point above the selected point is outside the spline segment"), _("The control point below the selected point is outside the spline segment"), _("The control point right of the selected point is outside the spline segment"), _("The control point left of the selected point is outside the spline segment") _("This hint does not control any points") _STR_ProbHint3* _STR_ProbMultUni, STR_ProbMultName */ SCPreserveLayer(p->sc,p->layer,false); ncp_changed = pcp_changed = false; if ( p->explaining==_("The x coord of the selected point is near the specified value") || p->explaining==_("The selected point is near a vertical stem hint")) { sp->prevcp.x += p->expected-sp->me.x; sp->nextcp.x += p->expected-sp->me.x; sp->me.x = p->expected; ncp_changed = pcp_changed = true; } else if ( p->explaining==_("The selected point is not at integral coordinates") || p->explaining==_("The selected point does not have integral control points")) { sp->me.x = rint(sp->me.x); sp->me.y = rint(sp->me.y); sp->nextcp.x = rint(sp->nextcp.x); sp->nextcp.y = rint(sp->nextcp.y); sp->prevcp.x = rint(sp->prevcp.x); sp->prevcp.y = rint(sp->prevcp.y); ncp_changed = pcp_changed = true; } else if ( p->explaining==_("The y coord of the selected point is near the specified value") || p->explaining==_("The selected point is near a horizontal stem hint") || p->explaining==_("The y coord of the selected point is near the baseline") || p->explaining==_("The y coord of the selected point is near the xheight") || p->explaining==_("The y coord of the selected point is near the cap height") || p->explaining==_("The y coord of the selected point is near the ascender height") || p->explaining==_("The y coord of the selected point is near the descender height") ) { sp->prevcp.y += p->expected-sp->me.y; sp->nextcp.y += p->expected-sp->me.y; sp->me.y = p->expected; ncp_changed = pcp_changed = true; } else if ( p->explaining==_("The selected spline attains its extrema somewhere other than its endpoints") ) { SplineCharAddExtrema(p->sc,p->sc->layers[p->layer].splines, ae_between_selected,p->sc->parent->ascent+p->sc->parent->descent); } else if ( p->explaining==_("The selected line segment is nearly horizontal") ) { if ( sp->me.y!=p->found ) { sp=sp->next->to; if ( !sp->selected || sp->me.y!=p->found ) { IError("Couldn't find line"); return; } } sp->prevcp.y += p->expected-sp->me.y; sp->nextcp.y += p->expected-sp->me.y; sp->me.y = p->expected; ncp_changed = pcp_changed = true; } else if ( p->explaining==_("The control point above the selected point is nearly horizontal") || p->explaining==_("The control point below the selected point is nearly horizontal") || p->explaining==_("The control point right of the selected point is nearly horizontal") || p->explaining==_("The control point left of the selected point is nearly horizontal") ) { BasePoint *tofix, *other; if ( sp->nextcp.y==p->found ) { tofix = &sp->nextcp; other = &sp->prevcp; } else { tofix = &sp->prevcp; other = &sp->nextcp; } if ( tofix->y!=p->found ) { IError("Couldn't find control point"); return; } tofix->y = p->expected; ncp_changed = pcp_changed = true; if ( sp->pointtype==pt_curve || sp->pointtype==pt_hvcurve ) other->y = p->expected; else { sp->pointtype = pt_corner; if ( other==&sp->nextcp ) ncp_changed = false; else pcp_changed = false; } } else if ( p->explaining==_("The selected line segment is nearly vertical") ) { if ( sp->me.x!=p->found ) { sp=sp->next->to; if ( !sp->selected || sp->me.x!=p->found ) { IError("Couldn't find line"); return; } } sp->prevcp.x += p->expected-sp->me.x; sp->nextcp.x += p->expected-sp->me.x; sp->me.x = p->expected; ncp_changed = pcp_changed = true; } else if ( p->explaining==_("The control point above the selected point is nearly vertical") || p->explaining==_("The control point below the selected point is nearly vertical") || p->explaining==_("The control point right of the selected point is nearly vertical") || p->explaining==_("The control point left of the selected point is nearly vertical") ) { BasePoint *tofix, *other; if ( sp->nextcp.x==p->found ) { tofix = &sp->nextcp; other = &sp->prevcp; } else { tofix = &sp->prevcp; other = &sp->nextcp; } if ( tofix->x!=p->found ) { IError("Couldn't find control point"); return; } tofix->x = p->expected; ncp_changed = pcp_changed = true; if ( sp->pointtype==pt_curve || sp->pointtype==pt_hvcurve ) other->x = p->expected; else { sp->pointtype = pt_corner; if ( other==&sp->nextcp ) ncp_changed = false; else pcp_changed = false; } } else if ( p->explaining==_("This path should have been drawn in a counter-clockwise direction") || p->explaining==_("This path should have been drawn in a clockwise direction") ) { SplineSetReverse(spl); } else if ( p->explaining==_("This glyph contains control points which are probably too close to the main points to alter the look of the spline") ) { if ( sp->next!=NULL ) { double len = sqrt((sp->me.x-sp->next->to->me.x)*(sp->me.x-sp->next->to->me.x) + (sp->me.y-sp->next->to->me.y)*(sp->me.y-sp->next->to->me.y)); double cplen = sqrt((sp->me.x-sp->nextcp.x)*(sp->me.x-sp->nextcp.x) + (sp->me.y-sp->nextcp.y)*(sp->me.y-sp->nextcp.y)); if ( cplen!=0 && cplen<p->irrelevantfactor*len ) { sp->nextcp = sp->me; sp->nonextcp = true; ncp_changed = true; } } if ( sp->prev!=NULL ) { double len = sqrt((sp->me.x-sp->prev->from->me.x)*(sp->me.x-sp->prev->from->me.x) + (sp->me.y-sp->prev->from->me.y)*(sp->me.y-sp->prev->from->me.y)); double cplen = sqrt((sp->me.x-sp->prevcp.x)*(sp->me.x-sp->prevcp.x) + (sp->me.y-sp->prevcp.y)*(sp->me.y-sp->prevcp.y)); if ( cplen!=0 && cplen<p->irrelevantfactor*len ) { sp->prevcp = sp->me; sp->noprevcp = true; pcp_changed = true; } } } else IError("Did not fix: %d", p->explaining ); if ( p->sc->layers[p->layer].order2 ) { if ( ncp_changed ) SplinePointNextCPChanged2(sp); if ( pcp_changed ) SplinePointPrevCPChanged2(sp); } if ( sp->next!=NULL ) SplineRefigure(sp->next); if ( sp->prev!=NULL ) SplineRefigure(sp->prev); SCCharChangedUpdate(p->sc,p->layer); } static int explain_e_h(GWindow gw, GEvent *event) { if ( event->type==et_close ) { struct problems *p = GDrawGetUserData(gw); p->doneexplain = true; } else if ( event->type==et_controlevent && event->u.control.subtype == et_buttonactivate ) { struct problems *p = GDrawGetUserData(gw); if ( GGadgetGetCid(event->u.control.g)==CID_Stop ) p->finish = true; else if ( GGadgetGetCid(event->u.control.g)==CID_Fix ) FixIt(p); p->doneexplain = true; } else if ( event->type==et_controlevent && event->u.control.subtype == et_radiochanged ) { struct problems *p = GDrawGetUserData(gw); p->ignorethis = GGadgetIsChecked(event->u.control.g); } else if ( event->type==et_char ) { if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) { help("problems.html"); return( true ); } return( false ); } return( true ); } static void ExplainIt(struct problems *p, SplineChar *sc, char *explain, real found, real expected ) { GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[9], boxes[3], *varray[10], *barray[14]; GTextInfo label[9]; char buf[200]; SplinePointList *spl; Spline *spline, *first; int fixable; if ( !p->explain || p->finish ) return; if ( p->explainw==NULL ) { memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor; wattrs.event_masks = ~(1<<et_charup); wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Problem explanation"); pos.x = pos.y = 0; pos.width = GGadgetScale(GDrawPointsToPixels(NULL,400)); pos.height = GDrawPointsToPixels(NULL,86); p->explainw = GDrawCreateTopWindow(NULL,&pos,explain_e_h,p,&wattrs); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); memset(&boxes,0,sizeof(boxes)); label[0].text = (unichar_t *) explain; label[0].text_is_1byte = true; gcd[0].gd.label = &label[0]; gcd[0].gd.pos.x = 6; gcd[0].gd.pos.y = 6; gcd[0].gd.pos.width = 400-12; gcd[0].gd.flags = gg_visible | gg_enabled; gcd[0].creator = GLabelCreate; varray[0] = &gcd[0]; varray[1] = NULL; label[4].text = (unichar_t *) ""; label[4].text_is_1byte = true; gcd[4].gd.label = &label[4]; gcd[4].gd.pos.x = 6; gcd[4].gd.pos.y = gcd[0].gd.pos.y+12; gcd[4].gd.pos.width = 400-12; gcd[4].gd.flags = gg_visible | gg_enabled; gcd[4].creator = GLabelCreate; varray[2] = &gcd[4]; varray[3] = NULL; label[5].text = (unichar_t *) _("Ignore this problem in the future"); label[5].text_is_1byte = true; gcd[5].gd.label = &label[5]; gcd[5].gd.pos.x = 6; gcd[5].gd.pos.y = gcd[4].gd.pos.y+12; gcd[5].gd.flags = gg_visible | gg_enabled; gcd[5].creator = GCheckBoxCreate; varray[4] = &gcd[5]; varray[5] = NULL; gcd[1].gd.pos.x = 15-3; gcd[1].gd.pos.y = gcd[5].gd.pos.y+20; gcd[1].gd.pos.width = -1; gcd[1].gd.pos.height = 0; gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_default; label[1].text = (unichar_t *) _("_Next"); label[1].text_is_1byte = true; label[1].text_in_resource = true; gcd[1].gd.mnemonic = 'N'; gcd[1].gd.label = &label[1]; gcd[1].gd.cid = CID_Next; gcd[1].creator = GButtonCreate; barray[0] = GCD_Glue; barray[1] = &gcd[1]; barray[2] = GCD_Glue; barray[3] = GCD_Glue; gcd[6].gd.pos.x = 200-30; gcd[6].gd.pos.y = gcd[2].gd.pos.y; gcd[6].gd.pos.width = -1; gcd[6].gd.pos.height = 0; gcd[6].gd.flags = /*gg_visible |*/ gg_enabled; label[6].text = (unichar_t *) _("Fix"); label[6].text_is_1byte = true; gcd[6].gd.mnemonic = 'F'; gcd[6].gd.label = &label[6]; gcd[6].gd.cid = CID_Fix; gcd[6].creator = GButtonCreate; barray[4] = GCD_Glue; barray[5] = GCD_Glue; barray[6] = &gcd[6]; barray[7] = GCD_Glue; gcd[2].gd.pos.x = -15; gcd[2].gd.pos.y = gcd[1].gd.pos.y+3; gcd[2].gd.pos.width = -1; gcd[2].gd.pos.height = 0; gcd[2].gd.flags = gg_visible | gg_enabled | gg_but_cancel; label[2].text = (unichar_t *) _("_Stop"); label[2].text_is_1byte = true; label[2].text_in_resource = true; gcd[2].gd.label = &label[2]; gcd[2].gd.mnemonic = 'S'; gcd[2].gd.cid = CID_Stop; gcd[2].creator = GButtonCreate; barray[8] = GCD_Glue; barray[9] = GCD_Glue; barray[10] = GCD_Glue; barray[11] = &gcd[2]; barray[12] = GCD_Glue; barray[13] = NULL; boxes[2].gd.flags = gg_enabled|gg_visible; boxes[2].gd.u.boxelements = barray; boxes[2].creator = GHBoxCreate; varray[6] = &boxes[2]; varray[7] = NULL; varray[8] = NULL; boxes[0].gd.pos.x = boxes[0].gd.pos.y = 2; boxes[0].gd.flags = gg_enabled|gg_visible; boxes[0].gd.u.boxelements = varray; boxes[0].creator = GHVGroupCreate; GGadgetsCreate(p->explainw,boxes); GHVBoxSetExpandableCol(boxes[2].ret,gb_expandgluesame); p->explaintext = gcd[0].ret; p->explainvals = gcd[4].ret; p->ignoregadg = gcd[5].ret; p->topbox = boxes[0].ret; } else GGadgetSetTitle8(p->explaintext,explain); p->explaining = explain; fixable = /*explain==_("This glyph contains a horizontal hint near the specified width") || explain==_("This glyph contains a vertical hint near the specified width") ||*/ explain==_("This reference has been flipped, so the paths in it are drawn backwards") || explain==_("The x coord of the selected point is near the specified value") || explain==_("The selected point is near a vertical stem hint") || explain==_("The y coord of the selected point is near the specified value") || explain==_("The selected point is near a horizontal stem hint") || explain==_("This glyph contains control points which are probably too close to the main points to alter the look of the spline") || explain==_("The y coord of the selected point is near the baseline") || explain==_("The y coord of the selected point is near the xheight") || explain==_("The y coord of the selected point is near the cap height") || explain==_("The y coord of the selected point is near the ascender height") || explain==_("The y coord of the selected point is near the descender height") || explain==_("The selected line segment is nearly horizontal") || explain==_("The selected line segment is nearly vertical") || explain==_("The control point above the selected point is nearly horizontal") || explain==_("The control point below the selected point is nearly horizontal") || explain==_("The control point right of the selected point is nearly horizontal") || explain==_("The control point left of the selected point is nearly horizontal") || explain==_("The control point above the selected point is nearly vertical") || explain==_("The control point below the selected point is nearly vertical") || explain==_("The control point right of the selected point is nearly vertical") || explain==_("The control point left of the selected point is nearly vertical") || explain==_("This path should have been drawn in a counter-clockwise direction") || explain==_("This path should have been drawn in a clockwise direction") || explain==_("The selected spline attains its extrema somewhere other than its endpoints") || explain==_("This glyph's advance width is different from the standard width") || explain==_("This glyph's vertical advance is different from the standard width") || explain==_("This glyph is not mapped to any unicode code point, but its name should be.") || explain==_("The selected point is not at integral coordinates") || explain==_("The selected point does not have integral control points") || explain==_("This glyph is mapped to a unicode code point which is different from its name."); GGadgetSetVisible(GWidgetGetControl(p->explainw,CID_Fix),fixable); if ( explain==_("This glyph contains a substitution or ligature entry which refers to an empty char") ) { snprintf(buf,sizeof(buf), _("%2$.20s refers to an empty character \"%1$.20s\""), p->badsubsname, p->badsubs_lsubtable->subtable_name ); } else if ( explain==_("This glyph contains anchor points from some, but not all anchor classes in a subtable") ) { snprintf(buf,sizeof(buf), _("There is no anchor for class %1$.30s in subtable %2$.30s"), p->missinganchor_class->name, p->missinganchor_class->subtable->subtable_name ); } else if ( explain==_("Two glyphs share the same unicode code point.\nChange the encoding to \"Glyph Order\" and use\nEdit->Select->Wildcard with the following code point") ) { snprintf(buf,sizeof(buf), _("U+%04x"), sc->unicodeenc ); } else if ( explain==_("Two glyphs have the same name.\nChange the encoding to \"Glyph Order\" and use\nEdit->Select->Wildcard with the following name") ) { snprintf(buf,sizeof(buf), _("%.40s"), sc->name ); } else if ( found==expected ) buf[0]='\0'; else { sprintf(buf,_("Found %1$.4g, expected %2$.4g"), (double) found, (double) expected ); } p->found = found; p->expected = expected; GGadgetSetTitle8(p->explainvals,buf); GGadgetSetChecked(p->ignoregadg,false); GHVBoxFitWindow(p->topbox); p->doneexplain = false; p->ignorethis = false; if ( sc!=p->lastcharopened || (CharView *) (sc->views)==NULL ) { if ( p->cvopened!=NULL && CVValid(p->fv->b.sf,p->lastcharopened,p->cvopened) ) GDrawDestroyWindow(p->cvopened->gw); p->cvopened = NULL; if ( (CharView *) (sc->views)!=NULL ) GDrawRaise(((CharView *) (sc->views))->gw); else p->cvopened = CharViewCreate(sc,p->fv,-1); GDrawSync(NULL); GDrawProcessPendingEvents(NULL); GDrawProcessPendingEvents(NULL); p->lastcharopened = sc; } if ( explain==_("This glyph contains a substitution or ligature entry which refers to an empty char") ) { SCCharInfo(sc,p->layer,p->fv->b.map,-1); GDrawSync(NULL); GDrawProcessPendingEvents(NULL); GDrawProcessPendingEvents(NULL); } SCUpdateAll(sc); /* We almost certainly just selected something */ GDrawSetVisible(p->explainw,true); GDrawRaise(p->explainw); while ( !p->doneexplain ) GDrawProcessOneEvent(NULL); /*GDrawSetVisible(p->explainw,false);*/ /* KDE gets unhappy about this and refuses to show the window later. I don't know why */ if ( p->cv!=NULL ) { CVClearSel(p->cv); } else { for ( spl = p->sc->layers[p->layer].splines; spl!=NULL; spl = spl->next ) { spl->first->selected = false; first = NULL; for ( spline = spl->first->next; spline!=NULL && spline!=first; spline=spline->to->next ) { spline->to->selected = false; if ( first==NULL ) first = spline; } } } } static void _ExplainIt(struct problems *p, int enc, char *explain, real found, real expected ) { ExplainIt(p,p->sc=SFMakeChar(p->fv->b.sf,p->fv->b.map,enc),explain,found,expected); } /* if they deleted a point or a splineset while we were explaining then we */ /* need to do some fix-ups. This routine detects a deletion and lets us know */ /* that more processing is needed */ static int missing(struct problems *p,SplineSet *test, SplinePoint *sp) { SplinePointList *spl, *check; SplinePoint *tsp; if ( !p->explain ) return( false ); if ( p->cv!=NULL ) spl = p->cv->b.layerheads[p->cv->b.drawmode]->splines; else spl = p->sc->layers[p->layer].splines; for ( check = spl; check!=test && check!=NULL; check = check->next ); if ( check==NULL ) return( true ); /* Deleted splineset */ if ( sp!=NULL ) { for ( tsp=test->first; tsp!=sp ; ) { if ( tsp->next==NULL ) return( true ); tsp = tsp->next->to; if ( tsp==test->first ) return( true ); } } return( false ); } static int missingspline(struct problems *p,SplineSet *test, Spline *spline) { SplinePointList *spl, *check; Spline *t, *first=NULL; if ( !p->explain ) return( false ); if ( p->cv!=NULL ) spl = p->cv->b.layerheads[p->cv->b.drawmode]->splines; else spl = p->sc->layers[p->layer].splines; for ( check = spl; check!=test && check!=NULL; check = check->next ); if ( check==NULL ) return( true ); /* Deleted splineset */ for ( t=test->first->next; t!=NULL && t!=first && t!=spline; t = t->to->next ) if ( first==NULL ) first = t; return( t!=spline ); } static int missinghint(StemInfo *base, StemInfo *findme) { while ( base!=NULL && base!=findme ) base = base->next; return( base==NULL ); } static int missingschint(StemInfo *findme, SplineChar *sc) { StemInfo *base; for ( base = sc->hstem; base!=NULL; base=base->next ) if ( base==findme ) return( false ); /* Hasn't been deleted */ for ( base = sc->vstem; base!=NULL; base=base->next ) if ( base==findme ) return( false ); return( true ); } static int HVITest(struct problems *p,BasePoint *to, BasePoint *from, Spline *spline, int hasia, real ia) { real yoff, xoff, angle; int ishor=false, isvert=false, isital=false; int isto; int type; BasePoint *base, *other; static char *hmsgs[5] = { N_("The selected line segment is nearly horizontal"), N_("The control point above the selected point is nearly horizontal"), N_("The control point below the selected point is nearly horizontal"), N_("The control point right of the selected point is nearly horizontal"), N_("The control point left of the selected point is nearly horizontal") }; static char *vmsgs[5] = { N_("The selected line segment is nearly vertical"), N_("The control point above the selected point is nearly vertical"), N_("The control point below the selected point is nearly vertical"), N_("The control point right of the selected point is nearly vertical"), N_("The control point left of the selected point is nearly vertical") }; static char *imsgs[5] = { N_("The selected line segment is near the italic angle"), N_("The control point above the selected point is near the italic angle"), N_("The control point below the selected point is near the italic angle"), N_("The control point right of the selected point is near the italic angle"), N_("The control point left of the selected point is near the italic angle") }; yoff = to->y-from->y; xoff = to->x-from->x; angle = atan2(yoff,xoff); if ( angle<0 ) angle += 3.1415926535897932; if ( angle<.1 || angle>3.1415926535897932-.1 ) { if ( yoff!=0 ) ishor = true; } else if ( angle>1.5707963-.1 && angle<1.5707963+.1 ) { if ( xoff!=0 ) isvert = true; } else if ( hasia && angle>ia-.1 && angle<ia+.1 ) { if ( angle<ia-.03 || angle>ia+.03 ) isital = true; } if ( ishor || isvert || isital ) { isto = false; if ( &spline->from->me==from || &spline->from->me==to ) spline->from->selected = true; if ( &spline->to->me==from || &spline->to->me==to ) spline->to->selected = isto = true; if ( from==&spline->from->me || from == &spline->to->me ) { base = from; other = to; } else { base = to; other = from; } if ( &spline->from->me==from && &spline->to->me==to ) { type = 0; /* Line */ if ( (ishor && xoff<0) || (isvert && yoff<0)) { base = from; other = to; } else { base = to; other = from; } } else if ( abs(yoff)>abs(xoff) ) type = ((yoff>0) ^ isto)?1:2; else type = ((xoff>0) ^ isto)?3:4; if ( ishor ) ExplainIt(p,p->sc,_(hmsgs[type]), other->y,base->y); else if ( isvert ) ExplainIt(p,p->sc,_(vmsgs[type]), other->x,base->x); else ExplainIt(p,p->sc,_(imsgs[type]),0,0); return( true ); } return( false ); } /* Is the control point outside of the spline segment when projected onto the */ /* vector between the end points of the spline segment? */ static int OddCPCheck(BasePoint *cp,BasePoint *base,BasePoint *v, SplinePoint *sp, struct problems *p) { real len = (cp->x-base->x)*v->x+ (cp->y-base->y)*v->y; real xoff, yoff; char *msg=NULL; if ( len<0 || len>1 || (len==0 && &sp->me!=base) || (len==1 && &sp->me==base)) { xoff = cp->x-sp->me.x; yoff = cp->y-sp->me.y; if ( fabs(yoff)>fabs(xoff) ) msg = yoff>0?_("The control point above the selected point is outside the spline segment"):_("The control point below the selected point is outside the spline segment"); else msg = xoff>0?_("The control point right of the selected point is outside the spline segment"):_("The control point left of the selected point is outside the spline segment"); sp->selected = true; ExplainIt(p,p->sc,msg, 0,0); return( true ); } return( false ); } static int Hint3Check(struct problems *p,StemInfo *h) { StemInfo *h2, *h3; /* Must be three hints to be interesting */ if ( h==NULL || (h2=h->next)==NULL || (h3=h2->next)==NULL ) return(false); if ( h3->next!=NULL ) { StemInfo *bad, *goods[3]; if ( h3->next->next!=NULL ) /* Don't try to find a subset with 5 */ return(false); if ( h->width==h2->width || h->width==h3->width ) { goods[0] = h; if ( h->width==h2->width ) { goods[1] = h2; if ( h->width==h3->width && h->width!=h3->next->width ) { goods[2] = h3; bad = h3->next; } else if ( h->width!=h3->width && h->width==h3->next->width ) { goods[2] = h3->next; bad = h3; } else return(false); } else if ( h->width==h3->width && h->width==h3->next->width ) { goods[1] = h3; goods[2] = h3->next; bad = h2; } else return(false); } else if ( h2->width == h3->width && h2->width==h3->next->width ) { bad = h; goods[0] = h2; goods[1] = h3; goods[2] = h3->next; } else return(false); if ( goods[2]->start-goods[1]->start == goods[1]->start-goods[0]->start ) { bad->active = true; ExplainIt(p,p->sc,_("This glyph has four hints, but if this one were omitted it would fit a stem3 hint"),0,0); if ( !missinghint(p->sc->hstem,bad) || !missinghint(p->sc->vstem,bad)) bad->active = false; if ( p->ignorethis ) p->stem3 = false; return( true ); } return(false); } if ( h->width==h2->width && h->width==h3->width && h2->start-h->start == h3->start-h2->start ) { if ( p->showexactstem3 ) { ExplainIt(p,p->sc,_("This glyph can use a stem3 hint"),0,0); if ( p->ignorethis ) p->showexactstem3 = false; } return( false ); /* It IS a stem3, so don't complain */ } if ( h->width==h2->width && h->width==h3->width ) { if ( h2->start-h->start+p->near > h3->start-h2->start && h2->start-h->start-p->near < h3->start-h2->start ) { ExplainIt(p,p->sc,_("The counters between these hints are not the same size, bad for a stem3 hint"),0,0); if ( p->ignorethis ) p->stem3 = false; return( true ); } return( false ); } if ( (h2->start-h->start+p->near > h3->start-h2->start && h2->start-h->start-p->near < h3->start-h2->start ) || (h2->start-h->start-h->width+p->near > h3->start-h2->start-h2->width && h2->start-h->start-h->width-p->near < h3->start-h2->start-h2->width )) { if ( h->width==h2->width ) { if ( h->width+p->near > h3->width && h->width-p->near < h3->width ) { h3->active = true; ExplainIt(p,p->sc,_("This hint has the wrong width for a stem3 hint"),0,0); if ( !missinghint(p->sc->hstem,h3) || !missinghint(p->sc->vstem,h3)) h3->active = false; if ( p->ignorethis ) p->stem3 = false; return( true ); } else return( false ); } if ( h->width==h3->width ) { if ( h->width+p->near > h2->width && h->width-p->near < h2->width ) { h2->active = true; ExplainIt(p,p->sc,_("This hint has the wrong width for a stem3 hint"),0,0); if ( !missinghint(p->sc->hstem,h2) || !missinghint(p->sc->vstem,h2)) h2->active = false; if ( p->ignorethis ) p->stem3 = false; return( true ); } else return( false ); } if ( h2->width==h3->width ) { if ( h2->width+p->near > h->width && h2->width-p->near < h->width ) { h->active = true; ExplainIt(p,p->sc,_("This hint has the wrong width for a stem3 hint"),0,0); if ( !missinghint(p->sc->hstem,h) || !missinghint(p->sc->vstem,h)) h->active = false; if ( p->ignorethis ) p->stem3 = false; return( true ); } else return( false ); } } return( false ); } static int probRefDepth(RefChar *r,int layer) { RefChar *ref; int cur, max=0; for ( ref= r->sc->layers[layer].refs; ref!=NULL; ref=ref->next ) { cur = probRefDepth(ref,layer); if ( cur>max ) max = cur; } return( max+1 ); } static int SCRefDepth(SplineChar *sc,int layer) { RefChar *ref; int cur, max=0; for ( ref= sc->layers[layer].refs; ref!=NULL; ref=ref->next ) { cur = probRefDepth(ref,layer); if ( cur>max ) max = cur; } return( max ); } static int SPLPointCnt(SplinePointList *spl) { SplinePoint *sp; int cnt=0; for ( ; spl!=NULL; spl = spl->next ) { for ( sp = spl->first; ; ) { ++cnt; if ( sp->prev!=NULL && !sp->prev->knownlinear ) { if ( sp->prev->order2 ) ++cnt; else cnt += 2; } if ( sp->next==NULL ) break; sp = sp->next->to; if ( sp==spl->first ) break; } } return( cnt ); } static RefChar *FindRefOfSplineInLayer(Layer *layer,Spline *spline) { RefChar *r; SplineSet *ss; Spline *s, *first; for ( r=layer->refs; r!=NULL; r=r->next ) { for ( ss=r->layers[0].splines; ss!=NULL; ss=ss->next ) { first = NULL; for ( s=ss->first->next ; s!=NULL && s!=first; s=s->to->next ) { if ( first==NULL ) first = s; if ( s==spline ) return( r ); } } } return( NULL ); } static int SCProblems(CharView *cv,SplineChar *sc,struct problems *p) { SplineSet *spl, *test; Spline *spline, *first; Layer *cur; SplinePoint *sp, *nsp; int needsupdate=false, changed=false; StemInfo *h; RefChar *r1, *r2; int uni; DBounds bb; restart: if ( cv!=NULL ) { needsupdate = CVClearSel(cv); cur = cv->b.layerheads[cv->b.drawmode]; spl = cur->splines; sc = cv->b.sc; } else { for ( spl = sc->layers[p->layer].splines; spl!=NULL; spl = spl->next ) { if ( spl->first->selected ) { needsupdate = true; spl->first->selected = false; } first = NULL; for ( spline = spl->first->next; spline!=NULL && spline!=first; spline=spline->to->next ) { if ( spline->to->selected ) { needsupdate = true; spline->to->selected = false; } if ( first==NULL ) first = spline; } } cur = &sc->layers[p->layer]; spl = cur->splines; } p->sc = sc; if (( p->ptnearhint || p->hintwidthnearval || p->hintwithnopt ) && sc->changedsincelasthinted && !sc->manualhints ) SplineCharAutoHint(sc,p->layer,NULL); if ( p->openpaths ) { for ( test=spl; test!=NULL && !p->finish; test=test->next ) { /* I'm also including in "open paths" the special case of a */ /* singleton point with connects to itself */ if ( test->first!=NULL && ( test->first->prev==NULL || ( test->first->prev == test->first->next && test->first->noprevcp && test->first->nonextcp))) { changed = true; test->first->selected = test->last->selected = true; ExplainIt(p,sc,_("The two selected points are the endpoints of an open path"),0,0); if ( p->ignorethis ) { p->openpaths = false; break; } if ( missing(p,test,NULL)) goto restart; } } } if ( p->intersectingpaths && !p->finish ) { Spline *s, *s2; int found; spl = LayerAllSplines(cur); found = SplineSetIntersect(spl,&s,&s2); spl = LayerUnAllSplines(cur); if ( found ) { changed = true; if ( (r1 = FindRefOfSplineInLayer(cur,s))!=NULL ) r1->selected = true; else { s->from->selected = true; s->to->selected = true; } if ( (r2 = FindRefOfSplineInLayer(cur,s2))!=NULL ) r2->selected = true; else { s2->from->selected = true; s2->to->selected = true; } ExplainIt(p,sc,_("The paths that make up this glyph intersect one another"),0,0); if ( p->ignorethis ) { p->intersectingpaths = false; /* break; */ } } } if ( p->nonintegral && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->nonintegral; test=test->next ) { sp = test->first; do { int interp = SPInterpolate(sp); int badme = interp ? (rint(2*sp->me.x)!=2*sp->me.x || rint(2*sp->me.y)!=2*sp->me.y) : (rint(sp->me.x)!=sp->me.x || rint(sp->me.y)!=sp->me.y); if ( badme || rint(sp->nextcp.x)!=sp->nextcp.x || rint(sp->nextcp.y)!=sp->nextcp.y || rint(sp->prevcp.x)!=sp->prevcp.x || rint(sp->prevcp.y)!=sp->prevcp.y ) { changed = true; sp->selected = true; if ( badme ) ExplainIt(p,sc,_("The selected point is not at integral coordinates"),0,0); else ExplainIt(p,sc,_("The selected point does not have integral control points"),0,0); if ( p->ignorethis ) { p->nonintegral = false; break; } if ( missing(p,test,nsp)) goto restart; } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->nonintegral ) break; } } if ( p->pointstoofar && !p->finish ) { SplinePoint *lastsp=NULL; BasePoint lastpt; memset(&lastpt,0,sizeof(lastpt)); for ( test=spl; test!=NULL && !p->finish && p->pointstoofar; test=test->next ) { sp = test->first; do { if ( BPTooFar(&lastpt,&sp->prevcp) || BPTooFar(&sp->prevcp,&sp->me) || BPTooFar(&sp->me,&sp->nextcp)) { changed = true; sp->selected = true; if ( lastsp==NULL ) { ExplainIt(p,sc,_("The selected point is too far from the origin"),0,0); } else { lastsp->selected = true; ExplainIt(p,sc,_("The selected points (or the intermediate control points) are too far apart"),0,0); } if ( p->ignorethis ) { p->pointstoofar = false; break; } if ( missing(p,test,sp)) goto restart; } memcpy(&lastpt,&sp->nextcp,sizeof(lastpt)); if ( sp->next==NULL ) break; sp = sp->next->to; if ( sp==test->first ) { memcpy(&lastpt,&sp->me,sizeof(lastpt)); break; } } while ( !p->finish ); if ( !p->pointstoofar ) break; } } if ( p->pointstooclose && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->pointstooclose; test=test->next ) { sp = test->first; do { if ( sp->next==NULL ) break; nsp = sp->next->to; if ( (nsp->me.x-sp->me.x)*(nsp->me.x-sp->me.x) + (nsp->me.y-sp->me.y)*(nsp->me.y-sp->me.y) < 2*2 ) { changed = true; sp->selected = nsp->selected = true; ExplainIt(p,sc,_("The selected points are too close to each other"),0,0); if ( p->ignorethis ) { p->pointstooclose = false; break; } if ( missing(p,test,nsp)) goto restart; } sp = nsp; } while ( sp!=test->first && !p->finish ); if ( !p->pointstooclose ) break; } } if ( p->xnearval && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->xnearval; test=test->next ) { sp = test->first; do { if ( sp->me.x-p->xval<p->near && p->xval-sp->me.x<p->near && sp->me.x!=p->xval ) { changed = true; sp->selected = true; ExplainIt(p,sc,_("The x coord of the selected point is near the specified value"),sp->me.x,p->xval); if ( p->ignorethis ) { p->xnearval = false; break; } if ( missing(p,test,sp)) goto restart; } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->xnearval ) break; } } if ( p->ynearval && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->ynearval; test=test->next ) { sp = test->first; do { if ( sp->me.y-p->yval<p->near && p->yval-sp->me.y<p->near && sp->me.y != p->yval ) { changed = true; sp->selected = true; ExplainIt(p,sc,_("The y coord of the selected point is near the specified value"),sp->me.y,p->yval); if ( p->ignorethis ) { p->ynearval = false; break; } if ( missing(p,test,sp)) goto restart; } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->ynearval ) break; } } if ( p->ynearstd && !p->finish ) { real expected; char *msg; for ( test=spl; test!=NULL && !p->finish && p->ynearstd; test=test->next ) { sp = test->first; do { if (( sp->me.y-p->xheight<p->near && p->xheight-sp->me.y<p->near && sp->me.y!=p->xheight ) || ( sp->me.y-p->caph<p->near && p->caph-sp->me.y<p->near && sp->me.y!=p->caph && sp->me.y!=p->ascent ) || ( sp->me.y-p->ascent<p->near && p->ascent-sp->me.y<p->near && sp->me.y!=p->caph && sp->me.y!=p->ascent ) || ( sp->me.y-p->descent<p->near && p->descent-sp->me.y<p->near && sp->me.y!=p->descent ) || ( sp->me.y<p->near && -sp->me.y<p->near && sp->me.y!=0 ) ) { changed = true; sp->selected = true; if ( sp->me.y<p->near && -sp->me.y<p->near ) { msg = _("The y coord of the selected point is near the baseline"); expected = 0; } else if ( sp->me.y-p->xheight<p->near && p->xheight-sp->me.y<p->near ) { msg = _("The y coord of the selected point is near the xheight"); expected = p->xheight; } else if ( sp->me.y-p->caph<p->near && p->caph-sp->me.y<p->near ) { msg = _("The y coord of the selected point is near the cap height"); expected = p->caph; } else if ( sp->me.y-p->ascent<p->near && p->ascent-sp->me.y<p->near ) { msg = _("The y coord of the selected point is near the ascender height"); expected = p->ascent; } else { msg = _("The y coord of the selected point is near the descender height"); expected = p->descent; } ExplainIt(p,sc,msg,sp->me.y,expected); if ( p->ignorethis ) { p->ynearstd = false; break; } if ( missing(p,test,sp)) goto restart; } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->ynearstd ) break; } } if ( p->linenearstd && !p->finish ) { real ia = (90-p->fv->b.sf->italicangle)*(3.1415926535897932/180); int hasia = p->fv->b.sf->italicangle!=0; for ( test=spl; test!=NULL && !p->finish && p->linenearstd; test = test->next ) { first = NULL; for ( spline = test->first->next; spline!=NULL && spline!=first && !p->finish; spline=spline->to->next ) { if ( spline->knownlinear ) { if ( HVITest(p,&spline->to->me,&spline->from->me,spline, hasia, ia)) { changed = true; if ( p->ignorethis ) { p->linenearstd = false; break; } if ( missingspline(p,test,spline)) goto restart; } } if ( first==NULL ) first = spline; } if ( !p->linenearstd ) break; } } if ( p->cpnearstd && !p->finish ) { real ia = (90-p->fv->b.sf->italicangle)*(3.1415926535897932/180); int hasia = p->fv->b.sf->italicangle!=0; for ( test=spl; test!=NULL && !p->finish && p->linenearstd; test = test->next ) { first = NULL; for ( spline = test->first->next; spline!=NULL && spline!=first && !p->finish; spline=spline->to->next ) { if ( !spline->knownlinear ) { if ( !spline->from->nonextcp && HVITest(p,&spline->from->nextcp,&spline->from->me,spline, hasia, ia)) { changed = true; if ( p->ignorethis ) { p->cpnearstd = false; break; } if ( missingspline(p,test,spline)) goto restart; } if ( !spline->to->noprevcp && HVITest(p,&spline->to->me,&spline->to->prevcp,spline, hasia, ia)) { changed = true; if ( p->ignorethis ) { p->cpnearstd = false; break; } if ( missingspline(p,test,spline)) goto restart; } } if ( first==NULL ) first = spline; } if ( !p->cpnearstd ) break; } } if ( p->cpodd && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->linenearstd; test = test->next ) { first = NULL; for ( spline = test->first->next; spline!=NULL && spline!=first && !p->finish; spline=spline->to->next ) { if ( !spline->knownlinear ) { BasePoint v; real len; v.x = spline->to->me.x-spline->from->me.x; v.y = spline->to->me.y-spline->from->me.y; len = /*sqrt*/(v.x*v.x+v.y*v.y); v.x /= len; v.y /= len; if ( !spline->from->nonextcp && OddCPCheck(&spline->from->nextcp,&spline->from->me,&v, spline->from,p)) { changed = true; if ( p->ignorethis ) { p->cpodd = false; break; } if ( missingspline(p,test,spline)) goto restart; } if ( !spline->to->noprevcp && OddCPCheck(&spline->to->prevcp,&spline->from->me,&v, spline->to,p)) { changed = true; if ( p->ignorethis ) { p->cpodd = false; break; } if ( missingspline(p,test,spline)) goto restart; } } if ( first==NULL ) first = spline; } if ( !p->cpodd ) break; } } if ( p->irrelevantcontrolpoints && !p->finish ) { for ( test=spl; test!=NULL && !p->finish && p->irrelevantcontrolpoints; test = test->next ) { for ( sp=test->first; !p->finish && p->irrelevantcontrolpoints; ) { int either = false; if ( sp->prev!=NULL ) { double len = sqrt((sp->me.x-sp->prev->from->me.x)*(sp->me.x-sp->prev->from->me.x) + (sp->me.y-sp->prev->from->me.y)*(sp->me.y-sp->prev->from->me.y)); double cplen = sqrt((sp->me.x-sp->prevcp.x)*(sp->me.x-sp->prevcp.x) + (sp->me.y-sp->prevcp.y)*(sp->me.y-sp->prevcp.y)); if ( cplen!=0 && cplen<p->irrelevantfactor*len ) either = true; } if ( sp->next!=NULL ) { double len = sqrt((sp->me.x-sp->next->to->me.x)*(sp->me.x-sp->next->to->me.x) + (sp->me.y-sp->next->to->me.y)*(sp->me.y-sp->next->to->me.y)); double cplen = sqrt((sp->me.x-sp->nextcp.x)*(sp->me.x-sp->nextcp.x) + (sp->me.y-sp->nextcp.y)*(sp->me.y-sp->nextcp.y)); if ( cplen!=0 && cplen<p->irrelevantfactor*len ) either = true; } if ( either ) { sp->selected = true; ExplainIt(p,sc,_("This glyph contains control points which are probably too close to the main points to alter the look of the spline"),0,0); if ( p->ignorethis ) { p->irrelevantcontrolpoints = false; break; } } if ( sp->next==NULL ) break; sp = sp->next->to; if ( sp==test->first ) break; } } } if ( p->hintwithnopt && !p->finish ) { int anys, anye; restarthhint: for ( h=sc->hstem; h!=NULL ; h=h->next ) { anys = anye = false; for ( test=spl; test!=NULL && !p->finish && (!anys || !anye); test=test->next ) { sp = test->first; do { if (sp->me.y==h->start ) anys = true; if (sp->me.y==h->start+h->width ) anye = true; if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); } if ( h->ghost && ( anys || anye )) /* Ghost hints only define one edge */; else if ( !anys || !anye ) { h->active = true; changed = true; ExplainIt(p,sc,_("This hint does not control any points"),0,0); if ( !missinghint(sc->hstem,h)) h->active = false; if ( p->ignorethis ) { p->hintwithnopt = false; break; } if ( missinghint(sc->hstem,h)) goto restarthhint; } } restartvhint: for ( h=sc->vstem; h!=NULL && p->hintwithnopt && !p->finish; h=h->next ) { anys = anye = false; for ( test=spl; test!=NULL && !p->finish && (!anys || !anye); test=test->next ) { sp = test->first; do { if (sp->me.x==h->start ) anys = true; if (sp->me.x==h->start+h->width ) anye = true; if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); } if ( !anys || !anye ) { h->active = true; changed = true; ExplainIt(p,sc,_("This hint does not control any points"),0,0); if ( p->ignorethis ) { p->hintwithnopt = false; break; } if ( missinghint(sc->vstem,h)) goto restartvhint; h->active = false; } } } if ( p->ptnearhint && !p->finish ) { real found, expected; h = NULL; for ( test=spl; test!=NULL && !p->finish && p->ptnearhint; test=test->next ) { sp = test->first; do { int hs = false, vs = false; for ( h=sc->hstem; h!=NULL; h=h->next ) { if (( sp->me.y-h->start<p->near && h->start-sp->me.y<p->near && sp->me.y!=h->start ) || ( sp->me.y-h->start+h->width<p->near && h->start+h->width-sp->me.y<p->near && sp->me.y!=h->start+h->width )) { found = sp->me.y; if ( sp->me.y-h->start<p->near && h->start-sp->me.y<p->near ) expected = h->start; else expected = h->start+h->width; h->active = true; hs = true; break; } } if ( !hs ) { for ( h=sc->vstem; h!=NULL; h=h->next ) { if (( sp->me.x-h->start<p->near && h->start-sp->me.x<p->near && sp->me.x!=h->start ) || ( sp->me.x-h->start+h->width<p->near && h->start+h->width-sp->me.x<p->near && sp->me.x!=h->start+h->width )) { found = sp->me.x; if ( sp->me.x-h->start<p->near && h->start-sp->me.x<p->near ) expected = h->start; else expected = h->start+h->width; h->active = true; vs = true; break; } } } if ( hs || vs ) { changed = true; sp->selected = true; ExplainIt(p,sc,hs?_("The selected point is near a horizontal stem hint"):_("The selected point is near a vertical stem hint"),found,expected); if ( h!=NULL ) h->active = false; if ( p->ignorethis ) { p->ptnearhint = false; break; } if ( missing(p,test,sp)) goto restart; } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->ptnearhint ) break; } } if ( p->overlappedhints && !p->finish && !cur->order2 && spl!=NULL ) { int anyhm=0; for ( test=spl; test!=NULL && !p->finish && p->overlappedhints; test=test->next ) { sp = test->first; do { if ( sp->hintmask!=NULL ) { anyhm = true; h = SCHintOverlapInMask(sc,sp->hintmask); if ( h!=NULL ) { sp->selected = true; h->active = true; changed = true; ExplainIt(p,sc,_("The hint mask of the selected point contains overlapping hints"),0,0); if ( p->ignorethis ) p->overlappedhints = false; if ( missing(p,test,sp)) goto restart; if ( missingschint(h,sc)) goto restart; h->active = false; sp->selected = false; if ( !p->overlappedhints ) break; } } if ( sp->next==NULL ) break; sp = sp->next->to; } while ( sp!=test->first && !p->finish ); if ( !p->overlappedhints ) break; } if ( p->overlappedhints && !anyhm ) { h = SCHintOverlapInMask(sc,NULL); if ( h!=NULL ) { h->active = true; changed = true; ExplainIt(p,sc,_("There are no hint masks in this layer but there are overlapping hints."),0,0); if ( missingschint(h,sc)) goto restart; h->active = false; } } } if ( p->hintwidthnearval && !p->finish ) { StemInfo *hs = NULL, *vs = NULL; for ( h=sc->hstem; h!=NULL; h=h->next ) { if ( h->width-p->widthval<p->near && p->widthval-h->width<p->near && h->width!=p->widthval ) { h->active = true; hs = h; break; } } for ( h=sc->vstem; h!=NULL; h=h->next ) { if ( h->width-p->widthval<p->near && p->widthval-h->width<p->near && h->width!=p->widthval ) { h->active = true; vs = h; break; } } if ( hs || vs ) { changed = true; ExplainIt(p,sc,hs?_("This glyph contains a horizontal hint near the specified width"):_("This glyph contains a vertical hint near the specified width"), hs?hs->width:vs->width,p->widthval); if ( hs!=NULL && !missinghint(sc->hstem,hs)) hs->active = false; if ( vs!=NULL && !missinghint(sc->vstem,vs)) vs->active = false; if ( p->ignorethis ) p->hintwidthnearval = false; else if ( (hs!=NULL && missinghint(sc->hstem,hs)) && ( vs!=NULL && missinghint(sc->vstem,vs))) goto restart; } } if ( p->stem3 && !p->finish ) changed |= Hint3Check(p,sc->hstem); if ( p->stem3 && !p->finish ) changed |= Hint3Check(p,sc->vstem); if ( p->direction && !p->finish ) { SplineSet **base, *ret, *ss; Spline *s, *s2; Layer *layer; int lastscan= -1; int self_intersects, dir; if ( cv!=NULL ) layer = cv->b.layerheads[cv->b.drawmode]; else layer = &sc->layers[p->layer]; ss = LayerAllSplines(layer); self_intersects = SplineSetIntersect(ss,&s,&s2); LayerUnAllSplines(layer); if ( self_intersects ) ff_post_error(_("This glyph self-intersects"),_("This glyph self-intersects. Checking for correct direction is meaningless until that is fixed")); else { base = &layer->splines; while ( !p->finish && (ret=SplineSetsDetectDir(base,&lastscan))!=NULL ) { sp = ret->first; changed = true; while ( 1 ) { sp->selected = true; if ( sp->next==NULL ) break; sp = sp->next->to; if ( sp==ret->first ) break; } dir = SplinePointListIsClockwise(ret); if ( dir==-1 ) ExplainIt(p,sc,_("This path probably intersects itself (though I could not find that when\n I checked for intersections), look closely at the corners"),0,0); else if ( dir==1 ) ExplainIt(p,sc,_("This path should have been drawn in a counter-clockwise direction"),0,0); else ExplainIt(p,sc,_("This path should have been drawn in a clockwise direction"),0,0); if ( p->ignorethis ) { p->direction = false; break; } } } } if ( p->missingextrema && !p->finish ) { SplineSet *ss; Spline *s, *first; double len2, bound2 = p->sc->parent->extrema_bound; double x,y; extended extrema[4]; if ( bound2<=0 ) bound2 = (p->sc->parent->ascent + p->sc->parent->descent)/32.0; bound2 *= bound2; ae_restart: for ( ss = sc->layers[p->layer].splines; ss!=NULL && !p->finish; ss=ss->next ) { ae2_restart: first = NULL; for ( s=ss->first->next ; s!=NULL && s!=first && !p->finish; s=s->to->next ) { if ( first==NULL ) first = s; if ( s->acceptableextrema ) continue; /* If marked as good, don't check it */ /* rough appoximation to spline's length */ x = (s->to->me.x-s->from->me.x); y = (s->to->me.y-s->from->me.y); len2 = x*x + y*y; /* short splines (serifs) need not to have points at their extrema */ /* But how do we define "short"? */ if ( len2>bound2 && Spline2DFindExtrema(s,extrema)>0 ) { s->from->selected = true; s->to->selected = true; ExplainIt(p,sc,_("The selected spline attains its extrema somewhere other than its endpoints"),0,0); if ( !SSExistsInLayer(ss,sc->layers[p->layer].splines) ) goto ae_restart; if ( !SplineExistsInSS(s,ss)) goto ae2_restart; if ( !SplineExistsInSS(first,ss)) first = s; if ( p->ignorethis ) { p->missingextrema = false; break; } } } if ( !p->missingextrema ) break; } } if ( p->flippedrefs && !p->finish && ( cv==NULL || cv->b.drawmode==dm_fore )) { RefChar *ref; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) ref->selected = false; for ( ref = sc->layers[p->layer].refs; !p->finish && ref!=NULL ; ref = ref->next ) { if ( ref->transform[0]*ref->transform[3]<0 || (ref->transform[0]==0 && ref->transform[1]*ref->transform[2]>0)) { changed = true; ref->selected = true; ExplainIt(p,sc,_("This reference has been flipped, so the paths in it are drawn backwards"),0,0); ref->selected = false; if ( p->ignorethis ) { p->flippedrefs = false; break; } } } } if ( p->refsbadtransformttf && !p->finish ) { RefChar *ref; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) ref->selected = false; for ( ref = sc->layers[p->layer].refs; !p->finish && ref!=NULL ; ref = ref->next ) { if ( ref->transform[0]>=2 || ref->transform[0]<-2 || ref->transform[1]>=2 || ref->transform[1]<-2 || ref->transform[2]>=2 || ref->transform[2]<-2 || ref->transform[3]>=2 || ref->transform[3]<-2 || rint(ref->transform[4])!=ref->transform[4] || rint(ref->transform[5])!=ref->transform[5]) { changed = true; ref->selected = true; ExplainIt(p,sc,_("This reference has a transformation matrix which cannot be expressed in truetype.\nAll entries (except translation) must be between [-2.0,2.0).\nTranslation must be integral."),0,0); ref->selected = false; if ( p->ignorethis ) { p->refsbadtransformttf = false; break; } } } } if ( p->mixedcontoursrefs && !p->finish ) { RefChar *ref; int hasref=0, hascontour = sc->layers[p->layer].splines!=NULL; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) { ref->selected = false; if ( ref->transform[0]>=2 || ref->transform[0]<-2 || ref->transform[1]>=2 || ref->transform[1]<-2 || ref->transform[2]>=2 || ref->transform[2]<-2 || ref->transform[3]>=2 || ref->transform[3]<-2 ) hascontour = true; else hasref = true; if ( hascontour && hasref ) { changed = true; ref->selected = true; ExplainIt(p,sc,_("This glyph contains both contours and references.\n(or contains a reference which has a bad transformation matrix and counts as a contour).\nThis cannot be expressed in the TrueType glyph format."),0,0); ref->selected = false; if ( p->ignorethis ) { p->mixedcontoursrefs = false; break; } } } } if ( p->refsbadtransformps && !p->finish ) { RefChar *ref; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) ref->selected = false; for ( ref = sc->layers[p->layer].refs; !p->finish && ref!=NULL ; ref = ref->next ) { if ( ref->transform[0]!=1.0 || ref->transform[1]!=0 || ref->transform[2]!=0 || ref->transform[3]!= 1.0 ) { changed = true; ref->selected = true; ExplainIt(p,sc,_("This reference has a transformation matrix which cannot be expressed in Type1/2 fonts.\nNo scaling or rotation allowed."),0,0); ref->selected = false; if ( p->ignorethis ) { p->refsbadtransformps = false; break; } } } } if ( p->multusemymetrics && !p->finish ) { RefChar *ref, *found; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) ref->selected = false; found = NULL; for ( ref = sc->layers[p->layer].refs; !p->finish && ref!=NULL ; ref = ref->next ) { if ( ref->use_my_metrics ) { if ( found==NULL ) found = ref; else { changed = true; ref->selected = true; found->selected = true; ExplainIt(p,sc,_("Both selected references have use-my-metrics set"),0,0); ref->selected = false; found->selected = false; if ( p->ignorethis ) { p->multusemymetrics = false; break; } } } } } if ( p->ptmatchrefsoutofdate && !p->finish ) { RefChar *ref; for ( ref = sc->layers[p->layer].refs; ref!=NULL ; ref = ref->next ) ref->selected = false; for ( ref = sc->layers[p->layer].refs; !p->finish && ref!=NULL ; ref = ref->next ) { if ( ref->point_match_out_of_date ) { changed = true; ref->selected = true; ExplainIt(p,sc,_("This reference uses point-matching but it refers to a glyph\n(or a previous reference refers to a glyph)\nwhose points have been renumbered."),0,0); ref->selected = false; if ( p->ignorethis ) { p->ptmatchrefsoutofdate = false; break; } } } } if ( p->toodeeprefs && !p->finish ) { int cnt=SCRefDepth(sc,p->layer); if ( cnt>p->refdepthmax ) { changed = true; ExplainIt(p,sc,_("References are nested more deeply in this glyph than the maximum allowed"),cnt,p->refdepthmax); if ( p->ignorethis ) p->toodeeprefs = false; } } if ( p->toomanypoints && !p->finish ) { int cnt=0; RefChar *r; cnt = SPLPointCnt(sc->layers[p->layer].splines); for ( r=sc->layers[p->layer].refs; r!=NULL ; r=r->next ) cnt += SPLPointCnt(r->layers[0].splines); if ( cnt>p->pointsmax ) { changed = true; ExplainIt(p,sc,_("There are more points in this glyph than the maximum allowed"),cnt,p->pointsmax); if ( p->ignorethis ) p->toomanypoints = false; } } if ( p->toomanyhints && !p->finish ) { int cnt=0; for ( h=sc->hstem; h!=NULL; h=h->next ) ++cnt; for ( h=sc->vstem; h!=NULL; h=h->next ) ++cnt; if ( cnt>p->hintsmax ) { changed = true; ExplainIt(p,sc,_("There are more hints in this glyph than the maximum allowed"),cnt,p->hintsmax); if ( p->ignorethis ) p->toomanyhints = false; } } if ( p->bitmaps && !p->finish && SCWorthOutputting(sc)) { BDFFont *bdf; for ( bdf=sc->parent->bitmaps; bdf!=NULL; bdf=bdf->next ) { if ( sc->orig_pos>=bdf->glyphcnt || bdf->glyphs[sc->orig_pos]==NULL ) { changed = true; ExplainIt(p,sc,_("This outline glyph is missing a bitmap version"),0,0); if ( p->ignorethis ) p->bitmaps = false; break; } } } if ( p->bitmapwidths && !p->finish && SCWorthOutputting(sc)) { BDFFont *bdf; double em = (sc->parent->ascent+sc->parent->descent); for ( bdf=sc->parent->bitmaps; bdf!=NULL; bdf=bdf->next ) { if ( sc->orig_pos<bdf->glyphcnt && bdf->glyphs[sc->orig_pos]!=NULL ) { BDFChar *bc = bdf->glyphs[sc->orig_pos]; if ( bc->width!= (int) rint( (sc->width*bdf->pixelsize)/em ) ) { changed = true; ExplainIt(p,sc,_("This outline glyph's advance width is different from that of the bitmap's"), bc->width,rint( (sc->width*bdf->pixelsize)/em )); if ( p->ignorethis ) p->bitmapwidths = false; break; } } } } if ( p->advancewidth && !p->finish && SCWorthOutputting(sc)) { if ( sc->width!=p->advancewidthval ) { changed = true; ExplainIt(p,sc,_("This glyph's advance width is different from the standard width"),sc->width,p->advancewidthval); if ( p->ignorethis ) p->advancewidth = false; } } if ( p->vadvancewidth && !p->finish && SCWorthOutputting(sc)) { if ( sc->vwidth!=p->vadvancewidthval ) { changed = true; ExplainIt(p,sc,_("This glyph's vertical advance is different from the standard width"),sc->vwidth,p->vadvancewidthval); if ( p->ignorethis ) p->vadvancewidth = false; } } if ( (p->bbymax || p->bbxmax || p->bbymin || p->bbxmin) && !p->finish && SCWorthOutputting(sc)) { SplineCharFindBounds(sc,&bb); if ( p->bbymax && bb.maxy > p->bbymax_val ) { changed = true; ExplainIt(p,sc,_("This glyph is taller than desired"),bb.maxy,p->bbymax_val); if ( p->ignorethis ) p->bbymax = false; } if ( p->bbymin && bb.miny < p->bbymin_val ) { changed = true; ExplainIt(p,sc,_("This glyph extends further below the baseline than desired"),bb.miny,p->bbymin_val); if ( p->ignorethis ) p->bbymin = false; } if ( p->bbxmax && bb.maxx > p->bbxmax_val ) { changed = true; ExplainIt(p,sc,_("This glyph is wider than desired"),bb.maxx,p->bbxmax_val); if ( p->ignorethis ) p->bbxmax = false; } if ( p->bbxmin && bb.minx < p->bbxmin_val ) { changed = true; ExplainIt(p,sc,_("This glyph extends left further than desired"),bb.minx,p->bbxmin_val); if ( p->ignorethis ) p->bbxmin = false; } } if ( p->badsubs && !p->finish ) { PST *pst; char *pt, *end; int ch; for ( pst = sc->possub ; pst!=NULL; pst=pst->next ) { if ( pst->type==pst_substitution || pst->type==pst_alternate || pst->type==pst_multiple || pst->type==pst_ligature ) { for ( pt=pst->u.subs.variant; *pt!='\0' ; pt=end ) { end = strchr(pt,' '); if ( end==NULL ) end=pt+strlen(pt); ch = *end; *end = '\0'; if ( !SCWorthOutputting(SFGetChar(sc->parent,-1,pt)) ) { changed = true; p->badsubsname = copy(pt); *end = ch; p->badsubs_lsubtable = pst->subtable; ExplainIt(p,sc,_("This glyph contains a substitution or ligature entry which refers to an empty char"),0,0); free(p->badsubsname); if ( p->ignorethis ) p->badsubs = false; } else *end = ch; while ( *end==' ' ) ++end; if ( !p->badsubs ) break; } if ( !p->badsubs ) break; } } } if ( p->missinganchor && !p->finish ) { forever { p->missinganchor_class = SCValidateAnchors(sc); if ( p->missinganchor_class == NULL ) break; ExplainIt(p,sc,_("This glyph contains anchor points from some, but not all anchor classes in a subtable"),0,0); if ( p->ignorethis ) p->missinganchor = false; break; } } if ( p->multuni && !p->finish && sc->unicodeenc!=-1 ) { SplineFont *sf = sc->parent; int i; for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL && sf->glyphs[i]!=sc ) { if ( sf->glyphs[i]->unicodeenc == sc->unicodeenc ) { changed = true; p->glyphname = sf->glyphs[i]->name; ExplainIt(p,sc,_("Two glyphs share the same unicode code point.\nChange the encoding to \"Glyph Order\" and use\nEdit->Select->Wildcard with the following code point"),0,0); if ( p->ignorethis ) p->multuni = false; } } } if ( p->multname && !p->finish ) { SplineFont *sf = sc->parent; int i; for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL && sf->glyphs[i]!=sc ) { if ( strcmp(sf->glyphs[i]->name, sc->name)==0 ) { changed = true; p->glyphenc = i; ExplainIt(p,sc,_("Two glyphs have the same name.\nChange the encoding to \"Glyph Order\" and use\nEdit->Select->Wildcard with the following name"),0,0); if ( p->ignorethis ) p->multname = false; } } } if ( p->uninamemismatch && !p->finish && strcmp(sc->name,".notdef")!=0 && strcmp(sc->name,".null")!=0 && strcmp(sc->name,"nonmarkingreturn")!=0 && (uni = UniFromName(sc->name,sc->parent->uni_interp,p->fv->b.map->enc))!= -1 && sc->unicodeenc != uni ) { changed = true; p->glyphenc = sc->orig_pos; if ( sc->unicodeenc==-1 ) ExplainIt(p,sc,_("This glyph is not mapped to any unicode code point, but its name should be."),0,0); else if ( strcmp(sc->name,"alefmaksurainitialarabic")==0 || strcmp(sc->name,"alefmaksuramedialarabic")==0 ) ExplainIt(p,sc,_("The use of names 'alefmaksurainitialarabic' and 'alefmaksuramedialarabic' is discouraged."),0,0); else ExplainIt(p,sc,_("This glyph is mapped to a unicode code point which is different from its name."),0,0); if ( p->ignorethis ) p->uninamemismatch = false; } if ( needsupdate || changed ) SCUpdateAll(sc); return( changed ); } static int CIDCheck(struct problems *p,int cid) { int found = false; if ( (p->cidmultiple || p->cidblank) && !p->finish ) { SplineFont *csf = p->fv->b.cidmaster; int i, cnt; for ( i=cnt=0; i<csf->subfontcnt; ++i ) if ( cid<csf->subfonts[i]->glyphcnt && SCWorthOutputting(csf->subfonts[i]->glyphs[cid]) ) ++cnt; if ( cnt>1 && p->cidmultiple ) { _ExplainIt(p,cid,_("This glyph is defined in more than one of the CID subfonts"),cnt,1); if ( p->ignorethis ) p->cidmultiple = false; found = true; } else if ( cnt==0 && p->cidblank ) { _ExplainIt(p,cid,_("This glyph is not defined in any of the CID subfonts"),0,0); if ( p->ignorethis ) p->cidblank = false; found = true; } } return( found ); } static char *missinglookup(struct problems *p,char *str) { int i; for ( i=0; i<p->rpl_cnt; ++i ) if ( strcmp(str,p->mg[i].search)==0 ) return( p->mg[i].rpl ); return( NULL ); } static void mgreplace(char **base, char *str,char *end, char *new, SplineChar *sc, PST *pst) { PST *p, *ps; if ( new==NULL || *new=='\0' ) { if ( *base==str && *end=='\0' && sc!=NULL ) { /* We deleted the last name from the pst, it is meaningless, remove it */ if ( sc->possub==pst ) sc->possub = pst->next; else { for ( p = sc->possub, ps=p->next; ps!=NULL && ps!=pst; p=ps, ps=ps->next ); if ( ps!=NULL ) p->next = pst->next; } pst->next = NULL; PSTFree(pst); } else if ( *end=='\0' ) *str = '\0'; else strcpy(str,end+1); /* Skip the space */ } else { char *res = galloc(strlen(*base)+strlen(new)-(end-str)+1); strncpy(res,*base,str-*base); strcpy(res+(str-*base),new); strcat(res,end); free(*base); *base = res; } } static void ClearMissingState(struct problems *p) { int i; if ( p->mg!=NULL ) { for ( i=0; i<p->rpl_cnt; ++i ) { free(p->mg[i].search); free(p->mg[i].rpl); } free(p->mg); } else free(p->mlt); p->mlt = NULL; p->mg = NULL; p->rpl_cnt = p->rpl_max = 0; } enum missingglyph_type { mg_pst, mg_fpst, mg_kern, mg_vkern, mg_asm }; struct mgask_data { GWindow gw; uint8 done, skipped; uint32 tag; char **_str, *start, *end; SplineChar *sc; PST *pst; struct problems *p; }; static void mark_to_replace(struct problems *p,struct mgask_data *d, char *rpl) { int ch; if ( p->rpl_cnt >= p->rpl_max ) { if ( p->rpl_max == 0 ) p->mg = galloc((p->rpl_max = 30)*sizeof(struct mgrpl)); else p->mg = grealloc(p->mg,(p->rpl_max += 30)*sizeof(struct mgrpl)); } ch = *d->end; *d->end = '\0'; p->mg[p->rpl_cnt].search = copy( d->start ); p->mg[p->rpl_cnt++].rpl = copy( rpl ); *d->end = ch; } #define CID_Always 1001 #define CID_RplText 1002 #define CID_Ignore 1003 #define CID_Rpl 1004 #define CID_Skip 1005 #define CID_Delete 1006 static int MGA_RplChange(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) { struct mgask_data *d = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *rpl = _GGadgetGetTitle(g); GGadgetSetEnabled(GWidgetGetControl(d->gw,CID_Rpl),*rpl!=0); } return( true ); } static int MGA_Rpl(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct mgask_data *d = GDrawGetUserData(GGadgetGetWindow(g)); const unichar_t *_rpl = _GGadgetGetTitle(GWidgetGetControl(d->gw,CID_RplText)); char *rpl = cu_copy(_rpl); if ( GGadgetIsChecked(GWidgetGetControl(d->gw,CID_Always))) mark_to_replace(d->p,d,rpl); mgreplace(d->_str,d->start,d->end,rpl,d->sc,d->pst); free(rpl); d->done = true; } return( true ); } static int MGA_Delete(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct mgask_data *d = GDrawGetUserData(GGadgetGetWindow(g)); if ( GGadgetIsChecked(GWidgetGetControl(d->gw,CID_Always))) mark_to_replace(d->p,d,""); mgreplace(d->_str,d->start,d->end,"",d->sc,d->pst); d->done = true; } return( true ); } static int MGA_Skip(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct mgask_data *d = GDrawGetUserData(GGadgetGetWindow(g)); d->done = d->skipped = true; } return( true ); } static int mgask_e_h(GWindow gw, GEvent *event) { if ( event->type==et_close ) { struct mgask_data *d = GDrawGetUserData(gw); d->done = d->skipped = true; } else if ( event->type==et_char ) { if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) { help("problems.html"); return( true ); } return( false ); } return( true ); } static int mgAsk(struct problems *p,char **_str,char *str, char *end,uint32 tag, SplineChar *sc,enum missingglyph_type which,void *data) { char buffer[200]; static char *pstnames[] = { "", N_("position"), N_("pair"), N_("substitution"), N_("alternate subs"), N_("multiple subs"), N_("ligature"), NULL }; static char *fpstnames[] = { N_("Contextual position"), N_("Contextual substitution"), N_("Chaining position"), N_("Chaining substitution"), N_("Reverse chaining subs"), NULL }; static char *asmnames[] = { N_("Indic reordering"), N_("Contextual substitution"), N_("Lig"), NULL, N_("Simple"), N_("Contextual insertion"), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, N_("Kerning"), NULL }; PST *pst = data; FPST *fpst = data; ASM *sm = data; KernClass *kc = data; char end_ch; GRect pos; GWindow gw; GWindowAttrs wattrs; GGadgetCreateData gcd[12]; GTextInfo label[12]; struct mgask_data d; int blen = GIntGetResource(_NUM_Buttonsize), ptwidth; int k, rplpos; end_ch = *end; *end = '\0'; if ( which == mg_pst ) { snprintf(buffer,sizeof(buffer), _("Glyph %1$.50s with a %2$s from lookup subtable %3$.50s"), sc->name, _(pstnames[pst->type]), pst->subtable->subtable_name ); } else if ( which == mg_fpst ) snprintf(buffer,sizeof(buffer), _("%1$s from lookup subtable %2$.50s"), _(fpstnames[fpst->type-pst_contextpos]), fpst->subtable->subtable_name ); else if ( which == mg_asm ) snprintf(buffer,sizeof(buffer), _("%1$s from lookup subtable %2$.50s"), _(asmnames[sm->type]), sm->subtable->subtable_name ); else snprintf(buffer,sizeof(buffer), _("%1$s from lookup subtable %2$.50s"), which==mg_kern ? _("Kerning Class"): _("Vertical Kerning Class"), kc->subtable->subtable_name ); memset(&d,'\0',sizeof(d)); d._str = _str; d.start = str; d.end = end; d.sc = sc; d.pst = which==mg_pst ? data : NULL; d.p = p; d.tag = tag; memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_centered|wam_restrict|wam_isdlg; wattrs.event_masks = ~(1<<et_charup); wattrs.is_dlg = 1; wattrs.restrict_input_to_me = 1; wattrs.centered = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Check for missing glyph names"); pos.x = pos.y = 0; ptwidth = 3*blen+GGadgetScale(80); pos.width =GDrawPointsToPixels(NULL,ptwidth); pos.height = GDrawPointsToPixels(NULL,180); d.gw = gw = GDrawCreateTopWindow(NULL,&pos,mgask_e_h,&d,&wattrs); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); k=0; label[k].text = (unichar_t *) buffer; label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = 6; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLabelCreate; label[k].text = (unichar_t *) _(" refers to a missing glyph"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+13; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLabelCreate; label[k].text = (unichar_t *) str; label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+13; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLabelCreate; label[k].text = (unichar_t *) _("Replace With:"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+16; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k++].creator = GLabelCreate; rplpos = k; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+13; gcd[k].gd.pos.width = ptwidth-20; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k].gd.cid = CID_RplText; gcd[k].gd.handle_controlevent = MGA_RplChange; gcd[k++].creator = GTextFieldCreate; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+30; gcd[k].gd.flags = gg_visible | gg_enabled; label[k].text = (unichar_t *) _("Always"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.cid = CID_Always; gcd[k++].creator = GCheckBoxCreate; label[k].text = (unichar_t *) _("Ignore this problem in the future"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+20; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k].gd.cid = CID_Ignore; gcd[k++].creator = GCheckBoxCreate; gcd[k].gd.pos.x = 10-3; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+30 -3; gcd[k].gd.pos.width = -1; gcd[k].gd.flags = gg_visible | gg_but_default; label[k].text = (unichar_t *) _("Replace"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = MGA_Rpl; gcd[k].gd.cid = CID_Rpl; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.x = 10+blen+(ptwidth-3*blen-GGadgetScale(20))/2; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3; gcd[k].gd.pos.width = -1; gcd[k].gd.flags = gg_visible | gg_enabled; label[k].text = (unichar_t *) _("Remove"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = MGA_Delete; gcd[k].gd.cid = CID_Delete; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.x = -10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y; gcd[k].gd.pos.width = -1; gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel; label[k].text = (unichar_t *) _("Skip"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = MGA_Skip; gcd[k].gd.cid = CID_Skip; gcd[k++].creator = GButtonCreate; gcd[k].gd.pos.x = 2; gcd[k].gd.pos.y = 2; gcd[k].gd.pos.width = pos.width-4; gcd[k].gd.pos.height = pos.height-4; gcd[k].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels; gcd[k++].creator = GGroupCreate; GGadgetsCreate(gw,gcd); *end = end_ch; GDrawSetVisible(gw,true); while ( !d.done ) GDrawProcessOneEvent(NULL); if ( GGadgetIsChecked(GWidgetGetControl(gw,CID_Ignore))) p->missingglyph = false; GDrawDestroyWindow(gw); return( !d.skipped ); } static int StrMissingGlyph(struct problems *p,char **_str,SplineChar *sc,int which, void *data) { char *end, ch, *str = *_str, *new; int off; int found = false; SplineFont *sf = p->fv!=NULL ? p->fv->b.sf : p->cv!=NULL ? p->cv->b.sc->parent : p->msc->parent; SplineChar *ssc; int changed=false; if ( str==NULL ) return( false ); while ( *str ) { if ( p->finish || !p->missingglyph ) break; while ( *str==' ' ) ++str; for ( end=str; *end!='\0' && *end!=' '; ++end ); ch = *end; *end='\0'; if ( strcmp(str,MAC_DELETED_GLYPH_NAME)==0 ) ssc = (SplineChar *) 1; else ssc = SFGetChar(sf,-1,str); *end = ch; if ( ssc==NULL ) { off = end-*_str; if ( (new = missinglookup(p,str))!=NULL ) { mgreplace(_str, str,end, new, sc, which==mg_pst ? data : NULL); changed = true; off += (strlen(new)-(end-str)); } else { if ( mgAsk(p,_str,str,end,0,sc,which,data)) { changed = true; off = 0; } found = true; } if ( changed ) { PST *test; if ( which==mg_pst ) { for ( test = sc->possub; test!=NULL && test!=data; test=test->next ); if ( test==NULL ) /* Entire pst was removed */ return( true ); *_str = test->u.subs.variant; } end = *_str+off; } } str = end; } return( found ); } static int SCMissingGlyph(struct problems *p,SplineChar *sc) { PST *pst, *next; int found = false; if ( !p->missingglyph || p->finish || sc==NULL ) return( false ); for ( pst=sc->possub; pst!=NULL; pst=next ) { next = pst->next; switch ( pst->type ) { case pst_pair: found |= StrMissingGlyph(p,&pst->u.pair.paired,sc,mg_pst,pst); break; case pst_substitution: case pst_alternate: case pst_multiple: case pst_ligature: found |= StrMissingGlyph(p,&pst->u.subs.variant,sc,mg_pst,pst); break; } } return( found ); } static int KCMissingGlyph(struct problems *p,KernClass *kc,int isv) { int i; int found = false; int which = isv ? mg_vkern : mg_kern; for ( i=0; i<kc->first_cnt; ++i ) if ( kc->firsts[i]!=NULL ) found |= StrMissingGlyph(p,&kc->firsts[i],NULL,which,kc); for ( i=1; i<kc->second_cnt; ++i ) found |= StrMissingGlyph(p,&kc->seconds[i],NULL,which,kc); return( found ); } static int FPSTMissingGlyph(struct problems *p,FPST *fpst) { int i,j; int found = false; switch ( fpst->format ) { case pst_glyphs: for ( i=0; i<fpst->rule_cnt; ++i ) for ( j=0; j<3; ++j ) found |= StrMissingGlyph(p,&(&fpst->rules[i].u.glyph.names)[j], NULL,mg_fpst,fpst); break; case pst_class: for ( i=1; i<3; ++i ) for ( j=0; j<(&fpst->nccnt)[i]; ++j ) found |= StrMissingGlyph(p,&(&fpst->nclass)[i][j],NULL,mg_fpst,fpst); break; case pst_reversecoverage: found |= StrMissingGlyph(p,&fpst->rules[0].u.rcoverage.replacements,NULL,mg_fpst,fpst); /* fall through */; case pst_coverage: for ( i=1; i<3; ++i ) for ( j=0; j<(&fpst->rules[0].u.coverage.ncnt)[i]; ++j ) found |= StrMissingGlyph(p,&(&fpst->rules[0].u.coverage.ncovers)[i][j],NULL,mg_fpst,fpst); break; } return( found ); } static int ASMMissingGlyph(struct problems *p,ASM *sm) { int j; int found = false; for ( j=4; j<sm->class_cnt; ++j ) found |= StrMissingGlyph(p,&sm->classes[j],NULL,mg_asm,sm); return( found ); } static int LookupFeaturesMissScript(struct problems *p,OTLookup *otl,OTLookup *nested, uint32 script, SplineFont *sf, char *glyph_name) { OTLookup *invokers, *any; struct lookup_subtable *subs; int i,l, ret; int found = false; FeatureScriptLangList *fsl; struct scriptlanglist *sl; char buffer[400]; char *buts[4]; if ( script==DEFAULT_SCRIPT ) return( false ); if ( otl->features == NULL ) { /* No features invoke us, so presume that we are to be invoked by a */ /* contextual lookup, and check its scripts rather than ours */ if ( nested!=NULL ) { /* There is no need to have a nested contextual lookup */ /* so we don't support them */ return(false); } any = NULL; for ( invokers=otl->lookup_type>=gpos_start?sf->gpos_lookups:sf->gsub_lookups; invokers!=NULL ; invokers = invokers->next ) { for ( subs=invokers->subtables; subs!=NULL; subs=subs->next ) { if ( subs->fpst!=NULL ) { FPST *fpst = subs->fpst; for ( i=0; i<fpst->rule_cnt; ++i ) { struct fpst_rule *r = &fpst->rules[i]; for ( l=0; l<r->lookup_cnt; ++l ) if ( r->lookups[l].lookup == otl ) { found |= LookupFeaturesMissScript(p,invokers,otl,script,sf,glyph_name); any = invokers; } } } } } if ( any==NULL ) { /* No opentype contextual lookup uses this lookup with no features*/ /* so it appears totally useless. But a mac feature might I guess*/ /* so don't complain */ } } else { for ( fsl = otl->features; fsl!=NULL; fsl=fsl->next ) { for ( sl=fsl->scripts; sl!=NULL; sl=sl->next ) { if ( sl->script==script ) break; } if ( sl!=NULL ) break; } if ( fsl==NULL ) { buffer[0]='\0'; if ( nested!=NULL ) snprintf(buffer,sizeof(buffer), _("The lookup %.30s which invokes lookup %.30s is active " "for glyph %.30s which has script '%c%c%c%c', yet this script does not " "appear in any of the features which apply the lookup.\n" "Would you like to add this script to one of those features?"), otl->lookup_name, nested->lookup_name, glyph_name, script>>24, script>>16, script>>8, script); else snprintf(buffer,sizeof(buffer), _("The lookup %.30s is active for glyph %.30s which has script " "'%c%c%c%c', yet this script does not appear in any of the features which " "apply the lookup.\n\n" "Would you like to add this script to one of those features?"), otl->lookup_name, glyph_name, script>>24, script>>16, script>>8, script); buts[0] = _("_OK"); buts[1] = _("_Skip"); buts[2]="_Ignore"; buts[3] = NULL; ret = ff_ask(_("Missing Script"),(const char **) buts,0,1,buffer); if ( ret==0 ) { sl = chunkalloc(sizeof(struct scriptlanglist)); sl->script = script; sl->lang_cnt = 1; sl->langs[0] = DEFAULT_LANG; sl->next = otl->features->scripts; otl->features->scripts = sl; sf->changed = true; } else if ( ret==2 ) p->missingscriptinfeature = false; return( true ); } } return( found ); } static int SCMissingScriptFeat(struct problems *p,SplineFont *sf,SplineChar *sc) { PST *pst; int found = false; uint32 script; AnchorPoint *ap; if ( !p->missingscriptinfeature || p->finish || sc==NULL ) return( false ); script = SCScriptFromUnicode(sc); for ( pst=sc->possub; pst!=NULL; pst=pst->next ) if ( pst->subtable!=NULL ) found |= LookupFeaturesMissScript(p,pst->subtable->lookup,NULL,script,sf,sc->name); for ( ap=sc->anchor; ap!=NULL; ap=ap->next ) found |= LookupFeaturesMissScript(p,ap->anchor->subtable->lookup,NULL,script,sf,sc->name); return( found ); } static int StrMissingScript(struct problems *p,SplineFont *sf,OTLookup *otl,char *class) { char *pt, *start; int ch; SplineChar *sc; uint32 script; int found = 0; if ( class==NULL ) return( false ); for ( pt=class; *pt && p->missingscriptinfeature; ) { while ( *pt==' ' ) ++pt; if ( *pt=='\0' ) break; for ( start=pt; *pt && *pt!=' '; ++pt ); ch = *pt; *pt='\0'; sc = SFGetChar(sf,-1,start); *pt = ch; if ( sc!=NULL ) { script = SCScriptFromUnicode(sc); found |= LookupFeaturesMissScript(p,otl,NULL,script,sf,sc->name); } } return( found ); } static int KCMissingScriptFeat(struct problems *p,SplineFont *sf, KernClass *kc,int isv) { int i; int found = false; OTLookup *otl = kc->subtable->lookup; for ( i=0; i<kc->first_cnt; ++i ) found |= StrMissingScript(p,sf,otl,kc->firsts[i]); return( found ); } static int FPSTMissingScriptFeat(struct problems *p,SplineFont *sf,FPST *fpst) { int i,j; int found = false; OTLookup *otl = fpst->subtable->lookup; switch ( fpst->format ) { case pst_glyphs: for ( i=0; i<fpst->rule_cnt; ++i ) for ( j=0; j<3; ++j ) found |= StrMissingScript(p,sf,otl,(&fpst->rules[i].u.glyph.names)[j]); break; case pst_class: for ( i=1; i<3; ++i ) for ( j=0; j<(&fpst->nccnt)[i]; ++j ) found |= StrMissingScript(p,sf,otl,(&fpst->nclass)[i][j]); break; case pst_reversecoverage: found |= StrMissingScript(p,sf,otl,fpst->rules[0].u.rcoverage.replacements); /* fall through */; case pst_coverage: for ( i=1; i<3; ++i ) for ( j=0; j<(&fpst->rules[0].u.coverage.ncnt)[i]; ++j ) found |= StrMissingScript(p,sf,otl,(&fpst->rules[0].u.coverage.ncovers)[i][j]); break; } return( found ); } static int CheckForATT(struct problems *p) { int found = false; int i,k; FPST *fpst; ASM *sm; KernClass *kc; SplineFont *_sf, *sf; static char *buts[3]; buts[0] = _("_Yes"); buts[1] = _("_No"); buts[2] = NULL; _sf = p->fv->b.sf; if ( _sf->cidmaster ) _sf = _sf->cidmaster; if ( p->missingglyph && !p->finish ) { if ( p->cv!=NULL ) found = SCMissingGlyph(p,p->cv->b.sc); else if ( p->msc!=NULL ) found = SCMissingGlyph(p,p->msc); else { k=0; do { if ( _sf->subfonts==NULL ) sf = _sf; else sf = _sf->subfonts[k++]; for ( i=0; i<sf->glyphcnt && !p->finish; ++i ) if ( sf->glyphs[i]!=NULL ) found |= SCMissingGlyph(p,sf->glyphs[i]); } while ( k<_sf->subfontcnt && !p->finish ); for ( kc=_sf->kerns; kc!=NULL && !p->finish; kc=kc->next ) found |= KCMissingGlyph(p,kc,false); for ( kc=_sf->vkerns; kc!=NULL && !p->finish; kc=kc->next ) found |= KCMissingGlyph(p,kc,true); for ( fpst=_sf->possub; fpst!=NULL && !p->finish && p->missingglyph; fpst=fpst->next ) found |= FPSTMissingGlyph(p,fpst); for ( sm=_sf->sm; sm!=NULL && !p->finish && p->missingglyph; sm=sm->next ) found |= ASMMissingGlyph(p,sm); } ClearMissingState(p); } if ( p->missingscriptinfeature && !p->finish ) { if ( p->cv!=NULL ) found = SCMissingScriptFeat(p,_sf,p->cv->b.sc); else if ( p->msc!=NULL ) found = SCMissingScriptFeat(p,_sf,p->msc); else { k=0; do { if ( _sf->subfonts==NULL ) sf = _sf; else sf = _sf->subfonts[k++]; for ( i=0; i<sf->glyphcnt && !p->finish; ++i ) if ( sf->glyphs[i]!=NULL ) found |= SCMissingScriptFeat(p,_sf,sf->glyphs[i]); } while ( k<_sf->subfontcnt && !p->finish ); for ( kc=_sf->kerns; kc!=NULL && !p->finish; kc=kc->next ) found |= KCMissingScriptFeat(p,_sf,kc,false); for ( kc=_sf->vkerns; kc!=NULL && !p->finish; kc=kc->next ) found |= KCMissingScriptFeat(p,_sf,kc,true); for ( fpst=_sf->possub; fpst!=NULL && !p->finish && p->missingglyph; fpst=fpst->next ) found |= FPSTMissingScriptFeat(p,_sf,fpst); /* Apple's state machines don't have the concept of "script" */ /* for their feature/settings */ } } return( found ); } static void DoProbs(struct problems *p) { int i, ret=false, gid; SplineChar *sc; BDFFont *bdf; ret = CheckForATT(p); if ( p->cv!=NULL ) { ret |= SCProblems(p->cv,NULL,p); ret |= CIDCheck(p,p->cv->b.sc->orig_pos); } else if ( p->msc!=NULL ) { ret |= SCProblems(NULL,p->msc,p); ret |= CIDCheck(p,p->msc->orig_pos); } else { for ( i=0; i<p->fv->b.map->enccount && !p->finish; ++i ) if ( p->fv->b.selected[i] ) { sc = NULL; if ( (gid=p->fv->b.map->map[i])!=-1 && (sc = p->fv->b.sf->glyphs[gid])!=NULL ) { if ( SCProblems(NULL,sc,p)) { if ( sc!=p->lastcharopened ) { if ( (CharView *) (sc->views)!=NULL ) GDrawRaise(((CharView *) (sc->views))->gw); else CharViewCreate(sc,p->fv,-1); p->lastcharopened = sc; } ret = true; } } if ( !p->finish && p->bitmaps && !SCWorthOutputting(sc)) { for ( bdf=p->fv->b.sf->bitmaps; bdf!=NULL; bdf=bdf->next ) if ( i<bdf->glyphcnt && bdf->glyphs[i]!=NULL ) { sc = SFMakeChar(p->fv->b.sf,p->fv->b.map,i); ExplainIt(p,sc,_("This blank outline glyph has an unexpected bitmap version"),0,0); ret = true; } } ret |= CIDCheck(p,i); } } if ( !ret ) ff_post_error(_("No problems found"),_("No problems found")); } static void FigureStandardHeights(struct problems *p) { BlueData bd; QuickBlues(p->fv->b.sf,p->layer,&bd); p->xheight = bd.xheight; p->caph = bd.caph; p->ascent = bd.ascent; p->descent = bd.descent; } static int Prob_DoAll(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct problems *p = GDrawGetUserData(GGadgetGetWindow(g)); int set = GGadgetGetCid(g)==CID_SetAll; GWindow gw = GGadgetGetWindow(g); static int cbs[] = { CID_OpenPaths, CID_IntersectingPaths, CID_PointsTooClose, CID_XNear, CID_MissingExtrema, CID_PointsTooFar, CID_NonIntegral, CID_YNear, CID_YNearStd, CID_HintNoPt, CID_PtNearHint, CID_HintWidthNear, CID_LineStd, CID_Direction, CID_CpStd, CID_CpOdd, CID_FlippedRefs, CID_Bitmaps, CID_AdvanceWidth, CID_BadSubs, CID_MissingAnchor, CID_MissingGlyph, CID_MissingScriptInFeature, CID_Stem3, CID_IrrelevantCP, CID_TooManyPoints, CID_TooManyHints, CID_TooDeepRefs, CID_BitmapWidths, CID_MultUni, CID_MultName, CID_PtMatchRefsOutOfDate, CID_RefBadTransformTTF, CID_RefBadTransformPS, CID_MixedContoursRefs, CID_UniNameMisMatch, CID_BBYMax, CID_BBYMin, CID_BBXMax, CID_BBXMin, CID_MultUseMyMetrics, CID_OverlappedHints, 0 }; int i; if ( p->fv->b.cidmaster!=NULL ) { GGadgetSetChecked(GWidgetGetControl(gw,CID_CIDMultiple),set); GGadgetSetChecked(GWidgetGetControl(gw,CID_CIDBlank),set); } if ( p->fv->b.sf->hasvmetrics ) GGadgetSetChecked(GWidgetGetControl(gw,CID_VAdvanceWidth),set); for ( i=0; cbs[i]!=0; ++i ) GGadgetSetChecked(GWidgetGetControl(gw,cbs[i]),set); } return( true ); } static int Prob_OK(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { GWindow gw = GGadgetGetWindow(g); struct problems *p = GDrawGetUserData(gw); int errs = false; openpaths = p->openpaths = GGadgetIsChecked(GWidgetGetControl(gw,CID_OpenPaths)); intersectingpaths = p->intersectingpaths = GGadgetIsChecked(GWidgetGetControl(gw,CID_IntersectingPaths)); nonintegral = p->nonintegral = GGadgetIsChecked(GWidgetGetControl(gw,CID_NonIntegral)); pointstooclose = p->pointstooclose = GGadgetIsChecked(GWidgetGetControl(gw,CID_PointsTooClose)); pointstoofar = p->pointstoofar = GGadgetIsChecked(GWidgetGetControl(gw,CID_PointsTooFar)); /*missing = p->missingextrema = GGadgetIsChecked(GWidgetGetControl(gw,CID_MissingExtrema))*/; doxnear = p->xnearval = GGadgetIsChecked(GWidgetGetControl(gw,CID_XNear)); doynear = p->ynearval = GGadgetIsChecked(GWidgetGetControl(gw,CID_YNear)); doynearstd = p->ynearstd = GGadgetIsChecked(GWidgetGetControl(gw,CID_YNearStd)); linestd = p->linenearstd = GGadgetIsChecked(GWidgetGetControl(gw,CID_LineStd)); cpstd = p->cpnearstd = GGadgetIsChecked(GWidgetGetControl(gw,CID_CpStd)); cpodd = p->cpodd = GGadgetIsChecked(GWidgetGetControl(gw,CID_CpOdd)); hintnopt = p->hintwithnopt = GGadgetIsChecked(GWidgetGetControl(gw,CID_HintNoPt)); ptnearhint = p->ptnearhint = GGadgetIsChecked(GWidgetGetControl(gw,CID_PtNearHint)); hintwidth = p->hintwidthnearval = GGadgetIsChecked(GWidgetGetControl(gw,CID_HintWidthNear)); missingextrema = p->missingextrema = GGadgetIsChecked(GWidgetGetControl(gw,CID_MissingExtrema)); direction = p->direction = GGadgetIsChecked(GWidgetGetControl(gw,CID_Direction)); flippedrefs = p->flippedrefs = GGadgetIsChecked(GWidgetGetControl(gw,CID_FlippedRefs)); bitmaps = p->bitmaps = GGadgetIsChecked(GWidgetGetControl(gw,CID_Bitmaps)); bitmapwidths = p->bitmapwidths = GGadgetIsChecked(GWidgetGetControl(gw,CID_BitmapWidths)); advancewidth = p->advancewidth = GGadgetIsChecked(GWidgetGetControl(gw,CID_AdvanceWidth)); bbymax = p->bbymax = GGadgetIsChecked(GWidgetGetControl(gw,CID_BBYMax)); bbymin = p->bbymin = GGadgetIsChecked(GWidgetGetControl(gw,CID_BBYMin)); bbxmax = p->bbxmax = GGadgetIsChecked(GWidgetGetControl(gw,CID_BBXMax)); bbxmin = p->bbxmin = GGadgetIsChecked(GWidgetGetControl(gw,CID_BBXMin)); irrelevantcp = p->irrelevantcontrolpoints = GGadgetIsChecked(GWidgetGetControl(gw,CID_IrrelevantCP)); multuni = p->multuni = GGadgetIsChecked(GWidgetGetControl(gw,CID_MultUni)); multname = p->multname = GGadgetIsChecked(GWidgetGetControl(gw,CID_MultName)); uninamemismatch = p->uninamemismatch = GGadgetIsChecked(GWidgetGetControl(gw,CID_UniNameMisMatch)); badsubs = p->badsubs = GGadgetIsChecked(GWidgetGetControl(gw,CID_BadSubs)); missinganchor = p->missinganchor = GGadgetIsChecked(GWidgetGetControl(gw,CID_MissingAnchor)); missingglyph = p->missingglyph = GGadgetIsChecked(GWidgetGetControl(gw,CID_MissingGlyph)); missingscriptinfeature = p->missingscriptinfeature = GGadgetIsChecked(GWidgetGetControl(gw,CID_MissingScriptInFeature)); toomanypoints = p->toomanypoints = GGadgetIsChecked(GWidgetGetControl(gw,CID_TooManyPoints)); toomanyhints = p->toomanyhints = GGadgetIsChecked(GWidgetGetControl(gw,CID_TooManyHints)); overlappedhints = p->overlappedhints = GGadgetIsChecked(GWidgetGetControl(gw,CID_OverlappedHints)); ptmatchrefsoutofdate = p->ptmatchrefsoutofdate = GGadgetIsChecked(GWidgetGetControl(gw,CID_PtMatchRefsOutOfDate)); multusemymetrics = p->multusemymetrics = GGadgetIsChecked(GWidgetGetControl(gw,CID_MultUseMyMetrics)); refsbadtransformttf = p->refsbadtransformttf = GGadgetIsChecked(GWidgetGetControl(gw,CID_RefBadTransformTTF)); refsbadtransformps = p->refsbadtransformps = GGadgetIsChecked(GWidgetGetControl(gw,CID_RefBadTransformPS)); mixedcontoursrefs = p->mixedcontoursrefs = GGadgetIsChecked(GWidgetGetControl(gw,CID_MixedContoursRefs)); toodeeprefs = p->toodeeprefs = GGadgetIsChecked(GWidgetGetControl(gw,CID_TooDeepRefs)); stem3 = p->stem3 = GGadgetIsChecked(GWidgetGetControl(gw,CID_Stem3)); if ( stem3 ) showexactstem3 = p->showexactstem3 = GGadgetIsChecked(GWidgetGetControl(gw,CID_ShowExactStem3)); if ( p->fv->b.cidmaster!=NULL ) { cidmultiple = p->cidmultiple = GGadgetIsChecked(GWidgetGetControl(gw,CID_CIDMultiple)); cidblank = p->cidblank = GGadgetIsChecked(GWidgetGetControl(gw,CID_CIDBlank)); } if ( p->fv->b.sf->hasvmetrics ) { vadvancewidth = p->vadvancewidth = GGadgetIsChecked(GWidgetGetControl(gw,CID_VAdvanceWidth)); } else p->vadvancewidth = false; p->explain = true; if ( doxnear ) p->xval = xval = GetReal8(gw,CID_XNearVal,U_("_X near¹"),&errs); if ( doynear ) p->yval = yval = GetReal8(gw,CID_YNearVal,U_("_Y near¹"),&errs); if ( hintwidth ) widthval = p->widthval = GetReal8(gw,CID_HintWidth,U_("Hint _Width Near¹"),&errs); if ( p->advancewidth ) advancewidthval = p->advancewidthval = GetInt8(gw,CID_AdvanceWidthVal,U_("Advance Width not"),&errs); if ( p->vadvancewidth ) vadvancewidthval = p->vadvancewidthval = GetInt8(gw,CID_VAdvanceWidthVal,U_("Vertical Advance not"),&errs); if ( p->bbymax ) bbymax_val = p->bbymax_val = GetInt8(gw,CID_BBYMaxVal,U_("Bounding box above"),&errs); if ( p->bbymin ) bbymin_val = p->bbymin_val = GetInt8(gw,CID_BBYMinVal,U_("Bounding box below"),&errs); if ( p->bbxmax ) bbxmax_val = p->bbxmax_val = GetInt8(gw,CID_BBXMaxVal,U_("Bounding box right of"),&errs); if ( p->bbxmin ) bbxmin_val = p->bbxmin_val = GetInt8(gw,CID_BBXMinVal,U_("Bounding box left of"),&errs); if ( toomanypoints ) p->pointsmax = pointsmax = GetInt8(gw,CID_PointsMax,_("_More points than:"),&errs); if ( toomanyhints ) p->hintsmax = hintsmax = GetInt8(gw,CID_HintsMax,_("_More hints than:"),&errs); if ( toodeeprefs ) /* GT: Refs is an abbreviation for References. Space is somewhat constrained here */ p->refdepthmax = refdepthmax = GetInt8(gw,CID_RefDepthMax,_("Refs neste_d deeper than:"),&errs); if ( irrelevantcp ) p->irrelevantfactor = irrelevantfactor = GetReal8(gw,CID_IrrelevantFactor,_("Irrelevant _Factor:"),&errs)/100.0; near = p->near = GetReal8(gw,CID_Near,_("Near"),&errs); if ( errs ) return( true ); lastsf = p->fv->b.sf; if ( doynearstd ) FigureStandardHeights(p); GDrawSetVisible(gw,false); if ( openpaths || intersectingpaths || pointstooclose || doxnear || doynear || doynearstd || linestd || hintnopt || ptnearhint || hintwidth || direction || p->cidmultiple || p->cidblank || p->flippedrefs || p->bitmaps || p->advancewidth || p->vadvancewidth || p->stem3 || p->bitmapwidths || p->missinganchor || p->irrelevantcontrolpoints || p->badsubs || p->missingglyph || p->missingscriptinfeature || nonintegral || pointstoofar || p->toomanypoints || p->toomanyhints || p->missingextrema || p->toodeeprefs || multuni || multname || uninamemismatch || p->ptmatchrefsoutofdate || p->refsbadtransformttf || p->multusemymetrics || p->overlappedhints || p->mixedcontoursrefs || p->refsbadtransformps || p->bbymax || p->bbxmax || p->bbymin || p->bbxmin ) { DoProbs(p); } p->done = true; } return( true ); } static void DummyFindProblems(CharView *cv) { struct problems p; memset(&p,0,sizeof(p)); p.fv = (FontView *) (cv->b.fv); p.cv=cv; p.layer = CVLayer((CharViewBase *) cv); p.map = cv->b.fv->map; p.lastcharopened = cv->b.sc; p.openpaths = true; p.intersectingpaths = true; p.direction = true; p.flippedrefs = true; p.missingextrema = true; p.toomanypoints = true; p.toomanyhints = true; p.pointstoofar = true; p.nonintegral = true; p.missinganchor = true; p.overlappedhints = true; p.pointsmax = 1500; p.hintsmax = 96; p.explain = true; DoProbs(&p); if ( p.explainw!=NULL ) GDrawDestroyWindow(p.explainw); } static int Prob_Cancel(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct problems *p = GDrawGetUserData(GGadgetGetWindow(g)); p->done = true; } return( true ); } static int Prob_TextChanged(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) { GGadgetSetChecked(GWidgetGetControl(GGadgetGetWindow(g),(intpt) GGadgetGetUserData(g)),true); } return( true ); } static int Prob_EnableExact(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_radiochanged ) { GGadgetSetEnabled(GWidgetGetControl(GGadgetGetWindow(g),CID_ShowExactStem3), GGadgetIsChecked(g)); } return( true ); } static int e_h(GWindow gw, GEvent *event) { if ( event->type==et_close ) { struct problems *p = GDrawGetUserData(gw); p->done = true; } return( event->type!=et_char ); } void FindProblems(FontView *fv,CharView *cv, SplineChar *sc) { GRect pos; GWindow gw; GWindowAttrs wattrs; GGadgetCreateData pgcd[15], pagcd[8], hgcd[10], rgcd[10], cgcd[5], mgcd[11], agcd[7], rfgcd[9]; GGadgetCreateData bbgcd[14]; GGadgetCreateData pboxes[6], paboxes[4], rfboxes[4], hboxes[5], aboxes[2], cboxes[2], bbboxes[2], rboxes[2], mboxes[5]; GGadgetCreateData *parray[12], *pharray1[4], *pharray2[4], *pharray3[7], *paarray[8], *paharray[4], *rfarray[9], *rfharray[4], *harray[9], *hharray1[4], *hharray2[4], *hharray3[4], *aarray[6], *carray[5], *bbarray[8][4], *rarray[7], *marray[7][2], *mharray1[4], *mharray2[5], *barray[10]; GTextInfo plabel[15], palabel[8], hlabel[9], rlabel[10], clabel[5], mlabel[10], alabel[7], rflabel[9]; GTextInfo bblabel[14]; GTabInfo aspects[9]; struct problems p; char xnbuf[20], ynbuf[20], widthbuf[20], nearbuf[20], awidthbuf[20], vawidthbuf[20], irrel[20], pmax[20], hmax[20], rmax[20], xxmaxbuf[20], xxminbuf[20], yymaxbuf[20], yyminbuf[20]; SplineChar *ssc; int i; SplineFont *sf; /*static GBox smallbox = { bt_raised, bs_rect, 2, 1, 0, 0, 0,0,0,0, COLOR_DEFAULT,COLOR_DEFAULT };*/ memset(&p,0,sizeof(p)); if ( fv==NULL ) fv = (FontView *) (cv->b.fv); p.fv = fv; p.cv=cv; p.msc = sc; if ( cv!=NULL ) p.lastcharopened = cv->b.sc; if ( fv!=NULL ) { p.map = fv->b.map; p.layer = fv->b.active_layer; } else if ( cv!=NULL ) { p.map = cv->b.fv->map; p.layer = CVLayer((CharViewBase *) cv); } else { p.map = sc->parent->fv->map; p.layer = sc->parent->fv->active_layer; } memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Find Problems"); pos.x = pos.y = 0; pos.width = GGadgetScale(GDrawPointsToPixels(NULL,218)); pos.height = GDrawPointsToPixels(NULL,294); gw = GDrawCreateTopWindow(NULL,&pos,e_h,&p,&wattrs); memset(&plabel,0,sizeof(plabel)); memset(&pgcd,0,sizeof(pgcd)); memset(&pboxes,0,sizeof(pboxes)); plabel[0].text = (unichar_t *) _("Non-_Integral coordinates"); plabel[0].text_is_1byte = true; plabel[0].text_in_resource = true; pgcd[0].gd.label = &plabel[0]; pgcd[0].gd.pos.x = 3; pgcd[0].gd.pos.y = 5; pgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( nonintegral ) pgcd[0].gd.flags |= gg_cb_on; pgcd[0].gd.popup_msg = (unichar_t *) _( "The coordinates of all points and control points in truetype\n" "must be integers (if they are not integers then FontForge will\n" "round them when it outputs them, potentially causing havoc).\n" "Even in PostScript fonts it is generally a good idea to use\n" "integral values."); pgcd[0].gd.cid = CID_NonIntegral; pgcd[0].creator = GCheckBoxCreate; parray[0] = &pgcd[0]; plabel[1].text = (unichar_t *) U_("_X near¹"); plabel[1].text_is_1byte = true; plabel[1].text_in_resource = true; pgcd[1].gd.label = &plabel[1]; pgcd[1].gd.mnemonic = 'X'; pgcd[1].gd.pos.x = 3; pgcd[1].gd.pos.y = pgcd[0].gd.pos.y+17; pgcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( doxnear ) pgcd[1].gd.flags |= gg_cb_on; pgcd[1].gd.popup_msg = (unichar_t *) _("Allows you to check that vertical stems in several\ncharacters start at the same location."); pgcd[1].gd.cid = CID_XNear; pgcd[1].creator = GCheckBoxCreate; pharray1[0] = &pgcd[1]; sprintf(xnbuf,"%g",xval); plabel[2].text = (unichar_t *) xnbuf; plabel[2].text_is_1byte = true; pgcd[2].gd.label = &plabel[2]; pgcd[2].gd.pos.x = 60; pgcd[2].gd.pos.y = pgcd[1].gd.pos.y-5; pgcd[2].gd.pos.width = 40; pgcd[2].gd.flags = gg_visible | gg_enabled; pgcd[2].gd.cid = CID_XNearVal; pgcd[2].gd.handle_controlevent = Prob_TextChanged; pgcd[2].data = (void *) CID_XNear; pgcd[2].creator = GTextFieldCreate; pharray1[1] = &pgcd[2]; pharray1[2] = GCD_Glue; pharray1[3] = NULL; pboxes[2].gd.flags = gg_enabled|gg_visible; pboxes[2].gd.u.boxelements = pharray1; pboxes[2].creator = GHBoxCreate; parray[1] = &pboxes[2]; plabel[3].text = (unichar_t *) U_("_Y near¹"); plabel[3].text_is_1byte = true; plabel[3].text_in_resource = true; pgcd[3].gd.label = &plabel[3]; pgcd[3].gd.mnemonic = 'Y'; pgcd[3].gd.pos.x = 3; pgcd[3].gd.pos.y = pgcd[1].gd.pos.y+24; pgcd[3].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( doynear ) pgcd[3].gd.flags |= gg_cb_on; pgcd[3].gd.popup_msg = (unichar_t *) _("Allows you to check that horizontal stems in several\ncharacters start at the same location."); pgcd[3].gd.cid = CID_YNear; pgcd[3].creator = GCheckBoxCreate; pharray2[0] = &pgcd[3]; sprintf(ynbuf,"%g",yval); plabel[4].text = (unichar_t *) ynbuf; plabel[4].text_is_1byte = true; pgcd[4].gd.label = &plabel[4]; pgcd[4].gd.pos.x = 60; pgcd[4].gd.pos.y = pgcd[3].gd.pos.y-5; pgcd[4].gd.pos.width = 40; pgcd[4].gd.flags = gg_visible | gg_enabled; pgcd[4].gd.cid = CID_YNearVal; pgcd[4].gd.handle_controlevent = Prob_TextChanged; pgcd[4].data = (void *) CID_YNear; pgcd[4].creator = GTextFieldCreate; pharray2[1] = &pgcd[4]; pharray2[2] = GCD_Glue; pharray2[3] = NULL; pboxes[3].gd.flags = gg_enabled|gg_visible; pboxes[3].gd.u.boxelements = pharray2; pboxes[3].creator = GHBoxCreate; parray[2] = &pboxes[3]; plabel[5].text = (unichar_t *) U_("Y near¹ _standard heights"); plabel[5].text_is_1byte = true; plabel[5].text_in_resource = true; pgcd[5].gd.label = &plabel[5]; pgcd[5].gd.mnemonic = 'S'; pgcd[5].gd.pos.x = 3; pgcd[5].gd.pos.y = pgcd[3].gd.pos.y+18; pgcd[5].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( doynearstd ) pgcd[5].gd.flags |= gg_cb_on; pgcd[5].gd.popup_msg = (unichar_t *) _("Allows you to find points which are slightly\noff from the baseline, xheight, cap height,\nascender, descender heights."); pgcd[5].gd.cid = CID_YNearStd; pgcd[5].creator = GCheckBoxCreate; parray[3] = &pgcd[5]; plabel[6].text = (unichar_t *) (fv->b.sf->italicangle==0?_("_Control Points near horizontal/vertical"):_("Control Points near horizontal/vertical/italic")); plabel[6].text_is_1byte = true; plabel[6].text_in_resource = true; pgcd[6].gd.label = &plabel[6]; pgcd[6].gd.mnemonic = 'C'; pgcd[6].gd.pos.x = 3; pgcd[6].gd.pos.y = pgcd[5].gd.pos.y+14; pgcd[6].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( cpstd ) pgcd[6].gd.flags |= gg_cb_on; pgcd[6].gd.popup_msg = (unichar_t *) _("Allows you to find control points which are almost,\nbut not quite horizontal or vertical\nfrom their base point\n(or at the italic angle)."); pgcd[6].gd.cid = CID_CpStd; pgcd[6].creator = GCheckBoxCreate; parray[4] = &pgcd[6]; plabel[7].text = (unichar_t *) _("Control Points _beyond spline"); plabel[7].text_is_1byte = true; plabel[7].text_in_resource = true; pgcd[7].gd.label = &plabel[7]; pgcd[7].gd.mnemonic = 'b'; pgcd[7].gd.pos.x = 3; pgcd[7].gd.pos.y = pgcd[6].gd.pos.y+14; pgcd[7].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( cpodd ) pgcd[7].gd.flags |= gg_cb_on; pgcd[7].gd.popup_msg = (unichar_t *) _("Allows you to find control points which when projected\nonto the line segment between the two end points lie\noutside of those end points"); pgcd[7].gd.cid = CID_CpOdd; pgcd[7].creator = GCheckBoxCreate; parray[5] = &pgcd[7]; plabel[8].text = (unichar_t *) _("Check for _irrelevant control points"); plabel[8].text_is_1byte = true; plabel[8].text_in_resource = true; pgcd[8].gd.label = &plabel[8]; pgcd[8].gd.pos.x = 3; pgcd[8].gd.pos.y = pgcd[7].gd.pos.y+14; pgcd[8].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( irrelevantcp ) pgcd[8].gd.flags |= gg_cb_on; pgcd[8].gd.popup_msg = (unichar_t *) _("Control points are irrelevant if they are too close to the main\npoint to make a significant difference in the shape of the curve."); pgcd[8].gd.cid = CID_IrrelevantCP; pgcd[8].creator = GCheckBoxCreate; parray[6] = &pgcd[8]; plabel[9].text = (unichar_t *) _("Irrelevant _Factor:"); plabel[9].text_is_1byte = true; pgcd[9].gd.label = &plabel[9]; pgcd[9].gd.pos.x = 20; pgcd[9].gd.pos.y = pgcd[8].gd.pos.y+17; pgcd[9].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; pgcd[9].gd.popup_msg = (unichar_t *) _("A control point is deemed irrelevant if the distance between it and the main\n(end) point is less than this times the distance between the two end points"); pgcd[9].creator = GLabelCreate; pharray3[0] = GCD_HPad10; pharray3[1] = &pgcd[9]; sprintf( irrel, "%g", irrelevantfactor*100 ); plabel[10].text = (unichar_t *) irrel; plabel[10].text_is_1byte = true; pgcd[10].gd.label = &plabel[10]; pgcd[10].gd.pos.x = 105; pgcd[10].gd.pos.y = pgcd[9].gd.pos.y-3; pgcd[10].gd.pos.width = 50; pgcd[10].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; pgcd[10].gd.popup_msg = (unichar_t *) _("A control point is deemed irrelevant if the distance between it and the main\n(end) point is less than this times the distance between the two end points"); pgcd[10].gd.cid = CID_IrrelevantFactor; pgcd[10].creator = GTextFieldCreate; pharray3[2] = &pgcd[10]; plabel[11].text = (unichar_t *) "%"; plabel[11].text_is_1byte = true; pgcd[11].gd.label = &plabel[11]; pgcd[11].gd.pos.x = 163; pgcd[11].gd.pos.y = pgcd[9].gd.pos.y; pgcd[11].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; pgcd[11].gd.popup_msg = (unichar_t *) _("A control point is deemed irrelevant if the distance between it and the main\n(end) point is less than this times the distance between the two end points"); pgcd[11].creator = GLabelCreate; pharray3[3] = &pgcd[11]; pharray3[4] = GCD_Glue; pharray3[5] = NULL; pboxes[4].gd.flags = gg_enabled|gg_visible; pboxes[4].gd.u.boxelements = pharray3; pboxes[4].creator = GHBoxCreate; parray[7] = &pboxes[4]; plabel[12].text = (unichar_t *) _("Poin_ts too close"); plabel[12].text_is_1byte = true; plabel[12].text_in_resource = true; pgcd[12].gd.label = &plabel[12]; pgcd[12].gd.pos.x = 3; pgcd[12].gd.pos.y = pgcd[11].gd.pos.y+14; pgcd[12].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( pointstooclose ) pgcd[12].gd.flags |= gg_cb_on; pgcd[12].gd.popup_msg = (unichar_t *) _("If two adjacent points on the same path are less than a few\nemunits apart they will cause problems for some of FontForge's\ncommands. PostScript shouldn't care though."); pgcd[12].gd.cid = CID_PointsTooClose; pgcd[12].creator = GCheckBoxCreate; parray[8] = &pgcd[12]; plabel[13].text = (unichar_t *) _("_Points too far"); plabel[13].text_is_1byte = true; plabel[13].text_in_resource = true; pgcd[13].gd.label = &plabel[13]; pgcd[13].gd.pos.x = 3; pgcd[13].gd.pos.y = pgcd[12].gd.pos.y+14; pgcd[13].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( pointstoofar ) pgcd[13].gd.flags |= gg_cb_on; pgcd[13].gd.popup_msg = (unichar_t *) _("Most font formats cannot specify adjacent points (or control points)\nwhich are more than 32767 em-units apart in either the x or y direction"); pgcd[13].gd.cid = CID_PointsTooFar; pgcd[13].creator = GCheckBoxCreate; parray[9] = &pgcd[13]; parray[10] = GCD_Glue; parray[11] = NULL; pboxes[0].gd.flags = gg_enabled|gg_visible; pboxes[0].gd.u.boxelements = parray; pboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&palabel,0,sizeof(palabel)); memset(&pagcd,0,sizeof(pagcd)); memset(&paboxes,0,sizeof(paboxes)); palabel[0].text = (unichar_t *) _("O_pen Paths"); palabel[0].text_is_1byte = true; palabel[0].text_in_resource = true; pagcd[0].gd.label = &palabel[0]; pagcd[0].gd.mnemonic = 'P'; pagcd[0].gd.pos.x = 3; pagcd[0].gd.pos.y = 6; pagcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( openpaths ) pagcd[0].gd.flags |= gg_cb_on; pagcd[0].gd.popup_msg = (unichar_t *) _("All paths should be closed loops, there should be no exposed endpoints"); pagcd[0].gd.cid = CID_OpenPaths; pagcd[0].creator = GCheckBoxCreate; paarray[0] = &pagcd[0]; palabel[1].text = (unichar_t *) _("Intersecting Paths"); palabel[1].text_is_1byte = true; pagcd[1].gd.label = &palabel[1]; pagcd[1].gd.mnemonic = 'E'; pagcd[1].gd.pos.x = 3; pagcd[1].gd.pos.y = pagcd[0].gd.pos.y+17; pagcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( intersectingpaths ) pagcd[1].gd.flags |= gg_cb_on; pagcd[1].gd.popup_msg = (unichar_t *) _("No paths with within a glyph should intersect"); pagcd[1].gd.cid = CID_IntersectingPaths; pagcd[1].creator = GCheckBoxCreate; paarray[1] = &pagcd[1]; palabel[2].text = (unichar_t *) (fv->b.sf->italicangle==0?_("_Edges near horizontal/vertical"):_("Edges near horizontal/vertical/italic")); palabel[2].text_is_1byte = true; palabel[2].text_in_resource = true; pagcd[2].gd.label = &palabel[2]; pagcd[2].gd.mnemonic = 'E'; pagcd[2].gd.pos.x = 3; pagcd[2].gd.pos.y = pagcd[1].gd.pos.y+17; pagcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( linestd ) pagcd[2].gd.flags |= gg_cb_on; pagcd[2].gd.popup_msg = (unichar_t *) _("Allows you to find lines which are almost,\nbut not quite horizontal or vertical\n(or at the italic angle)."); pagcd[2].gd.cid = CID_LineStd; pagcd[2].creator = GCheckBoxCreate; paarray[2] = &pagcd[2]; palabel[3].text = (unichar_t *) _("Check _outermost paths clockwise"); palabel[3].text_is_1byte = true; palabel[3].text_in_resource = true; pagcd[3].gd.label = &palabel[3]; pagcd[3].gd.mnemonic = 'S'; pagcd[3].gd.pos.x = 3; pagcd[3].gd.pos.y = pagcd[2].gd.pos.y+17; pagcd[3].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( direction ) pagcd[3].gd.flags |= gg_cb_on; pagcd[3].gd.popup_msg = (unichar_t *) _("PostScript and TrueType require that paths be drawn\nin a clockwise direction. This lets you check that they\nare.\n Before doing this test insure that\nno paths self-intersect"); pagcd[3].gd.cid = CID_Direction; pagcd[3].creator = GCheckBoxCreate; paarray[3] = &pagcd[3]; palabel[4].text = (unichar_t *) _("Check _missing extrema"); palabel[4].text_is_1byte = true; palabel[4].text_in_resource = true; pagcd[4].gd.label = &palabel[4]; pagcd[4].gd.pos.x = 3; pagcd[4].gd.pos.y = pagcd[3].gd.pos.y+17; pagcd[4].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( missingextrema ) pagcd[4].gd.flags |= gg_cb_on; pagcd[4].gd.popup_msg = (unichar_t *) _("PostScript and TrueType require that when a path\nreaches its maximum or minimum position\nthere must be a point at that location."); pagcd[4].gd.cid = CID_MissingExtrema; pagcd[4].creator = GCheckBoxCreate; paarray[4] = &pagcd[4]; palabel[5].text = (unichar_t *) _("_More points than:"); palabel[5].text_is_1byte = true; palabel[5].text_in_resource = true; pagcd[5].gd.label = &palabel[5]; pagcd[5].gd.mnemonic = 'r'; pagcd[5].gd.pos.x = 3; pagcd[5].gd.pos.y = pagcd[4].gd.pos.y+21; pagcd[5].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( toomanypoints ) pagcd[5].gd.flags |= gg_cb_on; pagcd[5].gd.popup_msg = (unichar_t *) _("The PostScript Language Reference Manual (Appendix B) says that\nan interpreter need not support paths with more than 1500 points.\nI think this count includes control points. From PostScript's point\nof view, all the contours in a character make up one path. Modern\ninterpreters tend to support paths with more points than this limit.\n(Note a truetype font after conversion to PS will contain\ntwice as many control points)"); pagcd[5].gd.cid = CID_TooManyPoints; pagcd[5].creator = GCheckBoxCreate; paharray[0] = &pagcd[5]; sprintf( pmax, "%d", pointsmax ); palabel[6].text = (unichar_t *) pmax; palabel[6].text_is_1byte = true; pagcd[6].gd.label = &palabel[6]; pagcd[6].gd.pos.x = 105; pagcd[6].gd.pos.y = pagcd[5].gd.pos.y-3; pagcd[6].gd.pos.width = 50; pagcd[6].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; pagcd[6].gd.popup_msg = (unichar_t *) _("The PostScript Language Reference Manual (Appendix B) says that\nan interpreter need not support paths with more than 1500 points.\nI think this count includes control points. From PostScript's point\nof view, all the contours in a character make up one path. Modern\ninterpreters tend to support paths with more points than this limit.\n(Note a truetype font after conversion to PS will contain\ntwice as many control points)"); pagcd[6].gd.cid = CID_PointsMax; pagcd[6].creator = GTextFieldCreate; paharray[1] = &pagcd[6]; paharray[2] = GCD_Glue; paharray[3] = NULL; paboxes[2].gd.flags = gg_enabled|gg_visible; paboxes[2].gd.u.boxelements = paharray; paboxes[2].creator = GHBoxCreate; paarray[5] = &paboxes[2]; paarray[6] = GCD_Glue; paarray[7] = NULL; paboxes[0].gd.flags = gg_enabled|gg_visible; paboxes[0].gd.u.boxelements = paarray; paboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&rflabel,0,sizeof(rflabel)); memset(&rfgcd,0,sizeof(rfgcd)); memset(&rfboxes,0,sizeof(rfboxes)); rflabel[0].text = (unichar_t *) _("Check _flipped references"); rflabel[0].text_is_1byte = true; rflabel[0].text_in_resource = true; rfgcd[0].gd.label = &rflabel[0]; rfgcd[0].gd.mnemonic = 'r'; rfgcd[0].gd.pos.x = 3; rfgcd[0].gd.pos.y = 6; rfgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( flippedrefs ) rfgcd[0].gd.flags |= gg_cb_on; rfgcd[0].gd.popup_msg = (unichar_t *) _("PostScript and TrueType require that paths be drawn\nin a clockwise direction. If you have a reference\nthat has been flipped then the paths in that reference will\nprobably be counter-clockwise. You should unlink it and do\nElement->Correct direction on it."); rfgcd[0].gd.cid = CID_FlippedRefs; rfgcd[0].creator = GCheckBoxCreate; rfarray[0] = &rfgcd[0]; /* GT: Refs is an abbreviation for References. Space is somewhat constrained here */ rflabel[1].text = (unichar_t *) _("Refs with bad tt transformation matrices"); rflabel[1].text_is_1byte = true; rflabel[1].text_in_resource = true; rfgcd[1].gd.label = &rflabel[1]; rfgcd[1].gd.mnemonic = 'r'; rfgcd[1].gd.pos.x = 3; rfgcd[1].gd.pos.y = rfgcd[0].gd.pos.y+17; rfgcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( refsbadtransformttf ) rfgcd[1].gd.flags |= gg_cb_on; rfgcd[1].gd.popup_msg = (unichar_t *) _("TrueType requires that all scaling and rotational\nentries in a transformation matrix be between -2 and 2"); rfgcd[1].gd.cid = CID_RefBadTransformTTF; rfgcd[1].creator = GCheckBoxCreate; rfarray[1] = &rfgcd[1]; rflabel[2].text = (unichar_t *) _("Mixed contours and references"); rflabel[2].text_is_1byte = true; rflabel[2].text_in_resource = true; rfgcd[2].gd.label = &rflabel[2]; rfgcd[2].gd.mnemonic = 'r'; rfgcd[2].gd.pos.x = 3; rfgcd[2].gd.pos.y = rfgcd[1].gd.pos.y+17; rfgcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( mixedcontoursrefs ) rfgcd[2].gd.flags |= gg_cb_on; rfgcd[2].gd.popup_msg = (unichar_t *) _("TrueType glyphs can either contain references or contours.\nNot both."); rfgcd[2].gd.cid = CID_MixedContoursRefs; rfgcd[2].creator = GCheckBoxCreate; rfarray[2] = &rfgcd[2]; /* GT: Refs is an abbreviation for References. Space is somewhat constrained here */ rflabel[3].text = (unichar_t *) _("Refs with bad ps transformation matrices"); rflabel[3].text_is_1byte = true; rflabel[3].text_in_resource = true; rfgcd[3].gd.label = &rflabel[3]; rfgcd[3].gd.mnemonic = 'r'; rfgcd[3].gd.pos.x = 3; rfgcd[3].gd.pos.y = rfgcd[2].gd.pos.y+17; rfgcd[3].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( refsbadtransformps ) rfgcd[3].gd.flags |= gg_cb_on; rfgcd[3].gd.popup_msg = (unichar_t *) _("Type1 and 2 fonts only support translation of references.\nThe first four entries of the transformation matrix should be\n[1 0 0 1]."); rfgcd[3].gd.cid = CID_RefBadTransformPS; rfgcd[3].creator = GCheckBoxCreate; rfarray[3] = &rfgcd[3]; /* GT: Refs is an abbreviation for References. Space is somewhat constrained here */ rflabel[4].text = (unichar_t *) _("Refs neste_d deeper than:"); rflabel[4].text_is_1byte = true; rflabel[4].text_in_resource = true; rfgcd[4].gd.label = &rflabel[4]; rfgcd[4].gd.mnemonic = 'r'; rfgcd[4].gd.pos.x = 3; rfgcd[4].gd.pos.y = rfgcd[3].gd.pos.y+21; rfgcd[4].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( toodeeprefs ) rfgcd[4].gd.flags |= gg_cb_on; rfgcd[4].gd.popup_msg = (unichar_t *) _("The Type 2 Charstring Reference (Appendix B) says that\nsubroutines may not be nested more than 10 deep. Each\nnesting level for references requires one subroutine\nlevel, and hints may require another level."); rfgcd[4].gd.cid = CID_TooDeepRefs; rfgcd[4].creator = GCheckBoxCreate; rfharray[0] = &rfgcd[4]; sprintf( rmax, "%d", refdepthmax ); rflabel[5].text = (unichar_t *) rmax; rflabel[5].text_is_1byte = true; rfgcd[5].gd.label = &rflabel[5]; rfgcd[5].gd.pos.x = 140; rfgcd[5].gd.pos.y = rfgcd[4].gd.pos.y-3; rfgcd[5].gd.pos.width = 40; rfgcd[5].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; rfgcd[5].gd.popup_msg = (unichar_t *) _("The Type 2 Charstring Reference (Appendix B) says that\nsubroutines may not be nested more than 10 deep. Each\nnesting level for references requires one subroutine\nlevel, and hints may require another level."); rfgcd[5].gd.cid = CID_RefDepthMax; rfgcd[5].creator = GTextFieldCreate; rfharray[1] = &rfgcd[5]; rfharray[2] = GCD_Glue; rfharray[3] = NULL; rfboxes[2].gd.flags = gg_enabled|gg_visible; rfboxes[2].gd.u.boxelements = rfharray; rfboxes[2].creator = GHBoxCreate; rfarray[4] = &rfboxes[2]; rflabel[6].text = (unichar_t *) _("Refs with out of date point matching"); rflabel[6].text_is_1byte = true; rflabel[6].text_in_resource = true; rfgcd[6].gd.label = &rflabel[6]; rfgcd[6].gd.mnemonic = 'r'; rfgcd[6].gd.pos.x = 3; rfgcd[6].gd.pos.y = rfgcd[5].gd.pos.y+24; rfgcd[6].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( ptmatchrefsoutofdate ) rfgcd[6].gd.flags |= gg_cb_on; rfgcd[6].gd.popup_msg = (unichar_t *) _("If a glyph has been edited so that it has a different\nnumber of points now, then any references\nwhich use point matching and depended on that glyph's\npoint count will be incorrect."); rfgcd[6].gd.cid = CID_PtMatchRefsOutOfDate; rfgcd[6].creator = GCheckBoxCreate; rfarray[5] = &rfgcd[6]; rflabel[7].text = (unichar_t *) _("Multiple refs with use-my-metrics"); rflabel[7].text_is_1byte = true; rflabel[7].text_in_resource = true; rfgcd[7].gd.label = &rflabel[7]; rfgcd[7].gd.mnemonic = 'r'; rfgcd[7].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( multusemymetrics ) rfgcd[7].gd.flags |= gg_cb_on; rfgcd[7].gd.popup_msg = (unichar_t *) _("There may be at most one reference with the use-my-metrics bit set"); rfgcd[7].gd.cid = CID_MultUseMyMetrics; rfgcd[7].creator = GCheckBoxCreate; rfarray[6] = &rfgcd[7]; rfarray[7] = GCD_Glue; rfarray[8] = NULL; rfboxes[0].gd.flags = gg_enabled|gg_visible; rfboxes[0].gd.u.boxelements = rfarray; rfboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&hlabel,0,sizeof(hlabel)); memset(&hgcd,0,sizeof(hgcd)); memset(&hboxes,0,sizeof(hboxes)); hlabel[0].text = (unichar_t *) _("_Hints controlling no points"); hlabel[0].text_is_1byte = true; hlabel[0].text_in_resource = true; hgcd[0].gd.label = &hlabel[0]; hgcd[0].gd.mnemonic = 'H'; hgcd[0].gd.pos.x = 3; hgcd[0].gd.pos.y = 5; hgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( hintnopt ) hgcd[0].gd.flags |= gg_cb_on; hgcd[0].gd.popup_msg = (unichar_t *) _("Ghostview (perhaps other interpreters) has a problem when a\nhint exists without any points that lie on it."); hgcd[0].gd.cid = CID_HintNoPt; hgcd[0].creator = GCheckBoxCreate; harray[0] = &hgcd[0]; hlabel[1].text = (unichar_t *) U_("_Points near¹ hint edges"); hlabel[1].text_is_1byte = true; hlabel[1].text_in_resource = true; hgcd[1].gd.label = &hlabel[1]; hgcd[1].gd.mnemonic = 'H'; hgcd[1].gd.pos.x = 3; hgcd[1].gd.pos.y = hgcd[0].gd.pos.y+17; hgcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( ptnearhint ) hgcd[1].gd.flags |= gg_cb_on; hgcd[1].gd.popup_msg = (unichar_t *) _("Often if a point is slightly off from a hint\nit is because a stem is made up\nof several segments, and one of them\nhas the wrong width."); hgcd[1].gd.cid = CID_PtNearHint; hgcd[1].creator = GCheckBoxCreate; harray[1] = &hgcd[1]; hlabel[2].text = (unichar_t *) U_("Hint _Width Near¹"); hlabel[2].text_is_1byte = true; hlabel[2].text_in_resource = true; hgcd[2].gd.label = &hlabel[2]; hgcd[2].gd.mnemonic = 'W'; hgcd[2].gd.pos.x = 3; hgcd[2].gd.pos.y = hgcd[1].gd.pos.y+21; hgcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( hintwidth ) hgcd[2].gd.flags |= gg_cb_on; hgcd[2].gd.popup_msg = (unichar_t *) _("Allows you to check that stems have consistent widths.."); hgcd[2].gd.cid = CID_HintWidthNear; hgcd[2].creator = GCheckBoxCreate; hharray1[0] = &hgcd[2]; sprintf(widthbuf,"%g",widthval); hlabel[3].text = (unichar_t *) widthbuf; hlabel[3].text_is_1byte = true; hgcd[3].gd.label = &hlabel[3]; hgcd[3].gd.pos.x = 100+5; hgcd[3].gd.pos.y = hgcd[2].gd.pos.y-1; hgcd[3].gd.pos.width = 40; hgcd[3].gd.flags = gg_visible | gg_enabled; hgcd[3].gd.cid = CID_HintWidth; hgcd[3].gd.handle_controlevent = Prob_TextChanged; hgcd[3].data = (void *) CID_HintWidthNear; hgcd[3].creator = GTextFieldCreate; hharray1[1] = &hgcd[3]; hharray1[2] = GCD_Glue; hharray1[3] = NULL; hboxes[2].gd.flags = gg_enabled|gg_visible; hboxes[2].gd.u.boxelements = hharray1; hboxes[2].creator = GHBoxCreate; harray[2] = &hboxes[2]; /* GT: The _3 is used to mark an accelerator */ hlabel[4].text = (unichar_t *) _("Almost stem_3 hint"); hlabel[4].text_is_1byte = true; hlabel[4].text_in_resource = true; hgcd[4].gd.label = &hlabel[4]; hgcd[4].gd.mnemonic = '3'; hgcd[4].gd.pos.x = 3; hgcd[4].gd.pos.y = hgcd[3].gd.pos.y+19; hgcd[4].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( stem3 ) hgcd[4].gd.flags |= gg_cb_on; hgcd[4].gd.popup_msg = (unichar_t *) _("This checks if the character almost, but not exactly,\nconforms to the requirements for a stem3 hint.\nThat is, either vertically or horizontally, there must\nbe exactly three hints, and they must have the same\nwidth and they must be evenly spaced."); hgcd[4].gd.cid = CID_Stem3; hgcd[4].gd.handle_controlevent = Prob_EnableExact; hgcd[4].creator = GCheckBoxCreate; harray[3] = &hgcd[4]; hlabel[5].text = (unichar_t *) _("_Show Exact *stem3"); hlabel[5].text_is_1byte = true; hlabel[5].text_in_resource = true; hgcd[5].gd.label = &hlabel[5]; hgcd[5].gd.mnemonic = 'S'; hgcd[5].gd.pos.x = hgcd[4].gd.pos.x+5; hgcd[5].gd.pos.y = hgcd[4].gd.pos.y+17; hgcd[5].gd.flags = gg_visible | gg_utf8_popup; if ( showexactstem3 ) hgcd[5].gd.flags |= gg_cb_on; if ( stem3 ) hgcd[5].gd.flags |= gg_enabled; hgcd[5].gd.popup_msg = (unichar_t *) _("Shows when this character is exactly a stem3 hint"); hgcd[5].gd.cid = CID_ShowExactStem3; hgcd[5].creator = GCheckBoxCreate; hharray2[0] = GCD_HPad10; hharray2[1] = &hgcd[5]; hharray2[2] = GCD_Glue; hharray2[3] = NULL; hboxes[3].gd.flags = gg_enabled|gg_visible; hboxes[3].gd.u.boxelements = hharray2; hboxes[3].creator = GHBoxCreate; harray[4] = &hboxes[3]; hlabel[6].text = (unichar_t *) _("_More hints than:"); hlabel[6].text_is_1byte = true; hlabel[6].text_in_resource = true; hgcd[6].gd.label = &hlabel[6]; hgcd[6].gd.pos.x = 3; hgcd[6].gd.pos.y = hgcd[5].gd.pos.y+21; hgcd[6].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( toomanyhints ) hgcd[6].gd.flags |= gg_cb_on; hgcd[6].gd.popup_msg = (unichar_t *) _("The Type 2 Charstring Reference (Appendix B) says that\nthere may be at most 96 horizontal and vertical stem hints\nin a character."); hgcd[6].gd.cid = CID_TooManyHints; hgcd[6].creator = GCheckBoxCreate; hharray3[0] = &hgcd[6]; sprintf( hmax, "%d", hintsmax ); hlabel[7].text = (unichar_t *) hmax; hlabel[7].text_is_1byte = true; hgcd[7].gd.label = &hlabel[7]; hgcd[7].gd.pos.x = 105; hgcd[7].gd.pos.y = hgcd[6].gd.pos.y-3; hgcd[7].gd.pos.width = 50; hgcd[7].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; hgcd[7].gd.popup_msg = (unichar_t *) _("The Type 2 Charstring Reference (Appendix B) says that\nthere may be at most 96 horizontal and vertical stem hints\nin a character."); hgcd[7].gd.cid = CID_HintsMax; hgcd[7].creator = GTextFieldCreate; hharray3[1] = &hgcd[7]; hharray3[2] = GCD_Glue; hharray3[3] = NULL; hboxes[4].gd.flags = gg_enabled|gg_visible; hboxes[4].gd.u.boxelements = hharray3; hboxes[4].creator = GHBoxCreate; harray[5] = &hboxes[4]; hlabel[8].text = (unichar_t *) _("_Overlapped hints"); hlabel[8].text_is_1byte = true; hlabel[8].text_in_resource = true; hgcd[8].gd.label = &hlabel[8]; hgcd[8].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( overlappedhints ) hgcd[8].gd.flags |= gg_cb_on; hgcd[8].gd.popup_msg = (unichar_t *) _("Either a glyph should have no overlapping hints,\nor a glyph with hint masks should have no overlapping\nhints within a hint mask."); hgcd[8].gd.cid = CID_OverlappedHints; hgcd[8].creator = GCheckBoxCreate; harray[6] = &hgcd[8]; harray[7] = GCD_Glue; harray[8] = NULL; hboxes[0].gd.flags = gg_enabled|gg_visible; hboxes[0].gd.u.boxelements = harray; hboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&rlabel,0,sizeof(rlabel)); memset(&rgcd,0,sizeof(rgcd)); memset(&rboxes,0,sizeof(rboxes)); rlabel[0].text = (unichar_t *) _("Check missing _bitmaps"); rlabel[0].text_is_1byte = true; rlabel[0].text_in_resource = true; rgcd[0].gd.label = &rlabel[0]; rgcd[0].gd.mnemonic = 'r'; rgcd[0].gd.pos.x = 3; rgcd[0].gd.pos.y = 6; rgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bitmaps ) rgcd[0].gd.flags |= gg_cb_on; rgcd[0].gd.popup_msg = (unichar_t *) _("Are there any outline characters which don't have a bitmap version in one of the bitmap fonts?\nConversely are there any bitmap characters without a corresponding outline character?"); rgcd[0].gd.cid = CID_Bitmaps; rgcd[0].creator = GCheckBoxCreate; rlabel[1].text = (unichar_t *) _("Bitmap/outline _advance mismatch"); rlabel[1].text_is_1byte = true; rlabel[1].text_in_resource = true; rgcd[1].gd.label = &rlabel[1]; rgcd[1].gd.mnemonic = 'r'; rgcd[1].gd.pos.x = 3; rgcd[1].gd.pos.y = 6; rgcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bitmapwidths ) rgcd[1].gd.flags |= gg_cb_on; rgcd[1].gd.popup_msg = (unichar_t *) _("Are there any bitmap glyphs whose advance width\nis not is expected from scaling and rounding\nthe outline's advance width?"); rgcd[1].gd.cid = CID_BitmapWidths; rgcd[1].creator = GCheckBoxCreate; rlabel[2].text = (unichar_t *) _("Check multiple Unicode"); rlabel[2].text_is_1byte = true; rgcd[2].gd.label = &rlabel[2]; rgcd[2].gd.pos.x = 3; rgcd[2].gd.pos.y = rgcd[1].gd.pos.y+15; rgcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( multuni ) rgcd[2].gd.flags |= gg_cb_on; rgcd[2].gd.popup_msg = (unichar_t *) _("Check multiple Unicode"); rgcd[2].gd.cid = CID_MultUni; rgcd[2].creator = GCheckBoxCreate; rlabel[3].text = (unichar_t *) _("Check multiple Names"); rlabel[3].text_is_1byte = true; rgcd[3].gd.label = &rlabel[3]; rgcd[3].gd.pos.x = 3; rgcd[3].gd.pos.y = rgcd[2].gd.pos.y+15; rgcd[3].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( multname ) rgcd[3].gd.flags |= gg_cb_on; rgcd[3].gd.popup_msg = (unichar_t *) _("Check for multiple characters with the same name"); rgcd[3].gd.cid = CID_MultName; rgcd[3].creator = GCheckBoxCreate; rlabel[4].text = (unichar_t *) _("Check Unicode/Name mismatch"); rlabel[4].text_is_1byte = true; rgcd[4].gd.label = &rlabel[4]; rgcd[4].gd.pos.x = 3; rgcd[4].gd.pos.y = rgcd[3].gd.pos.y+15; rgcd[4].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( uninamemismatch ) rgcd[4].gd.flags |= gg_cb_on; rgcd[4].gd.popup_msg = (unichar_t *) _("Check for characters whose name maps to a unicode code point\nwhich does not map the character's assigned code point."); rgcd[4].gd.cid = CID_UniNameMisMatch; rgcd[4].creator = GCheckBoxCreate; for ( i=0; i<=4; ++i ) rarray[i] = &rgcd[i]; rarray[i++] = GCD_Glue; rarray[i++] = NULL; rboxes[0].gd.flags = gg_enabled|gg_visible; rboxes[0].gd.u.boxelements = rarray; rboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&bblabel,0,sizeof(bblabel)); memset(&bbgcd,0,sizeof(bbgcd)); memset(&bbboxes,0,sizeof(bbboxes)); bblabel[0].text = (unichar_t *) _("Glyph BB Above"); bblabel[0].text_is_1byte = true; bblabel[0].text_in_resource = true; bbgcd[0].gd.label = &bblabel[0]; bbgcd[0].gd.mnemonic = 'r'; bbgcd[0].gd.pos.x = 3; bbgcd[0].gd.pos.y = 6; bbgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bbymax ) bbgcd[0].gd.flags |= gg_cb_on; bbgcd[0].gd.popup_msg = (unichar_t *) _("Are there any glyph's whose bounding boxes extend above this number?"); bbgcd[0].gd.cid = CID_BBYMax; bbgcd[0].creator = GCheckBoxCreate; sf = p.fv->b.sf; if ( lastsf!=sf ) { bbymax_val = bbymin_val = bbxmax_val /* = bbxmin_val */= vadvancewidth = advancewidth = 0; } sprintf(yymaxbuf,"%g", bbymax_val!=0 ? bbymax_val : sf->ascent); bblabel[1].text = (unichar_t *) yymaxbuf; bblabel[1].text_is_1byte = true; bbgcd[1].gd.label = &bblabel[1]; bbgcd[1].gd.pos.x = 100+15; bbgcd[1].gd.pos.y = bbgcd[0].gd.pos.y-1; bbgcd[1].gd.pos.width = 40; bbgcd[1].gd.flags = gg_visible | gg_enabled; bbgcd[1].gd.cid = CID_BBYMaxVal; bbgcd[1].gd.handle_controlevent = Prob_TextChanged; bbgcd[1].data = (void *) CID_BBYMax; bbgcd[1].creator = GTextFieldCreate; bbarray[0][0] = &bbgcd[0]; bbarray[0][1] = &bbgcd[1]; bbarray[0][2] = GCD_Glue; bbarray[0][3] = NULL; bblabel[2].text = (unichar_t *) _("Glyph BB Below"); bblabel[2].text_is_1byte = true; bblabel[2].text_in_resource = true; bbgcd[2].gd.label = &bblabel[2]; bbgcd[2].gd.mnemonic = 'r'; bbgcd[2].gd.pos.x = 3; bbgcd[2].gd.pos.y = bbgcd[0].gd.pos.y+21; bbgcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bbymin ) bbgcd[2].gd.flags |= gg_cb_on; bbgcd[2].gd.popup_msg = (unichar_t *) _("Are there any glyph's whose bounding boxes extend below this number?"); bbgcd[2].gd.cid = CID_BBYMin; bbgcd[2].creator = GCheckBoxCreate; sprintf(yyminbuf,"%g", bbymin_val!=0 ? bbymin_val : -sf->descent); bblabel[3].text = (unichar_t *) yyminbuf; bblabel[3].text_is_1byte = true; bbgcd[3].gd.label = &bblabel[3]; bbgcd[3].gd.pos.x = 100+15; bbgcd[3].gd.pos.y = bbgcd[2].gd.pos.y-1; bbgcd[3].gd.pos.width = 40; bbgcd[3].gd.flags = gg_visible | gg_enabled; bbgcd[3].gd.cid = CID_BBYMinVal; bbgcd[3].gd.handle_controlevent = Prob_TextChanged; bbgcd[3].data = (void *) CID_BBYMin; bbgcd[3].creator = GTextFieldCreate; bbarray[1][0] = &bbgcd[2]; bbarray[1][1] = &bbgcd[3]; bbarray[1][2] = GCD_Glue; bbarray[1][3] = NULL; bblabel[4].text = (unichar_t *) _("Glyph BB Right Of"); bblabel[4].text_is_1byte = true; bblabel[4].text_in_resource = true; bbgcd[4].gd.label = &bblabel[4]; bbgcd[4].gd.pos.x = 3; bbgcd[4].gd.pos.y = bbgcd[2].gd.pos.y+21; bbgcd[4].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bbxmax ) bbgcd[4].gd.flags |= gg_cb_on; bbgcd[4].gd.popup_msg = (unichar_t *) _("Are there any glyphs whose bounding boxes extend to the right of this number?"); bbgcd[4].gd.cid = CID_BBXMax; bbgcd[4].creator = GCheckBoxCreate; sprintf(xxmaxbuf,"%g", bbxmax_val!=0 ? bbxmax_val : (double) (sf->ascent+sf->descent)); bblabel[5].text = (unichar_t *) xxmaxbuf; bblabel[5].text_is_1byte = true; bbgcd[5].gd.label = &bblabel[5]; bbgcd[5].gd.pos.x = 100+15; bbgcd[5].gd.pos.y = bbgcd[4].gd.pos.y-1; bbgcd[5].gd.pos.width = 40; bbgcd[5].gd.flags = gg_visible | gg_enabled; bbgcd[5].gd.cid = CID_BBXMaxVal; bbgcd[5].gd.handle_controlevent = Prob_TextChanged; bbgcd[5].data = (void *) CID_BBXMax; bbgcd[5].creator = GTextFieldCreate; bbarray[2][0] = &bbgcd[4]; bbarray[2][1] = &bbgcd[5]; bbarray[2][2] = GCD_Glue; bbarray[2][3] = NULL; bblabel[6].text = (unichar_t *) _("Glyph BB Left Of"); bblabel[6].text_is_1byte = true; bblabel[6].text_in_resource = true; bbgcd[6].gd.label = &bblabel[6]; bbgcd[6].gd.pos.x = 3; bbgcd[6].gd.pos.y = bbgcd[4].gd.pos.y+21; bbgcd[6].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( bbxmin ) bbgcd[6].gd.flags |= gg_cb_on; bbgcd[6].gd.popup_msg = (unichar_t *) _("Are there any glyph's whose bounding boxes extend to the left of this number?"); bbgcd[6].gd.cid = CID_BBXMin; bbgcd[6].creator = GCheckBoxCreate; sprintf(xxminbuf,"%g",bbxmin_val); bblabel[7].text = (unichar_t *) xxminbuf; bblabel[7].text_is_1byte = true; bbgcd[7].gd.label = &bblabel[7]; bbgcd[7].gd.pos.x = 100+15; bbgcd[7].gd.pos.y = bbgcd[6].gd.pos.y-1; bbgcd[7].gd.pos.width = 40; bbgcd[7].gd.flags = gg_visible | gg_enabled; bbgcd[7].gd.cid = CID_BBXMinVal; bbgcd[7].gd.handle_controlevent = Prob_TextChanged; bbgcd[7].data = (void *) CID_BBXMin; bbgcd[7].creator = GTextFieldCreate; bbarray[3][0] = &bbgcd[6]; bbarray[3][1] = &bbgcd[7]; bbarray[3][2] = GCD_Glue; bbarray[3][3] = NULL; bblabel[8].text = (unichar_t *) _("Check Advance:"); bblabel[8].text_is_1byte = true; bblabel[8].text_in_resource = true; bbgcd[8].gd.label = &bblabel[8]; bbgcd[8].gd.mnemonic = 'W'; bbgcd[8].gd.pos.x = 3; bbgcd[8].gd.pos.y = bbgcd[6].gd.pos.y+21; bbgcd[8].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( advancewidth ) bbgcd[8].gd.flags |= gg_cb_on; bbgcd[8].gd.popup_msg = (unichar_t *) _("Check for characters whose advance width is not the displayed value."); bbgcd[8].gd.cid = CID_AdvanceWidth; bbgcd[8].creator = GCheckBoxCreate; if ( ( ssc = SFGetChar(sf,' ',NULL))!=NULL ) advancewidthval = ssc->width; sprintf(awidthbuf,"%g",advancewidthval); bblabel[9].text = (unichar_t *) awidthbuf; bblabel[9].text_is_1byte = true; bbgcd[9].gd.label = &bblabel[9]; bbgcd[9].gd.pos.x = 100+15; bbgcd[9].gd.pos.y = bbgcd[8].gd.pos.y-1; bbgcd[9].gd.pos.width = 40; bbgcd[9].gd.flags = gg_visible | gg_enabled; bbgcd[9].gd.cid = CID_AdvanceWidthVal; bbgcd[9].gd.handle_controlevent = Prob_TextChanged; bbgcd[9].data = (void *) CID_AdvanceWidth; bbgcd[9].creator = GTextFieldCreate; bbarray[4][0] = &bbgcd[8]; bbarray[4][1] = &bbgcd[9]; bbarray[4][2] = GCD_Glue; bbarray[4][3] = NULL; bblabel[10].text = (unichar_t *) _("Check VAdvance:\n"); bblabel[10].text_is_1byte = true; bbgcd[10].gd.label = &bblabel[10]; bbgcd[10].gd.mnemonic = 'W'; bbgcd[10].gd.pos.x = 3; bbgcd[10].gd.pos.y = bbgcd[9].gd.pos.y+24; bbgcd[10].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( !sf->hasvmetrics ) bbgcd[10].gd.flags = gg_visible; else if ( vadvancewidth ) bbgcd[10].gd.flags |= gg_cb_on; bbgcd[10].gd.popup_msg = (unichar_t *) _("Check for characters whose vertical advance width is not the displayed value."); bbgcd[10].gd.cid = CID_VAdvanceWidth; bbgcd[10].creator = GCheckBoxCreate; if ( vadvancewidth==0 ) vadvancewidth = sf->ascent+sf->descent; sprintf(vawidthbuf,"%g",vadvancewidthval); bblabel[11].text = (unichar_t *) vawidthbuf; bblabel[11].text_is_1byte = true; bbgcd[11].gd.label = &bblabel[11]; bbgcd[11].gd.pos.x = 100+15; bbgcd[11].gd.pos.y = bbgcd[10].gd.pos.y-1; bbgcd[11].gd.pos.width = 40; bbgcd[11].gd.flags = gg_visible | gg_enabled; if ( !sf->hasvmetrics ) bbgcd[11].gd.flags = gg_visible; bbgcd[11].gd.cid = CID_VAdvanceWidthVal; bbgcd[11].gd.handle_controlevent = Prob_TextChanged; bbgcd[11].data = (void *) CID_VAdvanceWidth; bbgcd[11].creator = GTextFieldCreate; bbarray[5][0] = &bbgcd[10]; bbarray[5][1] = &bbgcd[11]; bbarray[5][2] = GCD_Glue; bbarray[5][3] = NULL; bbarray[6][0] = GCD_Glue; bbarray[6][1] = GCD_Glue; bbarray[6][2] = GCD_Glue; bbarray[6][3] = NULL; bbarray[7][0] = NULL; bbboxes[0].gd.flags = gg_enabled|gg_visible; bbboxes[0].gd.u.boxelements = bbarray[0]; bbboxes[0].creator = GHVBoxCreate; /* ************************************************************************** */ memset(&clabel,0,sizeof(clabel)); memset(&cgcd,0,sizeof(cgcd)); memset(&cboxes,0,sizeof(cboxes)); clabel[0].text = (unichar_t *) _("Check for CIDs defined _twice"); clabel[0].text_is_1byte = true; clabel[0].text_in_resource = true; cgcd[0].gd.label = &clabel[0]; cgcd[0].gd.mnemonic = 'S'; cgcd[0].gd.pos.x = 3; cgcd[0].gd.pos.y = 6; cgcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( cidmultiple ) cgcd[0].gd.flags |= gg_cb_on; cgcd[0].gd.popup_msg = (unichar_t *) _("Check whether a CID is defined in more than one sub-font"); cgcd[0].gd.cid = CID_CIDMultiple; cgcd[0].creator = GCheckBoxCreate; carray[0] = &cgcd[0]; clabel[1].text = (unichar_t *) _("Check for _undefined CIDs"); clabel[1].text_is_1byte = true; clabel[1].text_in_resource = true; cgcd[1].gd.label = &clabel[1]; cgcd[1].gd.mnemonic = 'S'; cgcd[1].gd.pos.x = 3; cgcd[1].gd.pos.y = cgcd[0].gd.pos.y+17; cgcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( cidblank ) cgcd[1].gd.flags |= gg_cb_on; cgcd[1].gd.popup_msg = (unichar_t *) _("Check whether a CID is undefined in all sub-fonts"); cgcd[1].gd.cid = CID_CIDBlank; cgcd[1].creator = GCheckBoxCreate; carray[1] = &cgcd[1]; carray[2] = GCD_Glue; carray[3] = NULL; cboxes[0].gd.flags = gg_enabled|gg_visible; cboxes[0].gd.u.boxelements = carray; cboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&alabel,0,sizeof(alabel)); memset(&agcd,0,sizeof(agcd)); memset(&aboxes,0,sizeof(aboxes)); alabel[0].text = (unichar_t *) _("Check for missing _glyph names"); alabel[0].text_is_1byte = true; alabel[0].text_in_resource = true; agcd[0].gd.label = &alabel[0]; agcd[0].gd.pos.x = 3; agcd[0].gd.pos.y = 6; agcd[0].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( missingglyph ) agcd[0].gd.flags |= gg_cb_on; agcd[0].gd.popup_msg = (unichar_t *) _("Check whether a substitution, kerning class, etc. uses a glyph name which does not match any glyph in the font"); agcd[0].gd.cid = CID_MissingGlyph; agcd[0].creator = GCheckBoxCreate; aarray[0] = &agcd[0]; alabel[1].text = (unichar_t *) _("Check for missing _scripts in features"); alabel[1].text_is_1byte = true; alabel[1].text_in_resource = true; agcd[1].gd.label = &alabel[1]; agcd[1].gd.pos.x = 3; agcd[1].gd.pos.y = agcd[0].gd.pos.y+14; agcd[1].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( missingscriptinfeature ) agcd[1].gd.flags |= gg_cb_on; agcd[1].gd.popup_msg = (unichar_t *) _( "In every lookup that uses a glyph, check that at\n" "least one feature is active for the glyph's script."); agcd[1].gd.cid = CID_MissingScriptInFeature; agcd[1].creator = GCheckBoxCreate; aarray[1] = &agcd[1]; alabel[2].text = (unichar_t *) _("Check substitutions for empty chars"); alabel[2].text_is_1byte = true; agcd[2].gd.label = &alabel[2]; agcd[2].gd.pos.x = 3; agcd[2].gd.pos.y = agcd[1].gd.pos.y+15; agcd[2].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( badsubs ) agcd[2].gd.flags |= gg_cb_on; agcd[2].gd.popup_msg = (unichar_t *) _("Check for characters which contain 'GSUB' entries which refer to empty characters"); agcd[2].gd.cid = CID_BadSubs; agcd[2].creator = GCheckBoxCreate; aarray[2] = &agcd[2]; alabel[3].text = (unichar_t *) _("Check for incomplete mark to base subtables"); alabel[3].text_is_1byte = true; agcd[3].gd.label = &alabel[3]; agcd[3].gd.pos.x = 3; agcd[3].gd.pos.y = agcd[1].gd.pos.y+15; agcd[3].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; if ( missinganchor ) agcd[3].gd.flags |= gg_cb_on; agcd[3].gd.popup_msg = (unichar_t *) _( "The OpenType documentation suggests in a rather confusing way\n" "that if a base glyph (or base mark) contains an anchor point\n" "for one class in a lookup subtable, then it should contain\n" "anchors for all classes in the subtable" ); agcd[3].gd.cid = CID_MissingAnchor; agcd[3].creator = GCheckBoxCreate; aarray[3] = &agcd[3]; aarray[4] = GCD_Glue; aarray[5] = NULL; aboxes[0].gd.flags = gg_enabled|gg_visible; aboxes[0].gd.u.boxelements = aarray; aboxes[0].creator = GVBoxCreate; /* ************************************************************************** */ memset(&mlabel,0,sizeof(mlabel)); memset(&mgcd,0,sizeof(mgcd)); memset(&mboxes,0,sizeof(mboxes)); memset(aspects,0,sizeof(aspects)); i = 0; aspects[i].text = (unichar_t *) _("Points"); aspects[i].selected = true; aspects[i].text_is_1byte = true; aspects[i++].gcd = pboxes; aspects[i].text = (unichar_t *) _("Paths"); aspects[i].text_is_1byte = true; aspects[i++].gcd = paboxes; /* GT: Refs is an abbreviation for References. Space is tight here */ aspects[i].text = (unichar_t *) _("Refs"); aspects[i].text_is_1byte = true; aspects[i++].gcd = rfboxes; aspects[i].text = (unichar_t *) _("Hints"); aspects[i].text_is_1byte = true; aspects[i++].gcd = hboxes; aspects[i].text = (unichar_t *) _("ATT"); aspects[i].text_is_1byte = true; aspects[i++].gcd = aboxes; aspects[i].text = (unichar_t *) _("CID"); aspects[i].disabled = fv->b.cidmaster==NULL; aspects[i].text_is_1byte = true; aspects[i++].gcd = cboxes; aspects[i].text = (unichar_t *) _("BB"); aspects[i].text_is_1byte = true; aspects[i++].gcd = bbboxes; aspects[i].text = (unichar_t *) _("Random"); aspects[i].text_is_1byte = true; aspects[i++].gcd = rboxes; mgcd[0].gd.pos.x = 4; mgcd[0].gd.pos.y = 6; mgcd[0].gd.pos.width = 210; mgcd[0].gd.pos.height = 190; mgcd[0].gd.u.tabs = aspects; mgcd[0].gd.flags = gg_visible | gg_enabled; mgcd[0].creator = GTabSetCreate; marray[0][0] = &mgcd[0]; marray[0][1] = NULL; mgcd[1].gd.pos.x = 15; mgcd[1].gd.pos.y = 190+10; mgcd[1].gd.flags = gg_visible | gg_enabled | gg_dontcopybox; mlabel[1].text = (unichar_t *) _("Clear All"); mlabel[1].text_is_1byte = true; mlabel[1].text_in_resource = true; mgcd[1].gd.label = &mlabel[1]; /*mgcd[1].gd.box = &smallbox;*/ mgcd[1].gd.handle_controlevent = Prob_DoAll; mgcd[2].gd.cid = CID_ClearAll; mgcd[1].creator = GButtonCreate; mharray1[0] = &mgcd[1]; mgcd[2].gd.pos.x = mgcd[1].gd.pos.x+1.25*GIntGetResource(_NUM_Buttonsize); mgcd[2].gd.pos.y = mgcd[1].gd.pos.y; mgcd[2].gd.flags = gg_visible | gg_enabled | gg_dontcopybox; mlabel[2].text = (unichar_t *) _("Set All"); mlabel[2].text_is_1byte = true; mlabel[2].text_in_resource = true; mgcd[2].gd.label = &mlabel[2]; /*mgcd[2].gd.box = &smallbox;*/ mgcd[2].gd.handle_controlevent = Prob_DoAll; mgcd[2].gd.cid = CID_SetAll; mgcd[2].creator = GButtonCreate; mharray1[1] = &mgcd[2]; mharray1[2] = GCD_Glue; mharray1[3] = NULL; mboxes[2].gd.flags = gg_enabled|gg_visible; mboxes[2].gd.u.boxelements = mharray1; mboxes[2].creator = GHBoxCreate; marray[1][0] = &mboxes[2]; marray[1][1] = NULL; mgcd[3].gd.pos.x = 6; mgcd[3].gd.pos.y = mgcd[1].gd.pos.y+27; mgcd[3].gd.pos.width = 218-12; mgcd[3].gd.flags = gg_visible | gg_enabled; mgcd[3].creator = GLineCreate; marray[2][0] = &mgcd[3]; marray[2][1] = NULL; mlabel[4].text = (unichar_t *) U_("¹ \"Near\" means within"); mlabel[4].text_is_1byte = true; mgcd[4].gd.label = &mlabel[4]; mgcd[4].gd.mnemonic = 'N'; mgcd[4].gd.pos.x = 6; mgcd[4].gd.pos.y = mgcd[3].gd.pos.y+6+6; mgcd[4].gd.flags = gg_visible | gg_enabled; mgcd[4].creator = GLabelCreate; mharray2[0] = &mgcd[4]; sprintf(nearbuf,"%g",near); mlabel[5].text = (unichar_t *) nearbuf; mlabel[5].text_is_1byte = true; mgcd[5].gd.label = &mlabel[5]; mgcd[5].gd.pos.x = 130; mgcd[5].gd.pos.y = mgcd[4].gd.pos.y-6; mgcd[5].gd.pos.width = 40; mgcd[5].gd.flags = gg_visible | gg_enabled; mgcd[5].gd.cid = CID_Near; mgcd[5].creator = GTextFieldCreate; mharray2[1] = &mgcd[5]; mlabel[6].text = (unichar_t *) _("em-units"); mlabel[6].text_is_1byte = true; mgcd[6].gd.label = &mlabel[6]; mgcd[6].gd.pos.x = mgcd[5].gd.pos.x+mgcd[5].gd.pos.width+4; mgcd[6].gd.pos.y = mgcd[4].gd.pos.y; mgcd[6].gd.flags = gg_visible | gg_enabled; mgcd[6].creator = GLabelCreate; mharray2[2] = &mgcd[6]; mharray2[3] = GCD_Glue; mharray2[4] = NULL; mboxes[3].gd.flags = gg_enabled|gg_visible; mboxes[3].gd.u.boxelements = mharray2; mboxes[3].creator = GHBoxCreate; marray[3][0] = &mboxes[3]; marray[3][1] = NULL; mgcd[7].gd.pos.x = 15-3; mgcd[7].gd.pos.y = mgcd[5].gd.pos.y+26; mgcd[7].gd.pos.width = -1; mgcd[7].gd.pos.height = 0; mgcd[7].gd.flags = gg_visible | gg_enabled | gg_but_default; mlabel[7].text = (unichar_t *) _("_OK"); mlabel[7].text_is_1byte = true; mlabel[7].text_in_resource = true; mgcd[7].gd.mnemonic = 'O'; mgcd[7].gd.label = &mlabel[7]; mgcd[7].gd.handle_controlevent = Prob_OK; mgcd[7].creator = GButtonCreate; barray[0] = GCD_Glue; barray[1] = &mgcd[7]; barray[2] = GCD_Glue; barray[3] = GCD_Glue; mgcd[8].gd.pos.x = -15; mgcd[8].gd.pos.y = mgcd[7].gd.pos.y+3; mgcd[8].gd.pos.width = -1; mgcd[8].gd.pos.height = 0; mgcd[8].gd.flags = gg_visible | gg_enabled | gg_but_cancel; mlabel[8].text = (unichar_t *) _("_Cancel"); mlabel[8].text_is_1byte = true; mlabel[8].text_in_resource = true; mgcd[8].gd.label = &mlabel[8]; mgcd[8].gd.mnemonic = 'C'; mgcd[8].gd.handle_controlevent = Prob_Cancel; mgcd[8].creator = GButtonCreate; barray[4] = GCD_Glue; barray[5] = GCD_Glue; barray[6] = &mgcd[8]; barray[7] = GCD_Glue; barray[8] = NULL; mboxes[4].gd.flags = gg_enabled|gg_visible; mboxes[4].gd.u.boxelements = barray; mboxes[4].creator = GHBoxCreate; marray[4][0] = &mboxes[4]; marray[4][1] = NULL; marray[5][0] = NULL; mboxes[0].gd.pos.x = mboxes[0].gd.pos.y = 2; mboxes[0].gd.flags = gg_enabled|gg_visible; mboxes[0].gd.u.boxelements = marray[0]; mboxes[0].creator = GHVGroupCreate; GGadgetsCreate(gw,mboxes); GHVBoxSetExpandableRow(mboxes[0].ret,0); GHVBoxSetExpandableCol(mboxes[2].ret,gb_expandglue); GHVBoxSetExpandableCol(mboxes[3].ret,gb_expandglue); GHVBoxSetExpandableCol(mboxes[4].ret,gb_expandgluesame); GHVBoxSetExpandableRow(pboxes[0].ret,gb_expandglue); GHVBoxSetExpandableCol(pboxes[2].ret,gb_expandglue); GHVBoxSetExpandableCol(pboxes[3].ret,gb_expandglue); GHVBoxSetExpandableCol(pboxes[4].ret,gb_expandglue); GHVBoxSetExpandableRow(paboxes[0].ret,gb_expandglue); GHVBoxSetExpandableCol(paboxes[2].ret,gb_expandglue); GHVBoxSetExpandableRow(rfboxes[0].ret,gb_expandglue); GHVBoxSetExpandableCol(rfboxes[2].ret,gb_expandglue); GHVBoxSetExpandableRow(hboxes[0].ret,gb_expandglue); GHVBoxSetExpandableCol(hboxes[2].ret,gb_expandglue); GHVBoxSetExpandableCol(hboxes[3].ret,gb_expandglue); GHVBoxSetExpandableRow(aboxes[0].ret,gb_expandglue); GHVBoxSetExpandableRow(cboxes[0].ret,gb_expandglue); GHVBoxSetExpandableRow(bbboxes[0].ret,gb_expandglue); GHVBoxSetExpandableCol(bbboxes[0].ret,gb_expandglue); GHVBoxSetExpandableRow(rboxes[0].ret,gb_expandglue); GHVBoxFitWindow(mboxes[0].ret); GDrawSetVisible(gw,true); while ( !p.done ) GDrawProcessOneEvent(NULL); GDrawDestroyWindow(gw); if ( p.explainw!=NULL ) GDrawDestroyWindow(p.explainw); } /* ************************************************************************** */ /* ***************************** Validation code **************************** */ /* ************************************************************************** */ struct val_data { GWindow gw; GWindow v; GGadget *vsb; int lcnt; int loff_top; int vlcnt; SplineFont *sf; int cidmax; enum validation_state mask; int need_to_check_with_user_on_mask; int needs_blue; GTimer *recheck; int laststart; int finished_first_pass; int as,fh; GFont *font; SplineChar *sc; /* used by popup menu */ int lastgid; CharView *lastcv; int layer; }; static char *vserrornames[] = { N_("Open Contour"), N_("Self Intersecting"), N_("Wrong Direction"), N_("Flipped References"), N_("Missing Points at Extrema"), N_("Unknown glyph referenced in GSUB/GPOS/MATH"), N_("Too Many Points"), N_("Too Many Hints"), N_("Bad Glyph Name"), NULL, /* Maxp too many points */ NULL, /* Maxp too many paths */ NULL, /* Maxp too many component points */ NULL, /* Maxp too many component paths */ NULL, /* Maxp instructions too long */ NULL, /* Maxp too many references */ NULL, /* Maxp references too deep */ NULL, /* prep or fpgm too long */ N_("Distance between adjacent points is too big"), N_("Non-integral coordinates"), N_("Contains anchor points for some, but not all, classes in a subtable"), N_("There is another glyph in the font with this name"), N_("There is another glyph in the font with this unicode code point"), N_("Glyph contains overlapped hints (in the same hintmask)") }; static char *privateerrornames[] = { N_("Odd number of elements in BlueValues/OtherBlues array."), N_("Elements in BlueValues/OtherBlues array are disordered."), N_("Too many elements in BlueValues/OtherBlues array."), N_("Elements in BlueValues/OtherBlues array are too close (Change BlueFuzz)."), N_("Elements in BlueValues/OtherBlues array are not integers."), N_("Alignment zone height in BlueValues/OtherBlues array is too big for BlueScale."), NULL, NULL, N_("Odd number of elements in FamilyBlues/FamilyOtherBlues array."), N_("Elements in FamilyBlues/FamilyOtherBlues array are disordered."), N_("Too many elements in FamilyBlues/FamilyOtherBlues array."), N_("Elements in FamilyBlues/FamilyOtherBlues array are too close (Change BlueFuzz)."), N_("Elements in FamilyBlues/FamilyOtherBlues array are not integers."), N_("Alignment zone height in FamilyBlues/FamilyOtherBlues array is too big for BlueScale."), NULL, NULL, N_("Missing BlueValues entry."), N_("Bad BlueFuzz entry."), N_("Bad BlueScale entry."), N_("Bad StdHW entry."), N_("Bad StdVW entry."), N_("Bad StemSnapH entry."), N_("Bad StemSnapV entry."), N_("StemSnapH does not contain StdHW value."), N_("StemSnapV does not contain StdVW value."), N_("Bad BlueShift entry."), NULL }; char *VSErrorsFromMask(int mask, int private_mask) { int bit, m; int len; char *ret; len = 0; for ( m=0, bit=(vs_known<<1) ; bit<=vs_last; ++m, bit<<=1 ) if ( (mask&bit) && vserrornames[m]!=NULL ) len += strlen( _(vserrornames[m]))+2; if ( private_mask != 0 ) len += strlen( _("Bad Private Dictionary")) +2; ret = galloc(len+1); len = 0; for ( m=0, bit=(vs_known<<1) ; bit<=vs_last; ++m, bit<<=1 ) if ( (mask&bit) && vserrornames[m]!=NULL ) { ret[len++] =' '; strcpy(ret+len,_(vserrornames[m])); len += strlen( ret+len ); ret[len++] ='\n'; } if ( private_mask != 0 ) { ret[len++] =' '; strcpy(ret+len,_("Bad Private Dictionary")); len += strlen( ret+len ); ret[len++] ='\n'; } ret[len] = '\0'; return( ret ); } static int VSModMask(SplineChar *sc, struct val_data *vw) { int vs = 0; if ( sc!=NULL ) { vs = sc->layers[vw->layer].validation_state; if ( sc->unlink_rm_ovrlp_save_undo ) vs &= ~vs_selfintersects; /* if doing a truetype eval, then I'm told it's ok for references */ /* to overlap. And if refs can overlap, then we can't figure out */ /* direction properly */ /* I should really check that all the */ /* refs have legal ttf transform matrices */ if ( vw->mask==vs_maskttf && sc->layers[vw->layer].splines==NULL && sc->layers[vw->layer].refs!=NULL ) vs &= ~(vs_selfintersects|vs_wrongdirection); } return( vs ); } static int VW_FindLine(struct val_data *vw,int line, int *skips) { int gid,k, cidmax = vw->cidmax; SplineFont *sf = vw->sf; SplineFont *sub; SplineChar *sc; int sofar, tot; int bit; int vs; sofar = 0; for ( gid=0; gid<cidmax ; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } /* Ignore it if it has not been validated */ /* Ignore it if it is good */ vs = VSModMask(sc,vw); if ((vs&vs_known) && (vs&vw->mask)!=0 ) { tot = 1; if ( sc->vs_open ) for ( bit=(vs_known<<1) ; bit<=vs_last; bit<<=1 ) if ( (bit&vw->mask) && (vs&bit) ) ++tot; if ( sofar+tot>line ) { *skips = line-sofar; return( gid ); } sofar += tot; } } vs = ValidatePrivate(sf); if ( !vw->needs_blue ) vs &= ~pds_missingblue; if ( vs!=0 ) { tot = 1; for ( bit=1 ; bit!=0; bit<<=1 ) if ( vs&bit ) ++tot; if ( sofar+tot>line ) { *skips = line-sofar; return( -2 ); } } *skips = 0; return( -1 ); } static int VW_FindSC(struct val_data *vw,SplineChar *sought) { int gid,k, cidmax = vw->cidmax; SplineFont *sf = vw->sf; SplineFont *sub; SplineChar *sc; int sofar; int bit, vs; sofar = 0; for ( gid=0; gid<cidmax ; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } /* Ignore it if it has not been validated */ /* Ignore it if it is good */ vs = VSModMask(sc,vw); if ((vs&vs_known) && (vs&vw->mask)!=0 ) { if ( sc==sought ) return( sofar ); ++sofar; if ( sc->vs_open ) for ( bit=(vs_known<<1) ; bit<=vs_last; bit<<=1 ) if ( (bit&vw->mask) && (vs&bit) ) ++sofar; } else if ( sc==sought ) return( -1 ); } return( -1 ); } static int VW_VScroll(GGadget *g, GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(GGadgetGetWindow(g)); int newpos = vw->loff_top; switch( e->u.control.u.sb.type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= 9*vw->vlcnt/10; break; case et_sb_up: newpos -= vw->vlcnt/15; break; case et_sb_down: newpos += vw->vlcnt/15; break; case et_sb_downpage: newpos += 9*vw->vlcnt/10; break; case et_sb_bottom: newpos = 0; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = e->u.control.u.sb.pos; break; case et_sb_halfup: newpos -= vw->vlcnt/30; break; case et_sb_halfdown: newpos += vw->vlcnt/30; break; } if ( newpos + vw->vlcnt > vw->lcnt ) newpos = vw->lcnt-vw->vlcnt; if ( newpos<0 ) newpos = 0; if ( vw->loff_top!=newpos ) { vw->loff_top = newpos; GScrollBarSetPos(vw->vsb,newpos); GDrawRequestExpose(vw->v,NULL,false); } return( true ); } static void VW_SetSb(struct val_data *vw) { if ( vw->loff_top + vw->vlcnt > vw->lcnt ) vw->loff_top = vw->lcnt-vw->vlcnt; if ( vw->loff_top<0 ) vw->loff_top = 0; GScrollBarSetBounds(vw->vsb,0,vw->lcnt,vw->vlcnt); GScrollBarSetPos(vw->vsb,vw->loff_top); } static void VW_Remetric(struct val_data *vw) { int gid,k, cidmax = vw->cidmax; SplineFont *sub, *sf = vw->sf; SplineChar *sc; int sofar, tot; int bit, vs; sofar = 0; for ( gid=0; gid<cidmax ; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } /* Ignore it if it has not been validated */ /* Ignore it if it is good */ vs = VSModMask(sc,vw); if ((vs&vs_known) && (vs&vw->mask)!=0 ) { tot = 1; if ( sc->vs_open ) for ( bit=(vs_known<<1) ; bit<=vs_last; bit<<=1 ) if ( (bit&vw->mask) && (vs&bit) ) ++tot; sofar += tot; } } vs = ValidatePrivate(sf); if ( !vw->needs_blue ) vs &= ~pds_missingblue; if ( vs!=0 ) { tot = 1; for ( bit=1 ; bit!=0; bit<<=1 ) if ( vs&bit ) ++tot; sofar += tot; } if ( vw->lcnt!=sofar ) { vw->lcnt = sofar; VW_SetSb(vw); } GDrawRequestExpose(vw->v,NULL,false); } static void VWMenuConnect(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; int changed = false; SplineSet *ss; for ( ss=sc->layers[vw->layer].splines; ss!=NULL; ss=ss->next ) { if ( ss->first->prev==NULL && ss->first->next!=NULL ) { if ( !changed ) { SCPreserveLayer(sc,vw->layer,false); changed = true; } SplineMake(ss->last,ss->first,sc->layers[vw->layer].order2); ss->last = ss->first; } } if ( changed ) { SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } } static void VWMenuInlineRefs(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; int changed = false; RefChar *ref, *refnext; for ( ref= sc->layers[vw->layer].refs; ref!=NULL; ref=refnext ) { refnext = ref->next; if ( !changed ) SCPreserveLayer(sc,vw->layer,false); changed = true; SCRefToSplines(sc,ref,vw->layer); } if ( changed ) { SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } } static void VWMenuOverlap(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; if ( !SCRoundToCluster(sc,ly_all,false,.03,.12)) SCPreserveLayer(sc,vw->layer,false); sc->layers[vw->layer].splines = SplineSetRemoveOverlap(sc,sc->layers[vw->layer].splines,over_remove); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWMenuMark(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; sc->unlink_rm_ovrlp_save_undo = true; VW_Remetric(vw); } static void VWMenuInlineFlippedRefs(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; int changed = false; RefChar *ref, *refnext; for ( ref= sc->layers[vw->layer].refs; ref!=NULL; ref=refnext ) { refnext = ref->next; if ( ref->transform[0]*ref->transform[3]<0 || (ref->transform[0]==0 && ref->transform[1]*ref->transform[2]>0)) { if ( !changed ) SCPreserveLayer(sc,vw->layer,false); changed = true; SCRefToSplines(sc,ref,vw->layer); } } if ( changed ) { SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } } static void VWMenuCorrectDir(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; int changed = false; SCPreserveLayer(sc,vw->layer,false); sc->layers[vw->layer].splines = SplineSetsCorrect(sc->layers[vw->layer].splines,&changed); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWMenuGoodExtrema(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineFont *sf = vw->sf; int emsize = sf->ascent+sf->descent; SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); SplineCharAddExtrema(sc,sc->layers[vw->layer].splines,ae_only_good,emsize); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWMenuAllExtrema(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineFont *sf = vw->sf; int emsize = sf->ascent+sf->descent; SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); SplineCharAddExtrema(sc,sc->layers[vw->layer].splines,ae_all,emsize); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWMenuSimplify(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc = vw->sc; int vs = sc->layers[vw->layer].validation_state; static struct simplifyinfo smpl = { sf_normal,.75,.05,0,-1 }; SCPreserveLayer(sc,vw->layer,false); sc->layers[vw->layer].splines = SplineCharSimplify(sc,sc->layers[vw->layer].splines,&smpl); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWMenuRevalidateAll(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL ) { sc->layers[vw->layer].validation_state = 0; sc->layers[vw->layer].old_vs = 2; } ++k; } while ( k<vw->sf->subfontcnt ); VW_Remetric(vw); } static void VWMenuRevalidate(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); int vs = vw->sc->layers[vw->layer].validation_state; SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } static void VWReuseCV(struct val_data *vw, SplineChar *sc) { int k; SplineChar *sctest; SplineFont *sf = vw->sf; CharView *cv; /* See if the last cv we used is still open. This is a little complex as */ /* we must make sure that the splinechar is still in the font, and then */ /* that the cv is still attached to it */ cv = NULL; if ( vw->lastgid!=-1 && vw->lastcv!=NULL ) { sctest = NULL; if ( sf->subfontcnt==0 ) { if ( vw->lastgid<sf->glyphcnt ) sctest = sf->glyphs[vw->lastgid]; } else { for ( k = 0; k<sf->subfontcnt; ++k ) if ( vw->lastgid<sf->subfonts[k]->glyphcnt ) if ( (sctest = sf->subfonts[k]->glyphs[vw->lastgid])!=NULL ) break; } if ( sctest!=NULL ) for ( cv=(CharView *) (sctest->views); cv!=NULL && cv!=vw->lastcv; cv=(CharView *) (cv->b.next) ); } if ( cv==NULL ) cv = CharViewCreate(sc,(FontView *) (vw->sf->fv),vw->sf->fv->map->backmap[sc->orig_pos]); else { CVChangeSC(cv,sc); GDrawSetVisible(cv->gw,true); GDrawRaise(cv->gw); } if ( CVLayer((CharViewBase *) cv)!=vw->layer ) CVSetLayer(cv,vw->layer); vw->lastgid = sc->orig_pos; vw->lastcv = cv; if ( sc->layers[vw->layer].validation_state & vs_maskfindproblems & vw->mask ) DummyFindProblems(cv); } static void VWMenuOpenGlyph(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); VWReuseCV(vw,vw->sc); } static void VWMenuGotoGlyph(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); FontView *fv = (FontView *) (vw->sf->fv); int enc = GotoChar(vw->sf,fv->b.map,NULL); int gid, line; SplineChar *sc; if ( enc==-1 ) return; gid = fv->b.map->map[enc]; if ( gid==-1 || (sc=vw->sf->glyphs[gid])==NULL ) { ff_post_error(_("Glyph not in font"), _("Glyph not in font")); return; } else if ( (SCValidate(sc,vw->layer,true)&vw->mask)==0 ) { ff_post_notice(_("Glyph Valid"), _("No problems detected in %s"), sc->name ); return; } line = VW_FindSC(vw,sc); if ( line==-1 ) IError("Glyph doesn't exist?"); if ( line + vw->vlcnt > vw->lcnt ) line = vw->lcnt-vw->vlcnt; if ( line<0 ) line = 0; if ( vw->loff_top!=line ) { vw->loff_top = line; GScrollBarSetPos(vw->vsb,line); GDrawRequestExpose(vw->v,NULL,false); } } #define MID_SelectOpen 102 #define MID_SelectRO 103 #define MID_SelectDir 104 #define MID_SelectExtr 105 #define MID_SelectErrors 106 static void VWMenuSelect(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); FontView *fv = (FontView *) (vw->sf->fv); int mask = mi->mid == MID_SelectErrors ? vw->mask : mi->mid == MID_SelectOpen ? vs_opencontour : mi->mid == MID_SelectRO ? vs_selfintersects : mi->mid == MID_SelectDir ? vs_wrongdirection : mi->mid == MID_SelectExtr ? vs_missingextrema : 0; EncMap *map = fv->b.map; int i, gid; SplineChar *sc; for ( i=0; i<map->enccount; ++i ) { fv->b.selected[i] = false; gid = map->map[i]; if ( gid!=-1 && (sc=vw->sf->glyphs[gid])!=NULL && (SCValidate(sc,vw->layer,true) & mask) ) fv->b.selected[i] = true; } GDrawSetVisible(fv->gw,true); GDrawRaise(fv->gw); GDrawRequestExpose(fv->v,NULL,false); } static GMenuItem vw_subselect[] = { { { (unichar_t *) N_("problselect|Errors"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuSelect, MID_SelectErrors }, { { (unichar_t *) N_("problselect|Open Contours"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuSelect, MID_SelectOpen }, { { (unichar_t *) N_("problselect|Bad Direction"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuSelect, MID_SelectDir }, { { (unichar_t *) N_("problselect|Self Intersections"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuSelect, MID_SelectRO }, { { (unichar_t *) N_("problselect|Missing Extrema"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuSelect, MID_SelectExtr }, NULL }; static void VWMenuManyConnect(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_opencontour) ) { int vs = sc->layers[vw->layer].validation_state; int changed = false; SplineSet *ss; for ( ss=sc->layers[vw->layer].splines; ss!=NULL; ss=ss->next ) { if ( ss->first->prev==NULL && ss->first->next!=NULL ) { if ( !changed ) { SCPreserveLayer(sc,vw->layer,false); changed = true; } SplineMake(ss->last,ss->first,sc->layers[vw->layer].order2); ss->last = ss->first; } } if ( changed ) { SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManyOverlap(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_selfintersects) ) { int vs = sc->layers[vw->layer].validation_state; /* If it's only got references, I could inline them, since the */ /* intersection would occur between two refs. But that seems */ /* to extreme to do to an unsuspecting user */ if ( !SCRoundToCluster(sc,ly_all,false,.03,.12)) SCPreserveLayer(sc,vw->layer,false); sc->layers[vw->layer].splines = SplineSetRemoveOverlap(sc,sc->layers[vw->layer].splines,over_remove); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManyMark(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_selfintersects) && sc->layers[vw->layer].refs!=NULL && sc->layers[vw->layer].refs->next!=NULL && sc->layers[vw->layer].splines==NULL ) { sc->unlink_rm_ovrlp_save_undo = true; VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManyCorrectDir(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; RefChar *ref, *refnext; int changed; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_wrongdirection) ) { int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); /* But a flipped reference is just wrong so I have no compunctions*/ /* about inlining it and then correcting its direction */ for ( ref= sc->layers[vw->layer].refs; ref!=NULL; ref=refnext ) { refnext = ref->next; if ( ref->transform[0]*ref->transform[3]<0 || (ref->transform[0]==0 && ref->transform[1]*ref->transform[2]>0)) { SCRefToSplines(sc,ref,vw->layer); } } sc->layers[vw->layer].splines = SplineSetsCorrect(sc->layers[vw->layer].splines,&changed); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManyGoodExtrema(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf = vw->sf; int emsize = sf->ascent+sf->descent; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_missingextrema) ) { int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); SplineCharAddExtrema(sc,sc->layers[vw->layer].splines,ae_only_good,emsize); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManyAllExtrema(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf = vw->sf; int emsize = sf->ascent+sf->descent; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_missingextrema) ) { int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); SplineCharAddExtrema(sc,sc->layers[vw->layer].splines,ae_all,emsize); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static void VWMenuManySimplify(GWindow gw,struct gmenuitem *mi,GEvent *e) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); SplineChar *sc; int k, gid; SplineFont *sf; static struct simplifyinfo smpl = { sf_normal,.75,.05,0,-1 }; k=0; do { sf = k<vw->sf->subfontcnt ? vw->sf->subfonts[k] : vw->sf; for ( gid=0; gid<sf->glyphcnt; ++gid ) if ( (sc=sf->glyphs[gid])!=NULL && (sc->layers[vw->layer].validation_state&vs_toomanypoints) ) { int vs = sc->layers[vw->layer].validation_state; SCPreserveLayer(sc,vw->layer,false); sc->layers[vw->layer].splines = SplineCharSimplify(sc,sc->layers[vw->layer].splines,&smpl); SCCharChangedUpdate(sc,vw->layer); SCValidate(vw->sc,vw->layer,true); if ( vs != vw->sc->layers[vw->layer].validation_state ) VW_Remetric(vw); } ++k; } while ( k<vw->sf->subfontcnt ); } static GMenuItem vw_subfixup[] = { { { (unichar_t *) N_("problfixup|Open Contours"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuManyConnect }, { { (unichar_t *) N_("problfixup|Self Intersections"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManyOverlap }, { { (unichar_t *) N_("problfixup|Mark for Overlap fix before Save"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManyMark }, { { (unichar_t *) N_("problfixup|Bad Directions"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManyCorrectDir }, { { (unichar_t *) N_("problfixup|Missing Extrema (cautiously)"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManyGoodExtrema }, { { (unichar_t *) N_("problfixup|Missing Extrema"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManyAllExtrema }, { { (unichar_t *) N_("problfixup|Too Many Points"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuManySimplify }, NULL }; static GMenuItem vw_popuplist[] = { { { (unichar_t *) N_("Close Open Contours"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuConnect }, { { (unichar_t *) N_("Inline All References"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuInlineRefs }, { { (unichar_t *) N_("Remove Overlap"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuOverlap }, { { (unichar_t *) N_("Mark for Overlap fix before Save"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuMark }, { { (unichar_t *) N_("Inline Flipped References"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuInlineFlippedRefs }, { { (unichar_t *) N_("Correct Direction"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuCorrectDir }, { { (unichar_t *) N_("Add Good Extrema"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuGoodExtrema }, { { (unichar_t *) N_("Add All Extrema"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuAllExtrema }, { { (unichar_t *) N_("Simplify"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 0 }, 0,0, NULL, NULL, VWMenuSimplify }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 1, 0, 0, }}, { { (unichar_t *) N_("Revalidate All"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuRevalidateAll }, { { (unichar_t *) N_("Revalidate"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuRevalidate }, { { (unichar_t *) N_("Open Glyph"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuOpenGlyph }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 1, 0, 0, }}, { { (unichar_t *) N_("Scroll To Glyph"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, NULL, NULL, VWMenuGotoGlyph }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 1, 0, 0, }}, { { (unichar_t *) N_("Select Glyphs With"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, vw_subselect }, { { (unichar_t *) N_("Try To Fix Glyphs With"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, '\0', 0, vw_subfixup }, { NULL } }; static void VWMouse(struct val_data *vw, GEvent *e) { int skips; int gid = VW_FindLine(vw,vw->loff_top + e->u.mouse.y/vw->fh, &skips); SplineChar *sc; int k=0; if ( gid==-2 && e->u.mouse.clicks==2 && e->type==et_mouseup ) { FontInfo(vw->sf,vw->layer,4,false); /* Bring up the Private Dict */ return; } if ( gid<0 ) return; if ( vw->sf->subfontcnt==0 ) { if ( (sc = vw->sf->glyphs[gid])==NULL ) return; } else { sc = NULL; for ( k=0; k<vw->sf->subfontcnt; ++k ) { if ( gid<vw->sf->subfonts[k]->glyphcnt && (sc=vw->sf->subfonts[k]->glyphs[gid])!=NULL ) break; } if ( sc==NULL ) return; } if ( e->u.mouse.clicks==2 && e->type==et_mouseup ) { VWReuseCV(vw,sc); } else if ( e->type==et_mouseup && e->u.mouse.x<10+vw->as && skips==0 ) { sc->vs_open = !sc->vs_open; VW_Remetric(vw); } else if ( e->type==et_mousedown && e->u.mouse.button==3 ) { static int initted = false; if ( !initted ) { int i; initted = true; for ( i=0; vw_popuplist[i].ti.text!=NULL || vw_popuplist[i].ti.line; ++i ) if ( vw_popuplist[i].ti.text!=NULL ) vw_popuplist[i].ti.text = (unichar_t *) _( (char *)vw_popuplist[i].ti.text); for (i=0; vw_subfixup[i].ti.text!=NULL || vw_subfixup[i].ti.line; ++i ) if ( vw_subfixup[i].ti.text!=NULL ) vw_subfixup[i].ti.text = (unichar_t *) S_( (char *)vw_subfixup[i].ti.text); for (i=0; vw_subselect[i].ti.text!=NULL || vw_subselect[i].ti.line; ++i ) if ( vw_subselect[i].ti.text!=NULL ) vw_subselect[i].ti.text = (unichar_t *) S_( (char *)vw_subselect[i].ti.text); } vw_popuplist[0].ti.disabled = (sc->layers[vw->layer].validation_state&vs_opencontour)?0:1; vw_popuplist[1].ti.disabled = (SCValidate(sc,vw->layer,true)&vs_selfintersects)?0:1; vw_popuplist[2].ti.disabled = (SCValidate(sc,vw->layer,true)&vs_selfintersects)?0:1; vw_popuplist[3].ti.disabled = (SCValidate(sc,vw->layer,true)&vs_selfintersects) && sc->layers[vw->layer].refs!=NULL?0:1; vw_popuplist[4].ti.disabled = (sc->layers[vw->layer].validation_state&vs_flippedreferences)?0:1; vw_popuplist[5].ti.disabled = (sc->layers[vw->layer].validation_state&vs_wrongdirection)?0:1; vw_popuplist[6].ti.disabled = (sc->layers[vw->layer].validation_state&vs_missingextrema)?0:1; vw_popuplist[7].ti.disabled = (sc->layers[vw->layer].validation_state&vs_missingextrema)?0:1; vw_popuplist[8].ti.disabled = (sc->layers[vw->layer].validation_state&vs_toomanypoints)?0:1; vw->sc = sc; GMenuCreatePopupMenu(vw->v,e, vw_popuplist); } } static void VWDrawWindow(GWindow pixmap,struct val_data *vw, GEvent *e) { int gid,k, cidmax = vw->cidmax; SplineFont *sub, *sf=vw->sf; SplineChar *sc; int sofar; int bit, skips, vs, y, m; GRect old, r; GDrawPushClip(pixmap,&e->u.expose.rect,&old); GDrawSetFont(pixmap,vw->font); gid = VW_FindLine(vw,vw->loff_top, &skips); if ( gid==-1 ) { GDrawDrawBiText8(pixmap,2,(vw->vlcnt-1)*vw->fh/2 + vw->as, vw->finished_first_pass ? _("Passed Validation") : _("Thinking..."), -1,NULL,0x000000 ); GDrawPopClip(pixmap,&old); return; } y = vw->as - skips*vw->fh; sofar = -skips; r.width = r.height = vw->as; if ( gid!=-2 ) { for ( ; gid<cidmax && sofar<vw->vlcnt ; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } /* Ignore it if it has not been validated */ /* Ignore it if it is good */ vs = VSModMask(sc,vw); if ((vs&vs_known) && (vs&vw->mask)!=0 ) { r.x = 2; r.y = y-vw->as+1; GDrawDrawRect(pixmap,&r,0x000000); GDrawDrawLine(pixmap,r.x+2,r.y+vw->as/2,r.x+vw->as-2,r.y+vw->as/2, 0x000000); if ( !sc->vs_open ) GDrawDrawLine(pixmap,r.x+vw->as/2,r.y+2,r.x+vw->as/2,r.y+vw->as-2, 0x000000); GDrawDrawBiText8(pixmap,r.x+r.width+2,y,sc->name,-1,NULL,0x000000 ); y += vw->fh; ++sofar; if ( sc->vs_open ) { for ( m=0, bit=(vs_known<<1) ; bit<=vs_last; ++m, bit<<=1 ) if ( (bit&vw->mask) && (vs&bit) && vserrornames[m]!=NULL ) { GDrawDrawBiText8(pixmap,10+r.width+r.x,y,_(vserrornames[m]),-1,NULL,0xff0000 ); y += vw->fh; ++sofar; } } } } } if ( sofar<vw->vlcnt ) { vs = ValidatePrivate(sf); if ( !vw->needs_blue ) vs &= ~pds_missingblue; if ( vs!=0 ) { /* GT: "Private" is a keyword (sort of) in PostScript. Perhaps it */ /* GT: should remain untranslated? */ GDrawDrawBiText8(pixmap,r.x+r.width+2,y,_("Private Dictionary"),-1,NULL,0x000000 ); y += vw->fh; for ( m=0, bit=1 ; bit!=0; ++m, bit<<=1 ) { if ( vs&bit ) { GDrawDrawBiText8(pixmap,10+r.width+r.x,y,_(privateerrornames[m]),-1,NULL,0xff0000 ); y += vw->fh; } } } } GDrawPopClip(pixmap,&old); } static int VWCheckup(struct val_data *vw) { /* Check some glyphs to see what their validation state is or if they have*/ /* changed */ int gid, k, cnt=0; int max; SplineFont *sf=vw->sf, *sub; int cntmax = vw->finished_first_pass ? 40 : 60; SplineChar *sc; int a_change = false; int firstv = true; char *buts[4]; if ( sf->subfontcnt==0 ) max = vw->cidmax = sf->glyphcnt; else max = vw->cidmax; for ( gid=vw->laststart; gid<max && cnt<cntmax && gid<vw->laststart+2000; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } if ( sc!=NULL && !(sc->layers[vw->layer].validation_state&vs_known)) { if ( firstv ) { GDrawSetCursor(vw->v,ct_watch); GDrawSync(NULL); firstv = false; } SCValidate(sc,vw->layer,true); ++cnt; } if ( sc!=NULL && vw->need_to_check_with_user_on_mask && (sc->layers[vw->layer].validation_state&vs_nonintegral )) { vw->need_to_check_with_user_on_mask = false; buts[0] = _("Report as Error"); buts[1]=_("Ignore"); buts[2] = NULL; if ( ff_ask(_("Not sure if this is an error..."),(const char **) buts,0,1, _("This font contains non-integral coordinates. That's OK\n" "in PostScript and SVG but causes problems in TrueType.\n" "Should I consider that an error here?"))==0 ) { a_change = true; vw->mask |= vs_nonintegral; } } if ( sc!=NULL && sc->layers[vw->layer].validation_state!=sc->layers[vw->layer].old_vs ) { a_change = true; sc->layers[vw->layer].old_vs = sc->layers[vw->layer].validation_state; } } if ( gid<max ) vw->laststart = gid; else { vw->laststart = 0; if ( !vw->finished_first_pass ) { vw->finished_first_pass = true; GDrawCancelTimer(vw->recheck); /* Check less frequently now we've completed a full scan */ vw->recheck = GDrawRequestTimer(vw->v,3000,3000,NULL); } } if ( a_change ) VW_Remetric(vw); if ( !firstv ) GDrawSetCursor(vw->v,ct_mypointer); return( a_change ); } static int VW_OK(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct val_data *vw = (struct val_data *) GDrawGetUserData(GGadgetGetWindow(g)); GDrawDestroyWindow(vw->gw); } return( true ); } static int vwv_e_h(GWindow gw, GEvent *event) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); switch ( event->type ) { case et_expose: if ( vw->recheck==NULL ) { vw->recheck = GDrawRequestTimer(vw->v,500,500,NULL); VWCheckup(vw); } VWDrawWindow(gw,vw,event); break; case et_mouseup: case et_mousedown: case et_mousemove: if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(vw->vsb,event)); } VWMouse(vw,event); break; case et_char: return( false ); break; case et_resize: { int vlcnt = event->u.resize.size.height/vw->fh; vw->vlcnt = vlcnt; VW_SetSb(vw); GDrawRequestExpose(vw->v,NULL,false); } break; case et_timer: VWCheckup(vw); break; } return( true ); } static int vw_e_h(GWindow gw, GEvent *event) { struct val_data *vw = (struct val_data *) GDrawGetUserData(gw); if ( event->type==et_close ) { GDrawDestroyWindow(gw); } else if ( event->type == et_char ) { return( false ); } else if ( event->type == et_destroy ) { if ( vw->sf!=NULL ) vw->sf->valwin = NULL; chunkfree(vw,sizeof(*vw)); } return( true ); } void SFValidationWindow(SplineFont *sf,int layer,enum fontformat format) { GWindowAttrs wattrs; GRect pos; GWindow gw; GGadgetCreateData gcd[4], boxes[4], *harray[4], *butarray[8], *varray[3]; GTextInfo label[4]; struct val_data *valwin; char buffer[200]; int k, gid; int cidmax; SplineFont *sub; SplineChar *sc; FontRequest rq; int as, ds, ld; int mask, needs_blue; static GFont *valfont=NULL; if ( sf->cidmaster ) sf = sf->cidmaster; mask = VSMaskFromFormat(sf,layer,format); needs_blue = (mask==vs_maskps || mask==vs_maskcid); if ( sf->valwin!=NULL ) { /* Don't need to force a revalidation because if the window exists */ /* it's been doing that all by itself */ if ( mask!=(sf->valwin->mask&~vs_nonintegral) ) { /* But if we go from postscript to truetype the types of errors */ /* change, so what we display might be different */ sf->valwin->mask = mask; sf->valwin->needs_blue = needs_blue; sf->valwin->layer = layer; VW_Remetric(sf->valwin); } GDrawSetVisible(sf->valwin->gw,true); GDrawRaise(sf->valwin->gw); return; } if ( sf->subfontcnt!=0 ) { cidmax = 0; for ( k=0; k<sf->subfontcnt; ++k ) if ( sf->subfonts[k]->glyphcnt > cidmax ) cidmax = sf->subfonts[k]->glyphcnt; } else cidmax = sf->glyphcnt; /* Init all glyphs as undrawn */ for ( gid=0; gid<cidmax ; ++gid ) { if ( sf->subfontcnt==0 ) sc = sf->glyphs[gid]; else { for ( k=0; k<sf->subfontcnt; ++k ) { sub = sf->subfonts[k]; if ( gid<sub->glyphcnt && (sc = sub->glyphs[gid])!=NULL ) break; } } if ( sc!=NULL ) { sc->layers[layer].old_vs = 0; sc->vs_open = true; /* should this default to false? */ } } valwin = chunkalloc(sizeof(struct val_data)); valwin->sf = sf; valwin->mask = mask; valwin->needs_blue = needs_blue; valwin->cidmax = cidmax; valwin->lastgid = -1; valwin->layer = layer; valwin->need_to_check_with_user_on_mask = (format==ff_none && !sf->layers[layer].order2 ); memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg; wattrs.event_masks = -1; wattrs.cursor = ct_mypointer; sprintf( buffer, _("Validation of %.100s"), sf->fontname ); wattrs.utf8_window_title = buffer; wattrs.is_dlg = true; wattrs.undercursor = 1; pos.x = pos.y = 0; pos.width = GDrawPointsToPixels(NULL,200); pos.height = GDrawPointsToPixels(NULL,300); valwin->gw = gw = GDrawCreateTopWindow(NULL,&pos,vw_e_h,valwin,&wattrs); if ( valfont==NULL ) { memset(&rq,0,sizeof(rq)); rq.utf8_family_name = "Helvetica"; rq.point_size = 11; rq.weight = 400; valfont = GDrawInstanciateFont(GDrawGetDisplayOfWindow(gw),&rq); valfont = GResourceFindFont("Validate.Font",valfont); } valwin->font = valfont; GDrawFontMetrics(valwin->font,&as,&ds,&ld); valwin->fh = as+ds; valwin->as = as; memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); memset(&boxes,0,sizeof(boxes)); k = 0; gcd[k].gd.flags = gg_visible | gg_enabled; gcd[k].gd.u.drawable_e_h = vwv_e_h; gcd[k++].creator = GDrawableCreate; gcd[k].gd.flags = gg_visible | gg_enabled | gg_sb_vert; gcd[k].gd.handle_controlevent = VW_VScroll; gcd[k++].creator = GScrollBarCreate; harray[0] = &gcd[k-2]; harray[1] = &gcd[k-1]; harray[2] = NULL; harray[3] = NULL; gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default; label[k].text = (unichar_t *) _("_OK"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.handle_controlevent = VW_OK; gcd[k++].creator = GButtonCreate; butarray[0] = GCD_Glue; butarray[1] = &gcd[k-1]; butarray[2] = GCD_Glue; butarray[3] = NULL; boxes[2].gd.flags = gg_enabled|gg_visible; boxes[2].gd.u.boxelements = harray; boxes[2].creator = GHVGroupCreate; boxes[3].gd.flags = gg_enabled|gg_visible; boxes[3].gd.u.boxelements = butarray; boxes[3].creator = GHBoxCreate; varray[0] = &boxes[2]; varray[1] = &boxes[3]; varray[2] = NULL; boxes[0].gd.flags = gg_enabled|gg_visible; boxes[0].gd.u.boxelements = varray; boxes[0].creator = GVBoxCreate; GGadgetsCreate(gw,boxes); valwin->vsb = gcd[1].ret; valwin->v = GDrawableGetWindow(gcd[0].ret); GHVBoxSetExpandableRow(boxes[0].ret,0); GHVBoxSetExpandableCol(boxes[2].ret,0); GHVBoxSetPadding(boxes[2].ret,0,0); GHVBoxSetExpandableCol(boxes[3].ret,gb_expandglue); GHVBoxFitWindow(boxes[0].ret); GDrawSetVisible(gw,true); } void ValidationDestroy(SplineFont *sf) { if ( sf->valwin!=NULL ) { sf->valwin->sf = NULL; GDrawDestroyWindow(sf->valwin->gw); sf->valwin = NULL; } }
37.145993
474
0.628256
[ "shape", "vector", "transform" ]
9b311b39a826d54b81d31e4844bae4977efe4fac
22,756
c
C
sh2emu/tk_qsrc/doomsrc/i_video.c
cr88192/bgbtech_shxemu
0e8c2de32c94631a1c18df17f23385235dc67879
[ "MIT" ]
5
2017-02-23T21:23:16.000Z
2018-04-12T20:42:03.000Z
software/firmware/linuxdoom-1.10/i_video.c
netik/dc28_badge
356ba57b4d1e83c310cc6136bd7f038df7533031
[ "Apache-2.0" ]
null
null
null
software/firmware/linuxdoom-1.10/i_video.c
netik/dc28_badge
356ba57b4d1e83c310cc6136bd7f038df7533031
[ "Apache-2.0" ]
null
null
null
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id:$ // // Copyright (C) 1993-1996 by id Software, Inc. // // This source is available for distribution and/or modification // only under the terms of the DOOM Source Code License as // published by id Software. All rights reserved. // // The source is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License // for more details. // // $Log:$ // // DESCRIPTION: // DOOM graphics stuff for X11, UNIX. // //----------------------------------------------------------------------------- static const char rcsid[] = "$Id: i_x.c,v 1.6 1997/02/03 22:45:10 b1 Exp $"; #include <stdlib.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <X11/extensions/XShm.h> // Had to dig up XShm.c for this one. // It is in the libXext, but not in the XFree86 headers. #ifdef LINUX int XShmGetEventBase( Display* dpy ); // problems with g++? #endif #include <stdarg.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errnos.h> #include <signal.h> #include "doomstat.h" #include "i_system.h" #include "v_video.h" #include "m_argv.h" #include "d_main.h" #include "doomdef.h" #define POINTER_WARP_COUNTDOWN 1 Display* X_display=0; Window X_mainWindow; Colormap X_cmap; Visual* X_visual; GC X_gc; XEvent X_event; int X_screen; XVisualInfo X_visualinfo; XImage* image; int X_width; int X_height; // MIT SHared Memory extension. boolean doShm; XShmSegmentInfo X_shminfo; int X_shmeventtype; // Fake mouse handling. // This cannot work properly w/o DGA. // Needs an invisible mouse cursor at least. boolean grabMouse; int doPointerWarp = POINTER_WARP_COUNTDOWN; // Blocky mode, // replace each 320x200 pixel with multiply*multiply pixels. // According to Dave Taylor, it still is a bonehead thing // to use .... static int multiply=1; // // Translates the key currently in X_event // int xlatekey(void) { int rc; switch(rc = XKeycodeToKeysym(X_display, X_event.xkey.keycode, 0)) { case XK_Left: rc = KEY_LEFTARROW; break; case XK_Right: rc = KEY_RIGHTARROW; break; case XK_Down: rc = KEY_DOWNARROW; break; case XK_Up: rc = KEY_UPARROW; break; case XK_Escape: rc = KEY_ESCAPE; break; case XK_Return: rc = KEY_ENTER; break; case XK_Tab: rc = KEY_TAB; break; case XK_F1: rc = KEY_F1; break; case XK_F2: rc = KEY_F2; break; case XK_F3: rc = KEY_F3; break; case XK_F4: rc = KEY_F4; break; case XK_F5: rc = KEY_F5; break; case XK_F6: rc = KEY_F6; break; case XK_F7: rc = KEY_F7; break; case XK_F8: rc = KEY_F8; break; case XK_F9: rc = KEY_F9; break; case XK_F10: rc = KEY_F10; break; case XK_F11: rc = KEY_F11; break; case XK_F12: rc = KEY_F12; break; case XK_BackSpace: case XK_Delete: rc = KEY_BACKSPACE; break; case XK_Pause: rc = KEY_PAUSE; break; case XK_KP_Equal: case XK_equal: rc = KEY_EQUALS; break; case XK_KP_Subtract: case XK_minus: rc = KEY_MINUS; break; case XK_Shift_L: case XK_Shift_R: rc = KEY_RSHIFT; break; case XK_Control_L: case XK_Control_R: rc = KEY_RCTRL; break; case XK_Alt_L: case XK_Meta_L: case XK_Alt_R: case XK_Meta_R: rc = KEY_RALT; break; default: if (rc >= XK_space && rc <= XK_asciitilde) rc = rc - XK_space + ' '; if (rc >= 'A' && rc <= 'Z') rc = rc - 'A' + 'a'; break; } return rc; } void I_ShutdownGraphics(void) { // Detach from X server if (!XShmDetach(X_display, &X_shminfo)) I_Error("XShmDetach() failed in I_ShutdownGraphics()"); // Release shared memory. shmdt(X_shminfo.shmaddr); shmctl(X_shminfo.shmid, IPC_RMID, 0); // Paranoia. image->data = NULL; } // // I_StartFrame // void I_StartFrame (void) { // er? } static int lastmousex = 0; static int lastmousey = 0; boolean mousemoved = false; boolean shmFinished; void I_GetEvent(void) { event_t event; // put event-grabbing stuff in here XNextEvent(X_display, &X_event); switch (X_event.type) { case KeyPress: event.type = ev_keydown; event.data1 = xlatekey(); D_PostEvent(&event); // fprintf(stderr, "k"); break; case KeyRelease: event.type = ev_keyup; event.data1 = xlatekey(); D_PostEvent(&event); // fprintf(stderr, "ku"); break; case ButtonPress: event.type = ev_mouse; event.data1 = (X_event.xbutton.state & Button1Mask) | (X_event.xbutton.state & Button2Mask ? 2 : 0) | (X_event.xbutton.state & Button3Mask ? 4 : 0) | (X_event.xbutton.button == Button1) | (X_event.xbutton.button == Button2 ? 2 : 0) | (X_event.xbutton.button == Button3 ? 4 : 0); event.data2 = event.data3 = 0; D_PostEvent(&event); // fprintf(stderr, "b"); break; case ButtonRelease: event.type = ev_mouse; event.data1 = (X_event.xbutton.state & Button1Mask) | (X_event.xbutton.state & Button2Mask ? 2 : 0) | (X_event.xbutton.state & Button3Mask ? 4 : 0); // suggest parentheses around arithmetic in operand of | event.data1 = event.data1 ^ (X_event.xbutton.button == Button1 ? 1 : 0) ^ (X_event.xbutton.button == Button2 ? 2 : 0) ^ (X_event.xbutton.button == Button3 ? 4 : 0); event.data2 = event.data3 = 0; D_PostEvent(&event); // fprintf(stderr, "bu"); break; case MotionNotify: event.type = ev_mouse; event.data1 = (X_event.xmotion.state & Button1Mask) | (X_event.xmotion.state & Button2Mask ? 2 : 0) | (X_event.xmotion.state & Button3Mask ? 4 : 0); event.data2 = (X_event.xmotion.x - lastmousex) << 2; event.data3 = (lastmousey - X_event.xmotion.y) << 2; if (event.data2 || event.data3) { lastmousex = X_event.xmotion.x; lastmousey = X_event.xmotion.y; if (X_event.xmotion.x != X_width/2 && X_event.xmotion.y != X_height/2) { D_PostEvent(&event); // fprintf(stderr, "m"); mousemoved = false; } else { mousemoved = true; } } break; case Expose: case ConfigureNotify: break; default: if (doShm && X_event.type == X_shmeventtype) shmFinished = true; break; } } Cursor createnullcursor ( Display* display, Window root ) { Pixmap cursormask; XGCValues xgc; GC gc; XColor dummycolour; Cursor cursor; cursormask = XCreatePixmap(display, root, 1, 1, 1/*depth*/); xgc.function = GXclear; gc = XCreateGC(display, cursormask, GCFunction, &xgc); XFillRectangle(display, cursormask, gc, 0, 0, 1, 1); dummycolour.pixel = 0; dummycolour.red = 0; dummycolour.flags = 04; cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0); XFreePixmap(display,cursormask); XFreeGC(display,gc); return cursor; } // // I_StartTic // void I_StartTic (void) { if (!X_display) return; while (XPending(X_display)) I_GetEvent(); // Warp the pointer back to the middle of the window // or it will wander off - that is, the game will // loose input focus within X11. if (grabMouse) { if (!--doPointerWarp) { XWarpPointer( X_display, None, X_mainWindow, 0, 0, 0, 0, X_width/2, X_height/2); doPointerWarp = POINTER_WARP_COUNTDOWN; } } mousemoved = false; } // // I_UpdateNoBlit // void I_UpdateNoBlit (void) { // what is this? } // // I_FinishUpdate // void I_FinishUpdate (void) { static int lasttic; int tics; int i; // UNUSED static unsigned char *bigscreen=0; // draws little dots on the bottom of the screen if (devparm) { i = I_GetTime(); tics = i - lasttic; lasttic = i; if (tics > 20) tics = 20; for (i=0 ; i<tics*2 ; i+=2) screens[0][ (SCREENHEIGHT-1)*SCREENWIDTH + i] = 0xff; for ( ; i<20*2 ; i+=2) screens[0][ (SCREENHEIGHT-1)*SCREENWIDTH + i] = 0x0; } // scales the screen size before blitting it if (multiply == 2) { unsigned int *olineptrs[2]; unsigned int *ilineptr; int x, y, i; unsigned int twoopixels; unsigned int twomoreopixels; unsigned int fouripixels; ilineptr = (unsigned int *) (screens[0]); for (i=0 ; i<2 ; i++) olineptrs[i] = (unsigned int *) &image->data[i*X_width]; y = SCREENHEIGHT; while (y--) { x = SCREENWIDTH; do { fouripixels = *ilineptr++; twoopixels = (fouripixels & 0xff000000) | ((fouripixels>>8) & 0xffff00) | ((fouripixels>>16) & 0xff); twomoreopixels = ((fouripixels<<16) & 0xff000000) | ((fouripixels<<8) & 0xffff00) | (fouripixels & 0xff); #ifdef __BIG_ENDIAN__ *olineptrs[0]++ = twoopixels; *olineptrs[1]++ = twoopixels; *olineptrs[0]++ = twomoreopixels; *olineptrs[1]++ = twomoreopixels; #else *olineptrs[0]++ = twomoreopixels; *olineptrs[1]++ = twomoreopixels; *olineptrs[0]++ = twoopixels; *olineptrs[1]++ = twoopixels; #endif } while (x-=4); olineptrs[0] += X_width/4; olineptrs[1] += X_width/4; } } else if (multiply == 3) { unsigned int *olineptrs[3]; unsigned int *ilineptr; int x, y, i; unsigned int fouropixels[3]; unsigned int fouripixels; ilineptr = (unsigned int *) (screens[0]); for (i=0 ; i<3 ; i++) olineptrs[i] = (unsigned int *) &image->data[i*X_width]; y = SCREENHEIGHT; while (y--) { x = SCREENWIDTH; do { fouripixels = *ilineptr++; fouropixels[0] = (fouripixels & 0xff000000) | ((fouripixels>>8) & 0xff0000) | ((fouripixels>>16) & 0xffff); fouropixels[1] = ((fouripixels<<8) & 0xff000000) | (fouripixels & 0xffff00) | ((fouripixels>>8) & 0xff); fouropixels[2] = ((fouripixels<<16) & 0xffff0000) | ((fouripixels<<8) & 0xff00) | (fouripixels & 0xff); #ifdef __BIG_ENDIAN__ *olineptrs[0]++ = fouropixels[0]; *olineptrs[1]++ = fouropixels[0]; *olineptrs[2]++ = fouropixels[0]; *olineptrs[0]++ = fouropixels[1]; *olineptrs[1]++ = fouropixels[1]; *olineptrs[2]++ = fouropixels[1]; *olineptrs[0]++ = fouropixels[2]; *olineptrs[1]++ = fouropixels[2]; *olineptrs[2]++ = fouropixels[2]; #else *olineptrs[0]++ = fouropixels[2]; *olineptrs[1]++ = fouropixels[2]; *olineptrs[2]++ = fouropixels[2]; *olineptrs[0]++ = fouropixels[1]; *olineptrs[1]++ = fouropixels[1]; *olineptrs[2]++ = fouropixels[1]; *olineptrs[0]++ = fouropixels[0]; *olineptrs[1]++ = fouropixels[0]; *olineptrs[2]++ = fouropixels[0]; #endif } while (x-=4); olineptrs[0] += 2*X_width/4; olineptrs[1] += 2*X_width/4; olineptrs[2] += 2*X_width/4; } } else if (multiply == 4) { // Broken. Gotta fix this some day. void Expand4(unsigned *, double *); Expand4 ((unsigned *)(screens[0]), (double *) (image->data)); } if (doShm) { if (!XShmPutImage( X_display, X_mainWindow, X_gc, image, 0, 0, 0, 0, X_width, X_height, True )) I_Error("XShmPutImage() failed\n"); // wait for it to finish and processes all input events shmFinished = false; do { I_GetEvent(); } while (!shmFinished); } else { // draw the image XPutImage( X_display, X_mainWindow, X_gc, image, 0, 0, 0, 0, X_width, X_height ); // sync up with server XSync(X_display, False); } } // // I_ReadScreen // void I_ReadScreen (byte* scr) { memcpy (scr, screens[0], SCREENWIDTH*SCREENHEIGHT); } // // Palette stuff. // static XColor colors[256]; void UploadNewPalette(Colormap cmap, byte *palette) { register int i; register int c; static boolean firstcall = true; #ifdef __cplusplus if (X_visualinfo.c_class == PseudoColor && X_visualinfo.depth == 8) #else if (X_visualinfo.class == PseudoColor && X_visualinfo.depth == 8) #endif { // initialize the colormap if (firstcall) { firstcall = false; for (i=0 ; i<256 ; i++) { colors[i].pixel = i; colors[i].flags = DoRed|DoGreen|DoBlue; } } // set the X colormap entries for (i=0 ; i<256 ; i++) { c = gammatable[usegamma][*palette++]; colors[i].red = (c<<8) + c; c = gammatable[usegamma][*palette++]; colors[i].green = (c<<8) + c; c = gammatable[usegamma][*palette++]; colors[i].blue = (c<<8) + c; } // store the colors to the current colormap XStoreColors(X_display, cmap, colors, 256); } } // // I_SetPalette // void I_SetPalette (byte* palette) { UploadNewPalette(X_cmap, palette); } // // This function is probably redundant, // if XShmDetach works properly. // ddt never detached the XShm memory, // thus there might have been stale // handles accumulating. // void grabsharedmemory(int size) { int key = ('d'<<24) | ('o'<<16) | ('o'<<8) | 'm'; struct shmid_ds shminfo; int minsize = 320*200; int id; int rc; // UNUSED int done=0; int pollution=5; // try to use what was here before do { id = shmget((key_t) key, minsize, 0777); // just get the id if (id != -1) { rc=shmctl(id, IPC_STAT, &shminfo); // get stats on it if (!rc) { if (shminfo.shm_nattch) { fprintf(stderr, "User %d appears to be running " "DOOM. Is that wise?\n", shminfo.shm_cpid); key++; } else { if (getuid() == shminfo.shm_perm.cuid) { rc = shmctl(id, IPC_RMID, 0); if (!rc) fprintf(stderr, "Was able to kill my old shared memory\n"); else I_Error("Was NOT able to kill my old shared memory"); id = shmget((key_t)key, size, IPC_CREAT|0777); if (id==-1) I_Error("Could not get shared memory"); rc=shmctl(id, IPC_STAT, &shminfo); break; } if (size >= shminfo.shm_segsz) { fprintf(stderr, "will use %d's stale shared memory\n", shminfo.shm_cpid); break; } else { fprintf(stderr, "warning: can't use stale " "shared memory belonging to id %d, " "key=0x%x\n", shminfo.shm_cpid, key); key++; } } } else { I_Error("could not get stats on key=%d", key); } } else { id = shmget((key_t)key, size, IPC_CREAT|0777); if (id==-1) { extern int errno; fprintf(stderr, "errno=%d\n", errno); I_Error("Could not get any shared memory"); } break; } } while (--pollution); if (!pollution) { I_Error("Sorry, system too polluted with stale " "shared memory segments.\n"); } X_shminfo.shmid = id; // attach to the shared memory segment image->data = X_shminfo.shmaddr = shmat(id, 0, 0); fprintf(stderr, "shared memory id=%d, addr=0x%x\n", id, (int) (image->data)); } void I_InitGraphics(void) { char* displayname; char* d; int n; int pnum; int x=0; int y=0; // warning: char format, different type arg char xsign=' '; char ysign=' '; int oktodraw; unsigned long attribmask; XSetWindowAttributes attribs; XGCValues xgcvalues; int valuemask; static int firsttime=1; if (!firsttime) return; firsttime = 0; signal(SIGINT, (void (*)(int)) I_Quit); if (M_CheckParm("-2")) multiply = 2; if (M_CheckParm("-3")) multiply = 3; if (M_CheckParm("-4")) multiply = 4; X_width = SCREENWIDTH * multiply; X_height = SCREENHEIGHT * multiply; // check for command-line display name if ( (pnum=M_CheckParm("-disp")) ) // suggest parentheses around assignment displayname = myargv[pnum+1]; else displayname = 0; // check if the user wants to grab the mouse (quite unnice) grabMouse = !!M_CheckParm("-grabmouse"); // check for command-line geometry if ( (pnum=M_CheckParm("-geom")) ) // suggest parentheses around assignment { // warning: char format, different type arg 3,5 n = sscanf(myargv[pnum+1], "%c%d%c%d", &xsign, &x, &ysign, &y); if (n==2) x = y = 0; else if (n==6) { if (xsign == '-') x = -x; if (ysign == '-') y = -y; } else I_Error("bad -geom parameter"); } // open the display X_display = XOpenDisplay(displayname); if (!X_display) { if (displayname) I_Error("Could not open display [%s]", displayname); else I_Error("Could not open display (DISPLAY=[%s])", getenv("DISPLAY")); } // use the default visual X_screen = DefaultScreen(X_display); if (!XMatchVisualInfo(X_display, X_screen, 8, PseudoColor, &X_visualinfo)) I_Error("xdoom currently only supports 256-color PseudoColor screens"); X_visual = X_visualinfo.visual; // check for the MITSHM extension doShm = XShmQueryExtension(X_display); // even if it's available, make sure it's a local connection if (doShm) { if (!displayname) displayname = (char *) getenv("DISPLAY"); if (displayname) { d = displayname; while (*d && (*d != ':')) d++; if (*d) *d = 0; if (!(!strcasecmp(displayname, "unix") || !*displayname)) doShm = false; } } fprintf(stderr, "Using MITSHM extension\n"); // create the colormap X_cmap = XCreateColormap(X_display, RootWindow(X_display, X_screen), X_visual, AllocAll); // setup attributes for main window attribmask = CWEventMask | CWColormap | CWBorderPixel; attribs.event_mask = KeyPressMask | KeyReleaseMask // | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | ExposureMask; attribs.colormap = X_cmap; attribs.border_pixel = 0; // create the main window X_mainWindow = XCreateWindow( X_display, RootWindow(X_display, X_screen), x, y, X_width, X_height, 0, // borderwidth 8, // depth InputOutput, X_visual, attribmask, &attribs ); XDefineCursor(X_display, X_mainWindow, createnullcursor( X_display, X_mainWindow ) ); // create the GC valuemask = GCGraphicsExposures; xgcvalues.graphics_exposures = False; X_gc = XCreateGC( X_display, X_mainWindow, valuemask, &xgcvalues ); // map the window XMapWindow(X_display, X_mainWindow); // wait until it is OK to draw oktodraw = 0; while (!oktodraw) { XNextEvent(X_display, &X_event); if (X_event.type == Expose && !X_event.xexpose.count) { oktodraw = 1; } } // grabs the pointer so it is restricted to this window if (grabMouse) XGrabPointer(X_display, X_mainWindow, True, ButtonPressMask|ButtonReleaseMask|PointerMotionMask, GrabModeAsync, GrabModeAsync, X_mainWindow, None, CurrentTime); if (doShm) { X_shmeventtype = XShmGetEventBase(X_display) + ShmCompletion; // create the image image = XShmCreateImage( X_display, X_visual, 8, ZPixmap, 0, &X_shminfo, X_width, X_height ); grabsharedmemory(image->bytes_per_line * image->height); // UNUSED // create the shared memory segment // X_shminfo.shmid = shmget (IPC_PRIVATE, // image->bytes_per_line * image->height, IPC_CREAT | 0777); // if (X_shminfo.shmid < 0) // { // perror(""); // I_Error("shmget() failed in InitGraphics()"); // } // fprintf(stderr, "shared memory id=%d\n", X_shminfo.shmid); // attach to the shared memory segment // image->data = X_shminfo.shmaddr = shmat(X_shminfo.shmid, 0, 0); if (!image->data) { perror(""); I_Error("shmat() failed in InitGraphics()"); } // get the X server to attach to it if (!XShmAttach(X_display, &X_shminfo)) I_Error("XShmAttach() failed in InitGraphics()"); } else { image = XCreateImage( X_display, X_visual, 8, ZPixmap, 0, (char*)malloc(X_width * X_height), X_width, X_height, 8, X_width ); } if (multiply == 1) screens[0] = (unsigned char *) (image->data); else screens[0] = (unsigned char *) malloc (SCREENWIDTH * SCREENHEIGHT); } unsigned exptable[256]; void InitExpand (void) { int i; for (i=0 ; i<256 ; i++) exptable[i] = i | (i<<8) | (i<<16) | (i<<24); } double exptable2[256*256]; void InitExpand2 (void) { int i; int j; // UNUSED unsigned iexp, jexp; double* exp; union { double d; unsigned u[2]; } pixel; printf ("building exptable2...\n"); exp = exptable2; for (i=0 ; i<256 ; i++) { pixel.u[0] = i | (i<<8) | (i<<16) | (i<<24); for (j=0 ; j<256 ; j++) { pixel.u[1] = j | (j<<8) | (j<<16) | (j<<24); *exp++ = pixel.d; } } printf ("done.\n"); } int inited; void Expand4 ( unsigned* lineptr, double* xline ) { double dpixel; unsigned x; unsigned y; unsigned fourpixels; unsigned step; double* exp; exp = exptable2; if (!inited) { inited = 1; InitExpand2 (); } step = 3*SCREENWIDTH/2; y = SCREENHEIGHT-1; do { x = SCREENWIDTH; do { fourpixels = lineptr[0]; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff0000)>>13) ); xline[0] = dpixel; xline[160] = dpixel; xline[320] = dpixel; xline[480] = dpixel; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff)<<3 ) ); xline[1] = dpixel; xline[161] = dpixel; xline[321] = dpixel; xline[481] = dpixel; fourpixels = lineptr[1]; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff0000)>>13) ); xline[2] = dpixel; xline[162] = dpixel; xline[322] = dpixel; xline[482] = dpixel; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff)<<3 ) ); xline[3] = dpixel; xline[163] = dpixel; xline[323] = dpixel; xline[483] = dpixel; fourpixels = lineptr[2]; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff0000)>>13) ); xline[4] = dpixel; xline[164] = dpixel; xline[324] = dpixel; xline[484] = dpixel; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff)<<3 ) ); xline[5] = dpixel; xline[165] = dpixel; xline[325] = dpixel; xline[485] = dpixel; fourpixels = lineptr[3]; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff0000)>>13) ); xline[6] = dpixel; xline[166] = dpixel; xline[326] = dpixel; xline[486] = dpixel; dpixel = *(double *)( (int)exp + ( (fourpixels&0xffff)<<3 ) ); xline[7] = dpixel; xline[167] = dpixel; xline[327] = dpixel; xline[487] = dpixel; lineptr+=4; xline+=8; } while (x-=16); xline += step; } while (y--); }
21.65176
79
0.600018
[ "geometry" ]
9b3851cfa192416c33abb55e817957f169d8a071
1,634
h
C
mash/example/window_type_launcher/window_type_launcher.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
mash/example/window_type_launcher/window_type_launcher.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
mash/example/window_type_launcher/window_type_launcher.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MASH_EXAMPLE_WINDOW_TYPE_LAUNCHER_WINDOW_TYPE_LAUNCHER_H_ #define MASH_EXAMPLE_WINDOW_TYPE_LAUNCHER_WINDOW_TYPE_LAUNCHER_H_ #include <memory> #include "base/macros.h" #include "mash/public/interfaces/launchable.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" namespace views { class AuraInit; class Widget; } class WindowTypeLauncher : public shell::ShellClient, public mash::mojom::Launchable, public shell::InterfaceFactory<mash::mojom::Launchable> { public: WindowTypeLauncher(); ~WindowTypeLauncher() override; void RemoveWindow(views::Widget* window); private: // shell::ShellClient: void Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) override; bool AcceptConnection(shell::Connection* connection) override; // mash::mojom::Launchable: void Launch(uint32_t what, mash::mojom::LaunchMode how) override; // shell::InterfaceFactory<mash::mojom::Launchable>: void Create(shell::Connection* connection, mash::mojom::LaunchableRequest request) override; shell::Connector* connector_ = nullptr; mojo::BindingSet<mash::mojom::Launchable> bindings_; std::vector<views::Widget*> windows_; std::unique_ptr<views::AuraInit> aura_init_; DISALLOW_COPY_AND_ASSIGN(WindowTypeLauncher); }; #endif // MASH_EXAMPLE_WINDOW_TYPE_LAUNCHER_WINDOW_TYPE_LAUNCHER_H_
30.259259
73
0.752142
[ "vector" ]
9b43a003a3bdedb0099f98ba695322a2b2e48968
10,411
h
C
include/muu/emplacement_array.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
8
2020-10-09T06:50:26.000Z
2022-02-07T21:08:34.000Z
include/muu/emplacement_array.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
null
null
null
include/muu/emplacement_array.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
null
null
null
// This file is a part of muu and is subject to the the terms of the MIT license. // Copyright (c) Mark Gillard <mark.gillard@outlook.com.au> // See https://github.com/marzer/muu/blob/master/LICENSE for the full license text. // SPDX-License-Identifier: MIT #pragma once /// \file /// \brief Contains the definition of muu::emplacement_array. #include "generic_allocator.h" #include "impl/core_utils.h" #include "impl/std_new.h" #include "impl/std_launder.h" #if !MUU_HAS_EXCEPTIONS #include "impl/std_exception.h" // std::terminate() #endif #include "impl/header_start.h" namespace muu { /// \brief Simple std::vector-like array type for immovable or move-only types. /// /// \tparam T Element type stored in the array. template <typename T> class emplacement_array { static_assert(!std::is_reference_v<T>, "emplacement_array element type cannot be a reference."); static_assert(!is_cv<T>, "emplacement_array element type cannot be const- or volatile-qualified"); static_assert(std::is_nothrow_destructible_v<T>, "emplacement_array element type must be nothrow-destructible."); private: /// \cond generic_allocator* allocator_; size_t count_ = {}, capacity_; std::byte* storage_ = nullptr; MUU_PURE_INLINE_GETTER MUU_ATTR(returns_nonnull) T* ptr(size_t index) noexcept { return MUU_LAUNDER(reinterpret_cast<T*>(storage_ + index * sizeof(T))); } MUU_PURE_INLINE_GETTER MUU_ATTR(returns_nonnull) const T* ptr(size_t index) const noexcept { return MUU_LAUNDER(reinterpret_cast<const T*>(storage_ + index * sizeof(T))); } void destroy_all_elements() noexcept(std::is_nothrow_destructible_v<T>) { if constexpr (std::is_trivially_destructible_v<T>) count_ = {}; else { for (size_t i = count_; i-- > 0u;) { ptr(i)->~T(); if constexpr (!std::is_nothrow_destructible_v<T>) count_--; } if constexpr (std::is_nothrow_destructible_v<T>) count_ = {}; } } void release() noexcept(std::is_nothrow_destructible_v<T>) { if (storage_) { destroy_all_elements(); impl::generic_free(allocator_, storage_); storage_ = nullptr; } } /// \endcond public: /// \brief The array's value type. using value_type = T; /// \brief Unsigned index type. using size_type = size_t; /// \brief Signed index type. using difference_type = ptrdiff_t; /// \brief Reference to the array's value type. using reference = value_type&; /// \brief Const reference to the array's value type. using const_reference = const value_type&; /// \brief Pointer to the array's value type. using pointer = value_type*; /// \brief Const pointer to the array's value type. using const_pointer = const value_type*; /// \brief Iterator to a member of the array. using iterator = pointer; /// \brief Const iterator to a member of the array. using const_iterator = const_pointer; /// \brief Constructor. /// /// \param capacity The maximum number of elements the array needs to be able to store. /// \param allocator The #muu::generic_allocator used for allocations. Set to `nullptr` to use the default global allocator. MUU_NODISCARD_CTOR explicit emplacement_array(size_t capacity = 0, generic_allocator* allocator = nullptr) : allocator_{ allocator }, capacity_{ capacity } { if (capacity_) { storage_ = static_cast<std::byte*>(impl::generic_alloc(allocator_, sizeof(T) * capacity_, alignof(T))); MUU_ASSERT(storage_ && "allocate() failed!"); #if !MUU_HAS_EXCEPTIONS { if (!storage_) std::terminate(); } #endif } } /// \brief Move constructor. MUU_NODISCARD_CTOR emplacement_array(emplacement_array&& other) noexcept : allocator_{ other.allocator_ }, count_{ other.count_ }, capacity_{ other.capacity_ }, storage_{ other.storage_ } { other.count_ = 0; other.capacity_ = 0; other.storage_ = nullptr; } /// \brief Move-assignment operator. emplacement_array& operator=(emplacement_array&& rhs) noexcept { release(); allocator_ = rhs.allocator_; count_ = rhs.count_; capacity_ = rhs.capacity_; storage_ = rhs.storage_; rhs.count_ = 0; rhs.capacity_ = 0; rhs.storage_ = nullptr; return *this; } /// \brief Destructor. ~emplacement_array() noexcept { release(); } MUU_DELETE_COPY(emplacement_array); /// \brief Constructs one new element at the end of the array. /// /// \tparam Args Constructor argument types. /// \param args Arguments to pass to the element's constructor. /// /// \return A reference to the newly-constructed element. template <typename... Args> reference emplace_back(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args&&...>) { MUU_ASSERT(count_ < capacity_ && "The emplacement_array is at capacity"); if constexpr (std::is_nothrow_constructible_v<T, Args&&...>) { return *(::new (static_cast<void*>(storage_ + (sizeof(T) * count_++))) T{ static_cast<Args&&>(args)... }); } else { auto& newVal = *(::new (static_cast<void*>(storage_ + (sizeof(T) * count_))) T{ static_cast<Args&&>(args)... }); count_++; return newVal; } } /// \brief Constructs one new element in the array using a construction functor for the emplacement. /// /// \tparam EmplacementFunc A callable type with the signature `T*(void*)`. /// \param func A callable responsible for performing the placement-new construction. /// /// \return A reference to the newly-constructed element. template <typename EmplacementFunc, typename... ARGS> reference emplace_back_with(EmplacementFunc&& func) noexcept( std::is_nothrow_invocable_r_v<T&, EmplacementFunc&&, void*>) { MUU_ASSERT(count_ < capacity_ && "The emplacement_array is at capacity"); if constexpr (std::is_nothrow_invocable_r_v<T&, EmplacementFunc&&, void*>) { return *static_cast<EmplacementFunc&&>(func)(static_cast<void*>(storage_ + (sizeof(T) * count_++))); } else { auto& newVal = *static_cast<EmplacementFunc&&>(func)(static_cast<void*>(storage_ + (sizeof(T) * count_))); count_++; return newVal; } } /// \brief Returns a reference to the element at the selected index. MUU_PURE_INLINE_GETTER reference operator[](size_t index) noexcept { return *ptr(index); } /// \brief Returns a const reference to the element at the selected index. MUU_PURE_INLINE_GETTER const_reference operator[](size_t index) const noexcept { return *ptr(index); } /// \brief The number of elements in the array. MUU_PURE_INLINE_GETTER size_type size() const noexcept { return count_; } /// \brief The maximum number of elements that can be stored in the array. MUU_PURE_INLINE_GETTER size_type capacity() const noexcept { return capacity_; } /// \brief Returns true if the array is empty. MUU_PURE_INLINE_GETTER bool empty() const noexcept { return count_ == 0u; } /// \brief Returns the first element in the array. MUU_PURE_INLINE_GETTER reference front() noexcept { return (*this)[0]; } /// \brief Returns the first element in the array. MUU_PURE_INLINE_GETTER const_reference front() const noexcept { return (*this)[0]; } /// \brief Returns the last element in the array. MUU_PURE_INLINE_GETTER reference back() noexcept { return (*this)[count_ - 1_sz]; } /// \brief Returns the last element in the array. MUU_PURE_INLINE_GETTER const_reference back() const noexcept { return (*this)[count_ - 1_sz]; } /// \name Iterators /// @{ /// \brief Returns an iterator to the first element in the array. MUU_PURE_INLINE_GETTER iterator begin() noexcept { return ptr(0); } /// \brief Returns an iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER iterator end() noexcept { return ptr(count_); } /// \brief Returns a const_iterator to the first element in the array. MUU_PURE_INLINE_GETTER const_iterator begin() const noexcept { return ptr(0); } /// \brief Returns a const_iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER const_iterator end() const noexcept { return ptr(count_); } /// \brief Returns a const_iterator to the first element in the array. MUU_PURE_INLINE_GETTER const_iterator cbegin() const noexcept { return ptr(0); } /// \brief Returns a const_iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER const_iterator cend() const noexcept { return ptr(count_); } /// @} /// \name Iterators (ADL) /// @{ /// \brief Returns an iterator to the first element in the array. MUU_PURE_INLINE_GETTER friend iterator begin(emplacement_array& arr) noexcept { return arr.begin(); } /// \brief Returns an iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER friend iterator end(emplacement_array& arr) noexcept { return arr.end(); } /// \brief Returns a const_iterator to the first element in the array. MUU_PURE_INLINE_GETTER friend const_iterator begin(const emplacement_array& arr) noexcept { return arr.begin(); } /// \brief Returns a const_iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER friend const_iterator end(const emplacement_array& arr) noexcept { return arr.end(); } /// \brief Returns a const_iterator to the first element in the array. MUU_PURE_INLINE_GETTER friend const_iterator cbegin(const emplacement_array& arr) noexcept { return arr.begin(); } /// \brief Returns a const_iterator to one-past-the-last element in the array. MUU_PURE_INLINE_GETTER friend const_iterator cend(const emplacement_array& arr) noexcept { return arr.end(); } /// @} /// \brief Returns a pointer to the first element in the array. MUU_PURE_INLINE_GETTER pointer data() noexcept { return ptr(0); } /// \brief Returns a const pointer to the first element in the array. MUU_PURE_INLINE_GETTER const_pointer data() const noexcept { return ptr(0); } /// \brief Clears the array, destroying all currently allocated elements and resetting size to zero. void clear() noexcept(std::is_nothrow_destructible_v<T>) { destroy_all_elements(); } }; } #include "impl/header_end.h"
26.224181
127
0.689559
[ "vector" ]