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
318f5e5a69982df16691b2b375129ccb42de6bf7
17,045
c
C
MdeModulePkg/Universal/HiiDatabaseDxe/ImageEx.c
sscargal/ipmctl
48e4cdc8682e9efafc838bda66d4af282c29dc11
[ "BSD-3-Clause" ]
151
2018-06-01T20:14:34.000Z
2022-03-13T08:34:07.000Z
MdeModulePkg/Universal/HiiDatabaseDxe/ImageEx.c
sscargal/ipmctl
48e4cdc8682e9efafc838bda66d4af282c29dc11
[ "BSD-3-Clause" ]
179
2018-06-21T18:07:54.000Z
2022-03-30T16:06:39.000Z
MdeModulePkg/Universal/HiiDatabaseDxe/ImageEx.c
sscargal/ipmctl
48e4cdc8682e9efafc838bda66d4af282c29dc11
[ "BSD-3-Clause" ]
58
2018-06-07T21:59:15.000Z
2022-03-16T23:26:38.000Z
/** @file Implementation for EFI_HII_IMAGE_EX_PROTOCOL. Copyright (c) 2016, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "HiiDatabase.h" /** The prototype of this extension function is the same with EFI_HII_IMAGE_PROTOCOL.NewImage(). This protocol invokes EFI_HII_IMAGE_PROTOCOL.NewImage() implicitly. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param PackageList Handle of the package list where this image will be added. @param ImageId On return, contains the new image id, which is unique within PackageList. @param Image Points to the image. @retval EFI_SUCCESS The new image was added successfully. @retval EFI_NOT_FOUND The PackageList could not be found. @retval EFI_OUT_OF_RESOURCES Could not add the image due to lack of resources. @retval EFI_INVALID_PARAMETER Image is NULL or ImageId is NULL. **/ EFI_STATUS EFIAPI HiiNewImageEx ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_HANDLE PackageList, OUT EFI_IMAGE_ID *ImageId, IN CONST EFI_IMAGE_INPUT *Image ) { HII_DATABASE_PRIVATE_DATA *Private; Private = HII_IMAGE_EX_DATABASE_PRIVATE_DATA_FROM_THIS (This); return HiiNewImage (&Private->HiiImage, PackageList, ImageId, Image); } /** Return the information about the image, associated with the package list. The prototype of this extension function is the same with EFI_HII_IMAGE_PROTOCOL.GetImage(). This function is similar to EFI_HII_IMAGE_PROTOCOL.GetImage().The difference is that this function will locate all EFI_HII_IMAGE_DECODER_PROTOCOL instances installed in the system if the decoder of the certain image type is not supported by the EFI_HII_IMAGE_EX_PROTOCOL. The function will attempt to decode the image to the EFI_IMAGE_INPUT using the first EFI_HII_IMAGE_DECODER_PROTOCOL instance that supports the requested image type. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param PackageList The package list in the HII database to search for the specified image. @param ImageId The image's id, which is unique within PackageList. @param Image Points to the image. @retval EFI_SUCCESS The new image was returned successfully. @retval EFI_NOT_FOUND The image specified by ImageId is not available. The specified PackageList is not in the Database. @retval EFI_INVALID_PARAMETER Image was NULL or ImageId was 0. @retval EFI_OUT_OF_RESOURCES The bitmap could not be retrieved because there was not enough memory. **/ EFI_STATUS EFIAPI HiiGetImageEx ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_HANDLE PackageList, IN EFI_IMAGE_ID ImageId, OUT EFI_IMAGE_INPUT *Image ) { HII_DATABASE_PRIVATE_DATA *Private; Private = HII_IMAGE_EX_DATABASE_PRIVATE_DATA_FROM_THIS (This); return IGetImage (&Private->DatabaseList, PackageList, ImageId, Image, FALSE); } /** Change the information about the image. Same with EFI_HII_IMAGE_PROTOCOL.SetImage(),this protocol invokes EFI_HII_IMAGE_PROTOCOL.SetImage()implicitly. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param PackageList The package list containing the images. @param ImageId The image's id, which is unique within PackageList. @param Image Points to the image. @retval EFI_SUCCESS The new image was successfully updated. @retval EFI_NOT_FOUND The image specified by ImageId is not in the database. The specified PackageList is not in the database. @retval EFI_INVALID_PARAMETER The Image was NULL, the ImageId was 0 or the Image->Bitmap was NULL. **/ EFI_STATUS EFIAPI HiiSetImageEx ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_HANDLE PackageList, IN EFI_IMAGE_ID ImageId, IN CONST EFI_IMAGE_INPUT *Image ) { HII_DATABASE_PRIVATE_DATA *Private; Private = HII_IMAGE_EX_DATABASE_PRIVATE_DATA_FROM_THIS (This); return HiiSetImage (&Private->HiiImage, PackageList, ImageId, Image); } /** Renders an image to a bitmap or to the display. The prototype of this extension function is the same with EFI_HII_IMAGE_PROTOCOL.DrawImage(). This protocol invokes EFI_HII_IMAGE_PROTOCOL.DrawImage() implicitly. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param Flags Describes how the image is to be drawn. @param Image Points to the image to be displayed. @param Blt If this points to a non-NULL on entry, this points to the image, which is Width pixels wide and Height pixels high. The image will be drawn onto this image and EFI_HII_DRAW_FLAG_CLIP is implied. If this points to a NULL on entry, then a buffer will be allocated to hold the generated image and the pointer updated on exit. It is the caller's responsibility to free this buffer. @param BltX Specifies the offset from the left and top edge of the output image of the first pixel in the image. @param BltY Specifies the offset from the left and top edge of the output image of the first pixel in the image. @retval EFI_SUCCESS The image was successfully drawn. @retval EFI_OUT_OF_RESOURCES Unable to allocate an output buffer for Blt. @retval EFI_INVALID_PARAMETER The Image or Blt was NULL. **/ EFI_STATUS EFIAPI HiiDrawImageEx ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_DRAW_FLAGS Flags, IN CONST EFI_IMAGE_INPUT *Image, IN OUT EFI_IMAGE_OUTPUT **Blt, IN UINTN BltX, IN UINTN BltY ) { HII_DATABASE_PRIVATE_DATA *Private; Private = HII_IMAGE_EX_DATABASE_PRIVATE_DATA_FROM_THIS (This); return HiiDrawImage (&Private->HiiImage, Flags, Image, Blt, BltX, BltY); } /** Renders an image to a bitmap or the screen containing the contents of the specified image. This function is similar to EFI_HII_IMAGE_PROTOCOL.DrawImageId(). The difference is that this function will locate all EFI_HII_IMAGE_DECODER_PROTOCOL instances installed in the system if the decoder of the certain image type is not supported by the EFI_HII_IMAGE_EX_PROTOCOL. The function will attempt to decode the image to the EFI_IMAGE_INPUT using the first EFI_HII_IMAGE_DECODER_PROTOCOL instance that supports the requested image type. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param Flags Describes how the image is to be drawn. @param PackageList The package list in the HII database to search for the specified image. @param ImageId The image's id, which is unique within PackageList. @param Blt If this points to a non-NULL on entry, this points to the image, which is Width pixels wide and Height pixels high. The image will be drawn onto this image and EFI_HII_DRAW_FLAG_CLIP is implied. If this points to a NULL on entry, then a buffer will be allocated to hold the generated image and the pointer updated on exit. It is the caller's responsibility to free this buffer. @param BltX Specifies the offset from the left and top edge of the output image of the first pixel in the image. @param BltY Specifies the offset from the left and top edge of the output image of the first pixel in the image. @retval EFI_SUCCESS The image was successfully drawn. @retval EFI_OUT_OF_RESOURCES Unable to allocate an output buffer for Blt. @retval EFI_INVALID_PARAMETER The Blt was NULL or ImageId was 0. @retval EFI_NOT_FOUND The image specified by ImageId is not in the database. The specified PackageList is not in the database. **/ EFI_STATUS EFIAPI HiiDrawImageIdEx ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_DRAW_FLAGS Flags, IN EFI_HII_HANDLE PackageList, IN EFI_IMAGE_ID ImageId, IN OUT EFI_IMAGE_OUTPUT **Blt, IN UINTN BltX, IN UINTN BltY ) { EFI_STATUS Status; EFI_IMAGE_INPUT Image; // // Check input parameter. // if (This == NULL || Blt == NULL) { return EFI_INVALID_PARAMETER; } // // Get the specified Image. // Status = HiiGetImageEx (This, PackageList, ImageId, &Image); if (EFI_ERROR (Status)) { return Status; } // // Draw this image. // Status = HiiDrawImageEx (This, Flags, &Image, Blt, BltX, BltY); if (Image.Bitmap != NULL) { FreePool (Image.Bitmap); } return Status; } /** Return the first HII image decoder instance which supports the DecoderName. @param BlockType The image block type. @retval Pointer to the HII image decoder instance. **/ EFI_HII_IMAGE_DECODER_PROTOCOL * LocateHiiImageDecoder ( UINT8 BlockType ) { EFI_STATUS Status; EFI_HII_IMAGE_DECODER_PROTOCOL *Decoder; EFI_HANDLE *Handles; UINTN HandleNum; UINTN Index; EFI_GUID *DecoderNames; UINT16 NumberOfDecoderName; UINT16 DecoderNameIndex; EFI_GUID *DecoderName; switch (BlockType) { case EFI_HII_IIBT_IMAGE_JPEG: DecoderName = &gEfiHiiImageDecoderNameJpegGuid; break; case EFI_HII_IIBT_IMAGE_PNG: DecoderName = &gEfiHiiImageDecoderNamePngGuid; break; default: ASSERT (FALSE); return NULL; } Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiHiiImageDecoderProtocolGuid, NULL, &HandleNum, &Handles); if (EFI_ERROR (Status)) { return NULL; } for (Index = 0; Index < HandleNum; Index++) { Status = gBS->HandleProtocol (Handles[Index], &gEfiHiiImageDecoderProtocolGuid, (VOID **) &Decoder); if (EFI_ERROR (Status)) { continue; } Status = Decoder->GetImageDecoderName (Decoder, &DecoderNames, &NumberOfDecoderName); if (EFI_ERROR (Status)) { continue; } for (DecoderNameIndex = 0; DecoderNameIndex < NumberOfDecoderName; DecoderNameIndex++) { if (CompareGuid (DecoderName, &DecoderNames[DecoderNameIndex])) { return Decoder; } } } return NULL; } /** This function returns the image information to EFI_IMAGE_OUTPUT. Only the width and height are returned to the EFI_IMAGE_OUTPUT instead of decoding the image to the buffer. This function is used to get the geometry of the image. This function will try to locate all of the EFI_HII_IMAGE_DECODER_PROTOCOL installed on the system if the decoder of image type is not supported by the EFI_HII_IMAGE_EX_PROTOCOL. @param This A pointer to the EFI_HII_IMAGE_EX_PROTOCOL instance. @param PackageList Handle of the package list where this image will be searched. @param ImageId The image's id, which is unique within PackageList. @param Image Points to the image. @retval EFI_SUCCESS The new image was returned successfully. @retval EFI_NOT_FOUND The image specified by ImageId is not in the database. The specified PackageList is not in the database. @retval EFI_BUFFER_TOO_SMALL The buffer specified by ImageSize is too small to hold the image. @retval EFI_INVALID_PARAMETER The Image was NULL or the ImageId was 0. @retval EFI_OUT_OF_RESOURCES The bitmap could not be retrieved because there was not enough memory. **/ EFI_STATUS EFIAPI HiiGetImageInfo ( IN CONST EFI_HII_IMAGE_EX_PROTOCOL *This, IN EFI_HII_HANDLE PackageList, IN EFI_IMAGE_ID ImageId, OUT EFI_IMAGE_OUTPUT *Image ) { EFI_STATUS Status; HII_DATABASE_PRIVATE_DATA *Private; HII_DATABASE_PACKAGE_LIST_INSTANCE *PackageListNode; HII_IMAGE_PACKAGE_INSTANCE *ImagePackage; EFI_HII_IMAGE_BLOCK *CurrentImageBlock; EFI_HII_IMAGE_DECODER_PROTOCOL *Decoder; EFI_HII_IMAGE_DECODER_IMAGE_INFO_HEADER *ImageInfo; if (Image == NULL || ImageId == 0) { return EFI_INVALID_PARAMETER; } Private = HII_IMAGE_EX_DATABASE_PRIVATE_DATA_FROM_THIS (This); PackageListNode = LocatePackageList (&Private->DatabaseList, PackageList); if (PackageListNode == NULL) { return EFI_NOT_FOUND; } ImagePackage = PackageListNode->ImagePkg; if (ImagePackage == NULL) { return EFI_NOT_FOUND; } // // Find the image block specified by ImageId // CurrentImageBlock = GetImageIdOrAddress (ImagePackage->ImageBlock, &ImageId); if (CurrentImageBlock == NULL) { return EFI_NOT_FOUND; } switch (CurrentImageBlock->BlockType) { case EFI_HII_IIBT_IMAGE_JPEG: case EFI_HII_IIBT_IMAGE_PNG: Decoder = LocateHiiImageDecoder (CurrentImageBlock->BlockType); if (Decoder == NULL) { return EFI_UNSUPPORTED; } // // Use the common block code since the definition of two structures is the same. // ASSERT (OFFSET_OF (EFI_HII_IIBT_JPEG_BLOCK, Data) == OFFSET_OF (EFI_HII_IIBT_PNG_BLOCK, Data)); ASSERT (sizeof (((EFI_HII_IIBT_JPEG_BLOCK *) CurrentImageBlock)->Data) == sizeof (((EFI_HII_IIBT_PNG_BLOCK *) CurrentImageBlock)->Data)); ASSERT (OFFSET_OF (EFI_HII_IIBT_JPEG_BLOCK, Size) == OFFSET_OF (EFI_HII_IIBT_PNG_BLOCK, Size)); ASSERT (sizeof (((EFI_HII_IIBT_JPEG_BLOCK *) CurrentImageBlock)->Size) == sizeof (((EFI_HII_IIBT_PNG_BLOCK *) CurrentImageBlock)->Size)); Status = Decoder->GetImageInfo ( Decoder, ((EFI_HII_IIBT_JPEG_BLOCK *) CurrentImageBlock)->Data, ((EFI_HII_IIBT_JPEG_BLOCK *) CurrentImageBlock)->Size, &ImageInfo ); // // Spec requires to use the first capable image decoder instance. // The first image decoder instance may fail to decode the image. // if (!EFI_ERROR (Status)) { Image->Height = ImageInfo->ImageHeight; Image->Width = ImageInfo->ImageWidth; Image->Image.Bitmap = NULL; FreePool (ImageInfo); } return Status; case EFI_HII_IIBT_IMAGE_1BIT_TRANS: case EFI_HII_IIBT_IMAGE_4BIT_TRANS: case EFI_HII_IIBT_IMAGE_8BIT_TRANS: case EFI_HII_IIBT_IMAGE_1BIT: case EFI_HII_IIBT_IMAGE_4BIT: case EFI_HII_IIBT_IMAGE_8BIT: // // Use the common block code since the definition of these structures is the same. // Image->Width = ReadUnaligned16 (&((EFI_HII_IIBT_IMAGE_1BIT_BLOCK *) CurrentImageBlock)->Bitmap.Width); Image->Height = ReadUnaligned16 (&((EFI_HII_IIBT_IMAGE_1BIT_BLOCK *) CurrentImageBlock)->Bitmap.Height); Image->Image.Bitmap = NULL; return EFI_SUCCESS; case EFI_HII_IIBT_IMAGE_24BIT_TRANS: case EFI_HII_IIBT_IMAGE_24BIT: Image->Width = ReadUnaligned16 ((VOID *) &((EFI_HII_IIBT_IMAGE_24BIT_BLOCK *) CurrentImageBlock)->Bitmap.Width); Image->Height = ReadUnaligned16 ((VOID *) &((EFI_HII_IIBT_IMAGE_24BIT_BLOCK *) CurrentImageBlock)->Bitmap.Height); Image->Image.Bitmap = NULL; return EFI_SUCCESS; default: return EFI_NOT_FOUND; } }
39.824766
118
0.649868
[ "geometry" ]
31918c09574b29a158e28dc279a7960728e374a0
2,641
h
C
3rdparty/etl/include/ETCommon.h
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
3rdparty/etl/include/ETCommon.h
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
3rdparty/etl/include/ETCommon.h
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
#ifndef __ET_COMMON_H__ #define __ET_COMMON_H__ /******************************************************************************** EDITABLE TERRAIN LIBRARY v3 for Ogre Copyright (c) 2008 Holger Frydrych <frydrych@oddbeat.de> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ********************************************************************************/ #include "ETArray2D.h" #include <OgreCommon.h> #include <OgreColourValue.h> #include <set> #include <vector> #include <string> namespace ET { typedef Array2D<Ogre::Real> RealArray2D; typedef Array2D<Ogre::ColourValue> ColourArray2D; typedef std::set<unsigned int> VertexList; typedef std::vector<std::string> TextureList; /** Constant for big endian format */ const bool ENDIAN_BIG = false; /** Constant for little endian format */ const bool ENDIAN_LITTLE = true; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG const bool ENDIAN_NATIVE = ENDIAN_BIG; #else const bool ENDIAN_NATIVE = ENDIAN_LITTLE; #endif /** Flags for additional vertex buffer elements */ enum { VO_NORMALS = 0x01, VO_TANGENTS = 0x02, VO_BINORMALS = 0x04, VO_TEXCOORD1 = 0x08, VO_LODMORPH = 0x10 }; const unsigned int VO_DEFAULT = VO_NORMALS|VO_TEXCOORD1|VO_LODMORPH; /** * Direction for connecting neighbouring patches and choosing index buffers. * North is considered to be in negative Z direction. * East is considered to be in positive X direction. */ enum { DIR_NORTH = 0, DIR_EAST = 1, DIR_SOUTH = 2, DIR_WEST = 3 }; /** Opposite directions */ const int OPPOSITE_DIR[4] = { DIR_SOUTH, DIR_WEST, DIR_NORTH, DIR_EAST }; struct Rect { unsigned int x1, y1, x2, y2; Rect(unsigned int ax, unsigned int ay, unsigned int bx, unsigned int by) : x1(ax), y1(ay), x2(bx), y2(by) { } Rect() {} }; } #endif
28.397849
81
0.672473
[ "vector" ]
31933f20ad22066aa813e663e9c96593bab07669
6,315
h
C
AI_Game/Grid.h
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
AI_Game/Grid.h
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
AI_Game/Grid.h
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <GameEngine\DebugRenderer.h> #include "Node.h" class Grid { public: Grid(const Grid& _obj); Grid(); ~Grid(); /** \brief Create the grid (2d matrix of nodes) * \param _gridWorldSize - the width and height of the grid in pixels * \param _nodeDiameter - the diameter of each node The number of nodes is calculated by using the width and height division by the diameter m_numXNodes = (int)ceil((_width / _nodeDiameter)); m_numYNodes = (int)ceil((_height / _nodeDiameter)); * \param _walkable matrix - a 2d vector array of booleans depicting which node is walkable (needs to be the same size as the grid) */ Grid(const glm::vec2& _gridWorldSize, float _nodeDiameter, std::vector<bool>& _walkableMatrix); Grid(const glm::vec2& _gridWorldSize, float _nodeDiameter); /** \brief Create the grid (2d matrix of nodes) * \param _numXNodes - the number of nodes in the x axis * \param _numYNodes - the number of nodes in the Y axis * \param _nodeDiameter - the diameter of each node By passing how many nodes we want in the x and y axis we can manually calculate the size of the grid map in pixels by _width = float(_numXNodes * _nodeDiameter); _height = float(_numYNodes * _nodeDiameter); * \param _walkable matrix - a 2d vector array of booleans depicting which node is walkable (needs to be the same size as the grid) */ Grid(size_t _numXNodes, size_t _numYNodes, float _nodeDiameter, std::vector<bool>& _walkableMatrix); Grid(size_t _numXNodes, size_t _numYNodes, float _nodeDiameter); /** \brief Gets node based on world coordinate * \param _worldPos - the x,y coordinate in world space * the coordinate is to be converted into the indices in the node vector * eg. world coordinate of 0,0 to diameter, diameter (32,32 for example) * will be converted to 0, 0 and 0 + diameter, 0 + diameter to diameter * 2, diameter * 2 (diagonal top-right of index 0, 0) * will be converted to 1, 1 * \return Node* - a pointer to the node at this coordinate */ std::weak_ptr<Node> GetNodeAt(const glm::vec2& _worldPos); /** \brief Gets node based on its index in the node vector * \param _index - the x,y index in the vector * index 0,0 return the bottom left node, while index m_numXNodes, m_numyNodes will return the top right node * \return Node* - a pointer to the node at this index */ std::weak_ptr<Node> GetNodeAt(const glm::ivec2& _index); /** \brief Check if the node at a certain world coordinate can be walked on * \param _worldPos - the world coordinate of the node * \return bool - true if walkable, false if coordinate isn't in the node map or node isn't walkable */ bool IsWalkableAt(const glm::vec2& _worldPos); /** \brief Check if the node at a certain index in the node vector can be walked on * \param _index - the x,y index in the vector * \return bool - true if walkable, false if coordinate isn't in the node map or node isn't walkable */ bool IsWalkableAt(const glm::ivec2& _index); /** \brief Check if this index exists in the vector * \param _x - the x index (node on the x axis * \param _y - the y index (node on the y axis) * This fucntion will check if a certain index exists in the node vector * the index should not have coordinates below 0 or above the specified m_numXNodes and m_numyNodes of the map * \return bool - true if the coordinate exists */ bool IsPosInside(const glm::vec2& _index); /** \brief Sets the node at set world coordinate to _walkable * \param _worldPos - the world coordinate of the node * \param _walkable - the flag whether to set it to walkable or not */ void SetWalkableAt(const glm::vec2& _worldPos, bool _walkable); /** \brief Sets the node at set index to _walkable * \param _index - the index of the node in the vector * \param _walkable - the flag whether to set it to walkable or not */ void SetWalkableAt(const glm::ivec2& _index, bool _walkable); /** \brief Sets the terrain cost of node at set world coordinate to _cost * \param _worldPos - the world coordinate of the node * \param _cost - the terrain cost */ void SetTerrainCost(const glm::vec2& _worldPos, int _cost); /** \brief Sets the terrain cost of node at set index to _cost * \param _index - the index of the node in the vector * \param _cost - the terrain cost */ void SetTerrainCost(const glm::ivec2& _index, int _cost); /** \brief Gets all the available neighbors of the certain node * \param _node - pointer to the node to be checked * \param _diagonal - flag for diagonal movement * \return std::vector<Node*> - a vector of all available neighbors */ std::vector<std::weak_ptr<Node>> GetNeighbors(std::weak_ptr<Node> _node, const Diagonal& _diagonal); std::vector<Node> GetNeighbors(const Node& _node, const Diagonal& _diagonal); std::vector<std::shared_ptr<Node>> GetNodemap() const noexcept { return m_nodeMap; } /** \brief Render the outlines of the nodes as rectangles for debugging * \param _projection - the projection matrix to be used in the shader */ void DrawGrid(const glm::mat4& _projection); void DrawPath(const std::vector<glm::vec2>& _path, const glm::mat4& _projection); /** \brief Cleans the values of the nodes in the grid (except for terrain cost) */ void CleanGrid(); /** \brief Gets the total number of nodes in the node map */ int GetNumNodes(); private: void CreateGrid(std::vector<bool>& _walkableMatrix); ///< create the grid with preset collidable flags void CreateGrid(); ///< create the grid with all nodes set to collidable private: std::vector<std::shared_ptr<Node>> m_nodeMap; ///< a 1D vector representing a 2D vector for better performance glm::vec2 m_gridWorldSize{ 0.0f, 0.0f }; ///< the size of the grid world (width * node diameter and height * nodeDiameter) float m_nodeDiameter; /// the diameter of each node int m_numXNodes; ///< the number of nodes on the x axis (width) int m_numYNodes; ///< the number of nodes on the y axis (height) GameEngine::DebugRenderer m_debugRenderer; ///< a debug renderer to render the nodes for debugging };
47.126866
133
0.703563
[ "render", "vector" ]
319995786df310160ca8f902332c36e8e3853425
6,639
h
C
printemps/solver/tabu_search/core/tabu_search_core_move_evaluator.h
snowberryfield/cpp_metaheuristics
c1533608d0b2c0860a670bfba829a9d00be7d0d8
[ "MIT" ]
2
2020-08-28T08:49:50.000Z
2020-08-28T08:49:52.000Z
printemps/solver/tabu_search/core/tabu_search_core_move_evaluator.h
snowberryfield/cpp_metaheuristics
c1533608d0b2c0860a670bfba829a9d00be7d0d8
[ "MIT" ]
7
2020-05-03T06:14:32.000Z
2020-08-16T08:56:04.000Z
printemps/solver/tabu_search/core/tabu_search_core_move_evaluator.h
snowberryfield/cpp_metaheuristics
c1533608d0b2c0860a670bfba829a9d00be7d0d8
[ "MIT" ]
null
null
null
/*****************************************************************************/ // Copyright (c) 2020-2021 Yuji KOGUMA // Released under the MIT license // https://opensource.org/licenses/mit-license.php /*****************************************************************************/ #ifndef PRINTEMPS_SOLVER_TABU_SEARCH_CORE_TABU_SEARCH_CORE_MOVE_EVALUATOR_H__ #define PRINTEMPS_SOLVER_TABU_SEARCH_CORE_TABU_SEARCH_CORE_MOVE_EVALUATOR_H__ namespace printemps { namespace solver { namespace tabu_search { namespace core { /*****************************************************************************/ template <class T_Variable, class T_Expression> class TabuSearchCoreMoveEvaluator { private: model::Model<T_Variable, T_Expression> *m_model_ptr; Memory<T_Variable, T_Expression> * m_memory_ptr; option::Option m_option; public: /*************************************************************************/ TabuSearchCoreMoveEvaluator(void) { this->initialize(); } /*************************************************************************/ TabuSearchCoreMoveEvaluator( model::Model<T_Variable, T_Expression> *a_model_ptr, Memory<T_Variable, T_Expression> * a_memory_ptr, const option::Option & a_option) { this->setup(a_model_ptr, a_memory_ptr, a_option); } /*************************************************************************/ inline void setup(model::Model<T_Variable, T_Expression> *a_model_ptr, Memory<T_Variable, T_Expression> * a_memory_ptr, const option::Option & a_option) { this->initialize(); m_model_ptr = a_model_ptr; m_memory_ptr = a_memory_ptr; m_option = a_option; } /*************************************************************************/ inline void initialize(void) { m_model_ptr = nullptr; m_memory_ptr = nullptr; m_option.initialize(); } /*************************************************************************/ inline constexpr bool compute_permissibility( const neighborhood::Move<T_Variable, T_Expression> &a_MOVE, // const int a_DURATION) const noexcept { const auto &LAST_UPDATE_ITERATIONS = m_memory_ptr->last_update_iterations(); if (m_option.tabu_search.tabu_mode == option::tabu_mode::All && a_MOVE.sense != neighborhood::MoveSense::Selection) { /** * "All" tabu mode * The move is regarded as "tabu" if all of the variable to * be altered are included in the tabu list. */ for (const auto &alteration : a_MOVE.alterations) { const int &LAST_UPDATE_ITERATION = LAST_UPDATE_ITERATIONS[alteration.first->proxy_index()] [alteration.first->flat_index()]; if (a_DURATION >= LAST_UPDATE_ITERATION) { return true; } } return false; } else { /** * "Any" tabu mode * The move is regarded as "tabu" if it includes any alteration * about a variable in the tabu list. */ for (const auto &alteration : a_MOVE.alterations) { const int &LAST_UPDATE_ITERATION = LAST_UPDATE_ITERATIONS[alteration.first->proxy_index()] [alteration.first->flat_index()]; if (a_DURATION < LAST_UPDATE_ITERATION) { return false; } } return true; } /** * If the process is normal, this return statement is not reached. */ return true; } /*************************************************************************/ inline constexpr double compute_frequency_penalty( const neighborhood::Move<T_Variable, T_Expression> &a_MOVE, const int a_ITERATION) const noexcept { const auto &UPDATE_COUNTS = m_memory_ptr->update_counts(); if (a_ITERATION == 0) { return 0.0; } int move_update_count = 0; for (const auto &alteration : a_MOVE.alterations) { move_update_count += UPDATE_COUNTS[alteration.first->proxy_index()] [alteration.first->flat_index()]; } return move_update_count * m_memory_ptr->total_update_count_reciprocal() * m_option.tabu_search.frequency_penalty_coefficient; } /*************************************************************************/ inline constexpr double compute_lagrangian_penalty( const neighborhood::Move<T_Variable, T_Expression> &a_MOVE) const noexcept { double lagrangian_penalty = 0.0; for (const auto &alteration : a_MOVE.alterations) { lagrangian_penalty += alteration.first->lagrangian_coefficient() * alteration.second; } return lagrangian_penalty * m_option.tabu_search.lagrangian_penalty_coefficient; } /*************************************************************************/ inline constexpr void evaluate( TabuSearchCoreMoveScore * a_score_ptr, // const neighborhood::Move<T_Variable, T_Expression> &a_MOVE, // const int a_ITERATION, // const int a_DURATION) const noexcept { /** * Check if the move is permissible or not. */ a_score_ptr->is_permissible // = this->compute_permissibility(a_MOVE, a_DURATION); /** * Compute the frequency penalty of the move. */ a_score_ptr->frequency_penalty // = this->compute_frequency_penalty(a_MOVE, a_ITERATION); /** * Compute the lagrangian penalty of the move. */ a_score_ptr->lagrangian_penalty = 0.0; if (m_option.is_enabled_lagrange_dual) { a_score_ptr->lagrangian_penalty // = this->compute_lagrangian_penalty(a_MOVE); } } }; } // namespace core } // namespace tabu_search } // namespace solver } // namespace printemps #endif /*****************************************************************************/ // END /*****************************************************************************/
39.993976
79
0.492996
[ "model" ]
319c86f83c045c956305b9203598bbcc61267f1e
7,249
h
C
yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/util/Timer.h
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
null
null
null
yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/util/Timer.h
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
36
2019-06-03T20:30:45.000Z
2020-04-17T19:17:26.000Z
yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/util/Timer.h
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
6
2019-06-03T16:56:43.000Z
2020-01-09T03:32:31.000Z
#ifndef DDM__UTIL__TIMER_H_ #define DDM__UTIL__TIMER_H_ #include "../../ddm/internal/Config.h" // Timestamp interfaces: #include "../../ddm/util/Timestamp.h" #include "../../ddm/util/TimeMeasure.h" #include <climits> // Timestamp implementations: #if defined(DDM__UTIL__TIMER_PAPI) #include "../../ddm/util/internal/TimestampPAPI.h" #else #include "../../ddm/util/internal/TimestampCounterPosix.h" #include "../../ddm/util/internal/TimestampClockPosix.h" #endif #include "../../ddm/internal/Logging.h" namespace ddm { namespace util { template<TimeMeasure::MeasureMode TimerType> class Timer; ////////////////////////////////////////////////////////////////////////////// // Specialization for clock-based timer template<> class Timer<TimeMeasure::Clock> { public: typedef Timestamp::counter_t timestamp_t; private: typedef Timer self_t; private: timestamp_t timestampStart; private: #if defined(DDM__UTIL__TIMER_PAPI) // PAPI support, use measurements from PAPI typedef ddm::util::internal::TimestampPAPI<TimeMeasure::Clock> Timestamp_t; #elif defined(DDM__UTIL__TIMER_POSIX) // POSIX platform typedef ddm::util::internal::TimestampClockPosix Timestamp_t; #else // No PAPI, no POSIX #pragma error "ddm::util::Timer requires POSIX platform or PAPI" #endif public: typedef Timestamp_t timestamp_type; typedef timestamp_t timestamp; public: inline Timer() { timestampStart = Timer::Now(); } inline Timer(const self_t & other) : timestampStart(other.timestampStart) { } inline Timer & operator=(const self_t & other) { if (this != &other) { timestampStart = other.timestampStart; } return *this; } /** * Microseconds elapsed since instantiation of this Timer object. */ inline double Elapsed() const { timestamp_t now; Timestamp_t timestamp; now = timestamp.Value(); return (static_cast<double>(now - timestampStart) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Returns timestamp from instantiation of this Timer. */ inline const timestamp_t & Start() const { return timestampStart; } /** * Microseconds elapsed since given timestamp. */ inline static double ElapsedSince(timestamp_t timestamp) { Timestamp_t now; return (static_cast<double>(now.Value() - timestamp) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Produces current timestamp. */ inline static timestamp_t Now() { Timestamp_t timestamp; return timestamp.Value(); } /** * Convert interval of two timestamp values to microseconds. */ inline static double FromInterval( const timestamp_t & start, const timestamp_t & end) { return (static_cast<double>(end - start) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Convert interval of two timestamp values to mircoseconds. */ inline static double FromInterval( const double & start, const double & end) { return ((end - start) * Timestamp_t::FrequencyPrescale() / Timestamp_t::FrequencyScaling()); } inline static void Calibrate( unsigned int freq = 0) { DDM_LOG_DEBUG("Timer<Clock>::Calibrate(freq)", freq); Timestamp_t::Calibrate(freq); } inline static const char * TimerName() { return Timestamp_t::TimerName(); } inline static Timestamp::counter_t TimestampInfinity() { return Timestamp_t::TimestampInfinity(); } inline static Timestamp::counter_t TimestampNegInfinity() { return Timestamp_t::TimestampNegInfinity(); } inline static double FrequencyScaling() { return Timestamp_t::FrequencyScaling(); } }; ////////////////////////////////////////////////////////////////////////////// // Specialization for counter-based timer template<> class Timer<TimeMeasure::Counter> { public: typedef Timestamp::counter_t timestamp_t; private: typedef Timer self_t; private: timestamp_t timestampStart; private: #if defined(DDM__UTIL__TIMER_PAPI) // PAPI support, use measurements from PAPI typedef ddm::util::internal::TimestampPAPI<TimeMeasure::Counter> Timestamp_t; #elif defined(DDM__UTIL__TIMER_POSIX) // POSIX platform typedef ddm::util::internal::TimestampCounterPosix Timestamp_t; #else // No PAPI, no POSIX #pragma error "ddm::util::Timer requires POSIX platform or PAPI" #endif public: typedef Timestamp_t timestamp_type; typedef timestamp_t timestamp; public: inline Timer() { timestampStart = Timer::Now(); } inline Timer(const self_t & other) : timestampStart(other.timestampStart) { } inline Timer & operator=(const self_t & other) { if (this != &other) { timestampStart = other.timestampStart; } return *this; } /** * Microseconds elapsed since instantiation of this Timer object. */ inline double Elapsed() const { timestamp_t now; Timestamp_t timestamp; now = timestamp.Value(); return (static_cast<double>(now - timestampStart) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Returns timestamp from instantiation of this Timer. */ inline const timestamp_t & Start() const { return timestampStart; } /** * Microseconds elapsed since given timestamp. */ inline static double ElapsedSince(timestamp_t timestamp) { Timestamp_t now; return (static_cast<double>(now.Value() - timestamp) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Produces current timestamp. */ inline static timestamp_t Now() { Timestamp_t timestamp; return timestamp.Value(); } /** * Convert interval of two timestamp values to mircoseconds. */ inline static double FromInterval( const timestamp_t & start, const timestamp_t & end) { return (static_cast<double>(end - start) * static_cast<double>(Timestamp_t::FrequencyPrescale())) / static_cast<double>(Timestamp_t::FrequencyScaling()); } /** * Convert interval of two timestamp values to mircoseconds. */ inline static double FromInterval( const double & start, const double & end) { return ((end - start) * Timestamp_t::FrequencyPrescale() / Timestamp_t::FrequencyScaling()); } inline static void Calibrate( unsigned int freq = 0) { DDM_LOG_DEBUG("Timer<Counter>::Calibrate(freq)", freq); Timestamp_t::Calibrate(freq); } inline static const char * TimerName() { return Timestamp_t::TimerName(); } inline static Timestamp::counter_t TimestampInfinity() { return Timestamp_t::TimestampInfinity(); } inline static Timestamp::counter_t TimestampNegInfinity() { return Timestamp_t::TimestampNegInfinity(); } inline static double FrequencyScaling() { return Timestamp_t::FrequencyScaling(); } }; } // namespace util } // namespace ddm #endif // DDM__UTIL__TIMER_H_
23.012698
78
0.678714
[ "object" ]
319cf1072acc87c9a0872c7ea4bbece3b238a8a2
10,613
h
C
aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/ThirdPartySourceRepository.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/ThirdPartySourceRepository.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/ThirdPartySourceRepository.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/codeguru-reviewer/CodeGuruReviewer_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace CodeGuruReviewer { namespace Model { /** * <p> Information about a third-party source repository connected to CodeGuru * Reviewer. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codeguru-reviewer-2019-09-19/ThirdPartySourceRepository">AWS * API Reference</a></p> */ class AWS_CODEGURUREVIEWER_API ThirdPartySourceRepository { public: ThirdPartySourceRepository(); ThirdPartySourceRepository(Aws::Utils::Json::JsonView jsonValue); ThirdPartySourceRepository& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p> The name of the third party source repository. </p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p> The name of the third party source repository. </p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p> The name of the third party source repository. </p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p> The name of the third party source repository. </p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p> The name of the third party source repository. </p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p> The name of the third party source repository. </p> */ inline ThirdPartySourceRepository& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p> The name of the third party source repository. </p> */ inline ThirdPartySourceRepository& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p> The name of the third party source repository. </p> */ inline ThirdPartySourceRepository& WithName(const char* value) { SetName(value); return *this;} /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline const Aws::String& GetConnectionArn() const{ return m_connectionArn; } /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline bool ConnectionArnHasBeenSet() const { return m_connectionArnHasBeenSet; } /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline void SetConnectionArn(const Aws::String& value) { m_connectionArnHasBeenSet = true; m_connectionArn = value; } /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline void SetConnectionArn(Aws::String&& value) { m_connectionArnHasBeenSet = true; m_connectionArn = std::move(value); } /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline void SetConnectionArn(const char* value) { m_connectionArnHasBeenSet = true; m_connectionArn.assign(value); } /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline ThirdPartySourceRepository& WithConnectionArn(const Aws::String& value) { SetConnectionArn(value); return *this;} /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline ThirdPartySourceRepository& WithConnectionArn(Aws::String&& value) { SetConnectionArn(std::move(value)); return *this;} /** * <p> The Amazon Resource Name (ARN) of an Amazon Web Services CodeStar * Connections connection. Its format is * <code>arn:aws:codestar-connections:region-id:aws-account_id:connection/connection-id</code>. * For more information, see <a * href="https://docs.aws.amazon.com/codestar-connections/latest/APIReference/API_Connection.html"> * <code>Connection</code> </a> in the <i>Amazon Web Services CodeStar Connections * API Reference</i>. </p> */ inline ThirdPartySourceRepository& WithConnectionArn(const char* value) { SetConnectionArn(value); return *this;} /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline const Aws::String& GetOwner() const{ return m_owner; } /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline bool OwnerHasBeenSet() const { return m_ownerHasBeenSet; } /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline void SetOwner(const Aws::String& value) { m_ownerHasBeenSet = true; m_owner = value; } /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline void SetOwner(Aws::String&& value) { m_ownerHasBeenSet = true; m_owner = std::move(value); } /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline void SetOwner(const char* value) { m_ownerHasBeenSet = true; m_owner.assign(value); } /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline ThirdPartySourceRepository& WithOwner(const Aws::String& value) { SetOwner(value); return *this;} /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline ThirdPartySourceRepository& WithOwner(Aws::String&& value) { SetOwner(std::move(value)); return *this;} /** * <p> The owner of the repository. For a GitHub, GitHub Enterprise, or Bitbucket * repository, this is the username for the account that owns the repository. For * an S3 repository, this can be the username or Amazon Web Services account ID. * </p> */ inline ThirdPartySourceRepository& WithOwner(const char* value) { SetOwner(value); return *this;} private: Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_connectionArn; bool m_connectionArnHasBeenSet; Aws::String m_owner; bool m_ownerHasBeenSet; }; } // namespace Model } // namespace CodeGuruReviewer } // namespace Aws
42.452
130
0.685669
[ "model" ]
319e87e5b9ce0730a46fb5519d30147efc417553
1,574
h
C
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
null
null
null
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
null
null
null
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
2
2021-12-22T12:55:17.000Z
2021-12-27T06:04:07.000Z
/** * @file */ #pragma once #include <cppad/cppad.hpp> #include <utility> #include <vector> namespace autoagric { namespace planning { class CosThetaIpoptInterface { public: typedef CPPAD_TESTVECTOR(double) Dvector; typedef CPPAD_TESTVECTOR(CppAD::AD<double>) ADvector; CosThetaIpoptInterface(const std::vector<std::pair<double, double>>& point, const std::vector<double>& bounds); virtual ~CosThetaIpoptInterface() = default; void set_weight_cos_included_angle(const double weight_cos_included_angle); void set_weight_anchor_points(const double weight_anchor_points); void set_weight_length(const double weight_length); void get_optimization_results(std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; bool get_bounds_info(int n, Dvector& x_l, Dvector& x_u, int m, Dvector& g_l, Dvector& g_u); bool get_starting_point(int n, Dvector& x); void operator()(ADvector& fg, const ADvector& x); private: template <class T> bool eval_obj(const T& x, T& obj_value); template <class T> bool eval_constraints(const T& x, T& g); std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_; std::vector<double> opt_x_; std::vector<double> opt_y_; size_t num_of_variables_ = 0; size_t num_of_constraints_ = 0; size_t num_of_points_ = 0; double weight_cos_included_angle_ = 0.0; double weight_anchor_points_ = 0.0; double weight_length_ = 0.0; }; } // namespace planning } // namespace autoagric
22.811594
78
0.699492
[ "vector" ]
2e61eb91013e472d5252f3648ffd31f986d757c1
2,118
h
C
Userland/DevTools/HackStudio/LanguageServers/Cpp/AutoCompleteEngine.h
tgsm/serenity
8b78ed630893e2dc0d08b8fcd6700b4d5a29ba1f
[ "BSD-2-Clause" ]
null
null
null
Userland/DevTools/HackStudio/LanguageServers/Cpp/AutoCompleteEngine.h
tgsm/serenity
8b78ed630893e2dc0d08b8fcd6700b4d5a29ba1f
[ "BSD-2-Clause" ]
null
null
null
Userland/DevTools/HackStudio/LanguageServers/Cpp/AutoCompleteEngine.h
tgsm/serenity
8b78ed630893e2dc0d08b8fcd6700b4d5a29ba1f
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Itamar S. <itamar8910@gmail.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. * * 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. */ #pragma once #include "FileDB.h" #include <DevTools/HackStudio/AutoCompleteResponse.h> #include <LibGUI/TextPosition.h> class AutoCompleteEngine { public: AutoCompleteEngine(const FileDB& filedb); virtual ~AutoCompleteEngine(); virtual Vector<GUI::AutocompleteProvider::Entry> get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position) = 0; // TODO: In the future we can pass the range that was edited and only re-parse what we have to. virtual void on_edit([[maybe_unused]] const String& file) {}; virtual void file_opened([[maybe_unused]] const String& file) {}; protected: const FileDB& filedb() const { return m_filedb; } private: const FileDB& m_filedb; };
42.36
141
0.756374
[ "vector" ]
2e61ff36575a1a3acdae6e20f62f4eb84c97e113
870
h
C
src/Game/Utils/Math.h
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
src/Game/Utils/Math.h
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
src/Game/Utils/Math.h
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
#pragma once #include <glm\glm.hpp> namespace Math { struct Vec2Hash { std::size_t operator()(const glm::vec2& vec) const { return std::hash<float>()(vec.x) ^ std::hash<float>()(vec.y); } }; struct IVec2Hash { std::size_t operator()(const glm::ivec2& vec) const { return std::hash<int>()(vec.x) ^ std::hash<int>()(vec.y); } }; struct Vec3Hash { std::size_t operator()(const glm::vec3& vec) const { return std::hash<float>()(vec.x) ^ std::hash<float>()(vec.y) ^ std::hash<float>()(vec.z); } }; glm::ivec3 GetBlockPositionInChunk(const glm::vec3& globalPosition); glm::ivec3 GetBlockCoordinates(const glm::vec3& position); glm::ivec2 GetChunkPositionFromWorldPosition(const glm::vec3& worldPosition); std::vector<glm::vec3> CastRayAndGetIntersectingBlocks(const glm::vec3& origin, const glm::vec3& direction, float distance); }
24.857143
125
0.677011
[ "vector" ]
2e7292bad4b29071a834a170a412d4bded8b92f3
3,511
h
C
packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h
coral-labs/plugins
07578ae66c249d590db1b12876521c446bbb1596
[ "BSD-3-Clause" ]
2
2022-03-15T03:02:16.000Z
2022-03-15T03:02:52.000Z
packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h
coral-labs/plugins
07578ae66c249d590db1b12876521c446bbb1596
[ "BSD-3-Clause" ]
2
2022-03-29T20:46:48.000Z
2022-03-31T10:52:42.000Z
packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h
coral-labs/plugins
07578ae66c249d590db1b12876521c446bbb1596
[ "BSD-3-Clause" ]
5
2021-10-15T03:22:42.000Z
2022-03-08T13:23:05.000Z
// Copyright 2013 The Flutter 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 PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #include <comdef.h> #include <comip.h> #include <windows.h> #include <functional> #include <memory> #include <variant> #include <vector> #include "file_dialog_controller.h" #include "test/test_utils.h" _COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog); namespace file_selector_windows { namespace test { class TestFileDialogController; // A value to use for GetResult(s) in TestFileDialogController. The type depends // on whether the dialog is an open or save dialog. using MockShowResult = std::variant<std::monostate, IShellItemPtr, IShellItemArrayPtr>; // Called for TestFileDialogController::Show, to do validation and provide a // mock return value for GetResult(s). using MockShow = std::function<MockShowResult(const TestFileDialogController&, HWND)>; // A C++-friendly version of a COMDLG_FILTERSPEC. struct DialogFilter { std::wstring name; std::wstring spec; DialogFilter(const wchar_t* name, const wchar_t* spec) : name(name), spec(spec) {} }; // An extension of the normal file dialog controller that: // - Allows for inspection of set values. // - Allows faking the 'Show' interaction, providing tests an opportunity to // validate the dialog settings and provide a return value, via MockShow. class TestFileDialogController : public FileDialogController { public: TestFileDialogController(IFileDialog* dialog, MockShow mock_show); ~TestFileDialogController(); // FileDialogController: HRESULT SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters) override; HRESULT SetOkButtonLabel(const wchar_t* text) override; HRESULT Show(HWND parent) override; HRESULT GetResult(IShellItem** out_item) const override; HRESULT GetResults(IShellItemArray** out_items) const override; // Accessors for validating IFileDialogController setter calls. std::wstring GetDefaultFolderPath() const; std::wstring GetFileName() const; const std::vector<DialogFilter>& GetFileTypes() const; std::wstring GetOkButtonLabel() const; private: IFileDialogPtr dialog_; MockShow mock_show_; MockShowResult mock_result_; // The last set values, for IFileDialog properties that have setters but no // corresponding getters. std::wstring ok_button_label_; std::vector<DialogFilter> filter_groups_; }; // A controller factory that vends TestFileDialogController instances. class TestFileDialogControllerFactory : public FileDialogControllerFactory { public: // Creates a factory whose instances use mock_show for the Show callback. TestFileDialogControllerFactory(MockShow mock_show); virtual ~TestFileDialogControllerFactory(); // Disallow copy and assign. TestFileDialogControllerFactory(const TestFileDialogControllerFactory&) = delete; TestFileDialogControllerFactory& operator=( const TestFileDialogControllerFactory&) = delete; // FileDialogControllerFactory: std::unique_ptr<FileDialogController> CreateController( IFileDialog* dialog) const override; private: MockShow mock_show_; }; } // namespace test } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_
34.421569
99
0.790943
[ "vector" ]
2e771e47163cfe472e3094e2349800387960d60d
993
h
C
Sources/FromMX.h
vlad-alexandru-ionescu/E3Dos
378ce5655b3b752fc26ffaf67d9f43b939929634
[ "Apache-2.0" ]
48
2019-02-03T01:07:36.000Z
2019-05-09T15:15:43.000Z
Sources/FromMX.h
vlad-alexandru-ionescu/E3Dos
378ce5655b3b752fc26ffaf67d9f43b939929634
[ "Apache-2.0" ]
null
null
null
Sources/FromMX.h
vlad-alexandru-ionescu/E3Dos
378ce5655b3b752fc26ffaf67d9f43b939929634
[ "Apache-2.0" ]
1
2019-02-03T15:41:46.000Z
2019-02-03T15:41:46.000Z
#ifndef _FROMMX_H_ #define _FROMMX_H_ namespace FromMX { void Transform() { fstream gin("mm.dat", ios::in); unsigned long n; unsigned long i; unsigned long m; unsigned long aux; gin>>n; VECTOR3 *p=(VECTOR3 *)Heap.Allocate(n, sizeof(VECTOR3)); VECTOR3 *N=(VECTOR3 *)Heap.Allocate(n, sizeof(VECTOR3)); for(i=0;i<n;i++) gin>>p[i].x>>p[i].y>>p[i].z; for(i=0;i<n;i++) gin>>N[i].x>>N[i].y>>N[i].z; gin>>m; TRILGTEX_MESH Mesh; Mesh.New(m); for(i=0;i<m;i++) { gin>>aux; gin>>aux; Mesh.Tris[i].a=p[aux]; Mesh.Tris[i].aN=N[aux]; Mesh.Tris[i].at=PIXEL(0, 0); gin>>aux; Mesh.Tris[i].b=p[aux]; Mesh.Tris[i].bN=N[aux]; Mesh.Tris[i].bt=PIXEL(0, 0); gin>>aux; Mesh.Tris[i].c=p[aux]; Mesh.Tris[i].cN=N[aux]; Mesh.Tris[i].ct=PIXEL(0, 0); } Mesh.SaveMesh("MESH\\Ship.bx"); Heap.Free(p); Heap.Free(N); gin.close(); } } // namespace FromMX #endif // #ifndef _FROMMX_H_
14.391304
58
0.549849
[ "mesh", "transform" ]
2e7896ca155ad609f75b235bf61aeaaf32babcbe
46,402
h
C
dll/interceptor/Direct3DDevice9Functions.h
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
4
2015-09-23T14:12:07.000Z
2021-10-04T21:03:32.000Z
dll/interceptor/Direct3DDevice9Functions.h
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
null
null
null
dll/interceptor/Direct3DDevice9Functions.h
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
2
2018-06-26T14:59:11.000Z
2021-09-01T01:50:20.000Z
void D3D9Wrapper::IDirect3DDevice9::BitmapFromSurface(D3D9Base::LPDIRECT3DSURFACE9 pSurface, const RECT &Rect, Bitmap &Bmp) { D3DSURFACE_DESC Desc; D3DLOCKED_RECT LockedRect; HRESULT hr = pSurface->GetDesc(&Desc); Assert(SUCCEEDED(hr), "pSurface->GetDesc failed"); //m_pSurface->GetDesc(&LD.Desc); //DestSurface = D3D9Wrapper::IDirect3DDevice9::GetDirect3DDevice(m_pDevice)->GetOffscreenSurface(); /*RECT Rect; Rect.left = 0; Rect.right = Desc.Width; Rect.top = 0; Rect.bottom = Desc.Height;*/ #ifdef USE_D3DX if(pSurface != m_pScratchSurface) { hr = D3D9Base::D3DXLoadSurfaceFromSurface(m_pScratchSurface, NULL, &Rect, pSurface, NULL, &Rect, D3DX_FILTER_POINT, D3DCOLOR_XRGB(0, 0, 0)); if(FAILED(hr)) { Bmp.Allocate(1, 1); Bmp[0][0] = RGBColor::Magenta; return; } Assert(SUCCEEDED(hr), "D3DXLoadSurfaceFromSurface failed"); } hr = m_pScratchSurface->LockRect(&LockedRect, &Rect, NULL); Assert(SUCCEEDED(hr), "m_pScratchSurface->LockRect failed"); Bmp.Allocate(Desc.Width, Desc.Height); RGBColor *SurfData = (RGBColor*)LockedRect.pBits; for(UINT y = 0; y < Desc.Height; y++) { memcpy(Bmp[Desc.Height - 1 - y], &SurfData[y * LockedRect.Pitch / 4], Desc.Width * 4); } hr = m_pScratchSurface->UnlockRect(); Assert(SUCCEEDED(hr), "m_pScratchSurface->UnlockRect failed"); #endif } D3D9Wrapper::IDirect3DDevice9::IDirect3DDevice9(D3D9Base::LPDIRECT3DDEVICE9 pDevice) : IDirect3DUnknown((IUnknown*) pDevice) { m_pDevice = pDevice; g_Globals.InfoFile() << "Creating objects\n"; m_pDevice->CreateOffscreenPlainSurface(ScratchSurfaceWidth, ScratchSurfaceHeight, D3D9Base::D3DFMT_A8R8G8B8, D3D9Base::D3DPOOL_SYSTEMMEM, &m_pScratchSurface, NULL); m_Overlay.Init(m_pDevice); } D3D9Wrapper::IDirect3DDevice9* D3D9Wrapper::IDirect3DDevice9::GetDirect3DDevice(D3D9Base::LPDIRECT3DDEVICE9 pDevice) { D3D9Wrapper::IDirect3DDevice9* p = (D3D9Wrapper::IDirect3DDevice9*) m_List.GetDataPtr(pDevice); if(p == NULL) { p = new D3D9Wrapper::IDirect3DDevice9(pDevice); m_List.AddMember(pDevice, p); return p; } p->m_ulRef++; return p; } STDMETHODIMP_(ULONG) D3D9Wrapper::IDirect3DDevice9::Release(THIS) { //g_Globals.InfoFile() << "Releasing device: " << m_ulRef - 1 << endl; if(m_ulRef == 1) { ReportFreeDevice(); m_pScratchSurface->Release(); m_Overlay.FreeMemory(); g_Globals.InfoFile() << "Releasing objects\n"; } m_pUnk->Release(); ULONG ulRef = --m_ulRef; if(ulRef == 0) { m_List.DeleteMember(GetD3D9Device()); delete this; return NULL; } return ulRef; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::TestCooperativeLevel(THIS) { return m_pDevice->TestCooperativeLevel(); } STDMETHODIMP_(UINT) D3D9Wrapper::IDirect3DDevice9::GetAvailableTextureMem(THIS) { return m_pDevice->GetAvailableTextureMem(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::EvictManagedResources(THIS) { return m_pDevice->EvictManagedResources(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetDirect3D(THIS_ D3D9Wrapper::IDirect3D9** ppD3D9) { D3D9Base::LPDIRECT3D9 BaseDirect3D = NULL; HRESULT hr = m_pDevice->GetDirect3D(&BaseDirect3D); if(FAILED(hr)) { *ppD3D9 = NULL; return hr; } D3D9Wrapper::IDirect3D9* pD3D = D3D9Wrapper::IDirect3D9::GetDirect3D(BaseDirect3D); if(pD3D == NULL) { BaseDirect3D->Release(); hr = E_OUTOFMEMORY; } *ppD3D9 = pD3D; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetDeviceCaps(THIS_ D3DCAPS9* pCaps) { HRESULT hr = m_pDevice->GetDeviceCaps(pCaps); //Assert(hr != D3DERR_NOTAVAILABLE, "D3DERR_NOTAVAILABLE"); return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetDisplayMode(THIS_ UINT iSwapChain,D3DDISPLAYMODE* pMode) { return m_pDevice->GetDisplayMode(iSwapChain, pMode); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetCreationParameters(THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters) { return m_pDevice->GetCreationParameters( pParameters); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetCursorProperties(THIS_ UINT XHotSpot,UINT YHotSpot,D3D9Wrapper::IDirect3DSurface9* pCursorBitmap) { return m_pDevice->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap == 0 ? 0 : pCursorBitmap->GetSurface9()); } STDMETHODIMP_(void) D3D9Wrapper::IDirect3DDevice9::SetCursorPosition(THIS_ int X,int Y,DWORD Flags) { return m_pDevice->SetCursorPosition(X, Y, Flags); } STDMETHODIMP_(BOOL) D3D9Wrapper::IDirect3DDevice9::ShowCursor(THIS_ BOOL bShow) { return m_pDevice->ShowCursor(bShow); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateAdditionalSwapChain(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DSwapChain9** pSwapChain) { g_Globals.UnreportedFile() << "CreateAdditionalSwapChain\n"; return E_OUTOFMEMORY; //return m_pDevice->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetSwapChain(THIS_ UINT iSwapChain,IDirect3DSwapChain9** pSwapChain) { *pSwapChain = NULL; D3D9Base::LPDIRECT3DSWAPCHAIN9 BaseSwapChain = NULL; HRESULT hr = m_pDevice->GetSwapChain(iSwapChain, &BaseSwapChain); if(FAILED(hr) || BaseSwapChain == NULL) { return hr; } D3D9Wrapper::IDirect3DSwapChain9* NewSwapChain = D3D9Wrapper::IDirect3DSwapChain9::GetSwapChain(BaseSwapChain, this); if(NewSwapChain == NULL) { BaseSwapChain->Release(); return E_OUTOFMEMORY; } *pSwapChain = NewSwapChain; return hr; } STDMETHODIMP_(UINT) D3D9Wrapper::IDirect3DDevice9::GetNumberOfSwapChains(THIS) { return m_pDevice->GetNumberOfSwapChains(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::Reset(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters) { //m_Console.OnLostDevice(); m_Overlay.FreeMemory(); HRESULT hr = m_pDevice->Reset(pPresentationParameters); if(SUCCEEDED(hr)) { m_Overlay.Init(m_pDevice); //m_Console.OnResetDevice(); } return hr; } UINT FrameIndex = 0; STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::Present(THIS_ CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion) { ReportPresent(pSourceRect, pDestRect); if(g_Globals.UsingOverlay) { m_pDevice->BeginScene(); m_Overlay.RenderConsole(); m_pDevice->EndScene(); } /*if(g_Globals.CaptureNextFullScreen) { g_Globals.CaptureNextFullScreen = false; Bitmap Bmp; D3D9Base::LPDIRECT3DSURFACE9 BackBuffer; HRESULT hr = m_pDevice->GetBackBuffer(0, 0, D3D9Base::D3DBACKBUFFER_TYPE_MONO, &BackBuffer); Assert(SUCCEEDED(hr), "D3DDevice->GetBackBuffer failed"); BitmapFromSurface(BackBuffer, Bmp); BackBuffer->Release(); Bmp.SavePNG(g_Globals.NewTextureDirectory + String("ScreenCapture.png")); }*/ HRESULT hr = m_pDevice->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); if(hr == D3DERR_DEVICELOST) { m_Overlay.FreeMemory(); //m_Console.OnLostDevice(); } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetBackBuffer(THIS_ UINT iSwapChain,UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,D3D9Wrapper::IDirect3DSurface9** ppBackBuffer) { *ppBackBuffer = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->GetBackBuffer(iSwapChain, iBackBuffer, Type, &BaseSurface); if(FAILED(hr) || BaseSurface == NULL) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "GetBackBuffer called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppBackBuffer = NewSurface; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetRasterStatus(THIS_ UINT iSwapChain,D3DRASTER_STATUS* pRasterStatus) { return m_pDevice->GetRasterStatus(iSwapChain, pRasterStatus); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetDialogBoxMode(THIS_ BOOL bEnableDialogs) { return m_pDevice->SetDialogBoxMode(bEnableDialogs); } STDMETHODIMP_(void) D3D9Wrapper::IDirect3DDevice9::SetGammaRamp(THIS_ UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp) { return m_pDevice->SetGammaRamp(iSwapChain, Flags, pRamp); } STDMETHODIMP_(void) D3D9Wrapper::IDirect3DDevice9::GetGammaRamp(THIS_ UINT iSwapChain,D3DGAMMARAMP* pRamp) { return m_pDevice->GetGammaRamp(iSwapChain, pRamp); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateTexture(THIS_ UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,HANDLE* pSharedHandle) { *ppTexture = NULL; D3D9Base::LPDIRECT3DTEXTURE9 BaseTexture = NULL; HRESULT hr = m_pDevice->CreateTexture( Width, Height, Levels, Usage, Format, Pool, &BaseTexture, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DTexture9* NewTexture = D3D9Wrapper::IDirect3DTexture9::GetTexture(BaseTexture); if(NewTexture == NULL) { BaseTexture->Release(); return E_OUTOFMEMORY; } else { *ppTexture = NewTexture; // // Report the texture create // D3D9Base::LPDIRECT3DSURFACE9 TopLevelSurface; BaseTexture->GetSurfaceLevel(0, &TopLevelSurface); //g_Globals.ErrorFile() << "CreateTexture BaseTexture=" << BaseTexture << " TopLevelSurface=" << TopLevelSurface << endl; D3DSURFACE_DESC Desc; TopLevelSurface->GetDesc(&Desc); Bitmap Bmp(Desc.Width, Desc.Height); Bmp.Clear(RGBColor::Magenta); ReportUnlockTexture(Desc, Bmp, BaseTexture); TopLevelSurface->Release(); return hr; } } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateVolumeTexture(THIS_ UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,HANDLE* pSharedHandle) { g_Globals.UnreportedFile() << "CreateVolumeTexture\n"; return m_pDevice->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateCubeTexture(THIS_ UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,HANDLE* pSharedHandle) { g_Globals.UnreportedFile() << "CreateCubeTexture\n"; return m_pDevice->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateVertexBuffer(THIS_ UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle) { *ppVertexBuffer = NULL; D3D9Base::LPDIRECT3DVERTEXBUFFER9 BaseVB = NULL; if(g_Globals.ForceSoftwareVertexProcessing) { Usage |= D3DUSAGE_SOFTWAREPROCESSING; } HRESULT hr = m_pDevice->CreateVertexBuffer(Length, Usage, FVF, Pool, &BaseVB, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DVertexBuffer9* NewVB = D3D9Wrapper::IDirect3DVertexBuffer9::GetVertexBuffer(BaseVB); if(NewVB == NULL) { BaseVB->Release(); return E_OUTOFMEMORY; } *ppVertexBuffer = NewVB; BufferLockData LD; LD.Handle = BaseVB; LD.Flags = 0; LD.OffsetToLock = 0; LD.SizeToLock = 0; LD.pRAMBuffer = NULL; LD.Create = true; D3DVERTEXBUFFER_DESC Desc; BaseVB->GetDesc(&Desc); ReportLockVertexBuffer(LD, Desc); return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateIndexBuffer(THIS_ UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,HANDLE* pSharedHandle) { *ppIndexBuffer = NULL; D3D9Base::LPDIRECT3DINDEXBUFFER9 BaseIB = NULL; HRESULT hr = m_pDevice->CreateIndexBuffer(Length, Usage, Format, Pool, &BaseIB, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DIndexBuffer9* NewIB = D3D9Wrapper::IDirect3DIndexBuffer9::GetIndexBuffer(BaseIB); if(NewIB == NULL) { BaseIB->Release(); return E_OUTOFMEMORY; } *ppIndexBuffer = NewIB; BufferLockData LD; LD.Handle = BaseIB; LD.Flags = 0; LD.OffsetToLock = 0; LD.SizeToLock = 0; LD.pRAMBuffer = NULL; LD.Create = true; D3DINDEXBUFFER_DESC Desc; BaseIB->GetDesc(&Desc); ReportLockIndexBuffer(LD, Desc); return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateRenderTarget(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { *ppSurface = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, &BaseSurface, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "CreateRenderTarget called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppSurface = NewSurface; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateDepthStencilSurface(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { *ppSurface = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, &BaseSurface, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "CreateDepthStencilSurface called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppSurface = NewSurface; return hr; } void ReportUpdateSurface(D3D9Wrapper::IDirect3DDevice9 *Device, D3D9Wrapper::IDirect3DSurface9* pSourceSurface, const RECT &SourceRect, D3DSURFACE_DESC &DestinationDesc, D3D9Base::LPDIRECT3DTEXTURE9 BaseTexture) { Bitmap Bmp; Device->BitmapFromSurface(pSourceSurface->GetSurface9(), SourceRect, Bmp); ReportUnlockTexture(DestinationDesc, Bmp, BaseTexture); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::UpdateSurface(THIS_ IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestinationSurface,CONST POINT* pDestPoint) { D3D9Base::LPDIRECT3DSURFACE9 BaseSourceSurface = NULL; if(pSourceSurface != NULL) { BaseSourceSurface = pSourceSurface->GetSurface9(); } D3D9Base::LPDIRECT3DSURFACE9 BaseDestinationSurface = NULL; if(pDestinationSurface != NULL) { BaseDestinationSurface = pDestinationSurface->GetSurface9(); } //g_Globals.InfoFile() << "UpdateSurface called\n"; HRESULT hr = m_pDevice->UpdateSurface(BaseSourceSurface, pSourceRect, BaseDestinationSurface, pDestPoint); if(SUCCEEDED(hr)) { D3D9Base::LPDIRECT3DTEXTURE9 BaseTexture = NULL; hr = pDestinationSurface->GetContainer(D3D9Base::IID_IDirect3DTexture9, (void **)&BaseTexture); if(SUCCEEDED(hr)) { D3DSURFACE_DESC DestinationDesc, TopLevelDesc; pDestinationSurface->GetDesc(&DestinationDesc); /*UINT IsRenderTarget = 0; if(MyDesc.Usage & D3DUSAGE_RENDERTARGET) { IsRenderTarget = 1; } g_Globals.InfoFile() << "UpdateSurface Desc: Size=" << MyDesc.Width << "x" << MyDesc.Height << "Usage=" << IsRenderTarget << endl;*/ hr = BaseTexture->GetLevelDesc(0, &TopLevelDesc); Assert(SUCCEEDED(hr), "BaseTexture->GetLevelDesc failed"); //g_Globals.InfoFile() << "TopLevel check: " << this << " TopLevel=" << TopLevelDesc.Width << "x" << TopLevelDesc.Height << " this=" << MyDesc.Width << "x" << MyDesc.Height << endl; if(TopLevelDesc.Width == DestinationDesc.Width && TopLevelDesc.Height == DestinationDesc.Height) { ReportUpdateSurface(this, pSourceSurface, *pSourceRect, DestinationDesc, BaseTexture); } BaseTexture->Release(); } else { g_Globals.ErrorFile() << "GetContainer failed\n"; //(could be a cubemap) } } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::UpdateTexture(THIS_ IDirect3DBaseTexture9* pSourceTexture,IDirect3DBaseTexture9* pDestinationTexture) { g_Globals.InfoFile() << "UpdateTexture called\n"; return m_pDevice->UpdateTexture(pSourceTexture->GetBaseTexture9(), pDestinationTexture->GetBaseTexture9()); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetRenderTargetData(THIS_ IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface) { D3D9Base::LPDIRECT3DSURFACE9 BaseRenderTarget = NULL; if(pRenderTarget != NULL) { BaseRenderTarget = pRenderTarget->GetSurface9(); } return m_pDevice->GetRenderTargetData(BaseRenderTarget, pDestSurface->GetSurface9()); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetFrontBufferData(THIS_ UINT iSwapChain,IDirect3DSurface9* pDestSurface) { D3D9Base::LPDIRECT3DSURFACE9 BaseDestSurface = NULL; if(pDestSurface != NULL) { BaseDestSurface = pDestSurface->GetSurface9(); } return m_pDevice->GetFrontBufferData(iSwapChain, BaseDestSurface); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::StretchRect(THIS_ IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter) { g_Globals.InfoFile() << "StretchRect called\n"; return m_pDevice->StretchRect(pSourceSurface->GetSurface9(), pSourceRect, pDestSurface->GetSurface9(), pDestRect, Filter); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::ColorFill(THIS_ IDirect3DSurface9* pSurface,CONST RECT* pRect,D3DCOLOR color) { return m_pDevice->ColorFill(pSurface->GetSurface9(), pRect, color); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateOffscreenPlainSurface(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,D3D9Wrapper::IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { *ppSurface = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->CreateOffscreenPlainSurface(Width, Height, Format, Pool, &BaseSurface, pSharedHandle); if( FAILED(hr) ) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "CreateOffscreenPlainSurface called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppSurface = NewSurface; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetRenderTarget(THIS_ DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget) { /*IDirect3DSurface9* pOldRenderTarget = NULL; if(UpdateDynamicTextures) { HRESULT hr = GetRenderTarget(RenderTargetIndex, &pOldRenderTarget); if( FAILED(hr) ) { g_Globals.ErrorFile() << "GetRenderTarget failed in SetRenderTarget\n"; return hr; } }*/ D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; if(pRenderTarget != NULL) { BaseSurface = pRenderTarget->GetSurface9(); } ReportSetRenderTarget(RenderTargetIndex, BaseSurface); // // HACK: because I don't reimplement IDirect3DSwapChain9, and return the D3D9Base swap chain, it is possible that pRenderTarget // is a D3D9Base object, not a D3D9Wrapper one // if(UINT(BaseSurface) == 1) { g_Globals.InfoFile() << "D3D9Base render target detected (IDirect3DSwapChain9 bug)\n"; BaseSurface = (D3D9Base::LPDIRECT3DSURFACE9)pRenderTarget; } if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "SetRenderTarget called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(pRenderTarget)) << endl; } HRESULT hr = m_pDevice->SetRenderTarget(RenderTargetIndex, BaseSurface); if(FAILED(hr)) { return hr; } /*if(UpdateDynamicTextures && pOldRenderTarget != NULL) { D3DLOCKED_RECT LockInfo; hr = pOldRenderTarget->LockRect(&LockInfo, NULL, 0); if(FAILED(hr)) { g_Globals.ErrorFile() << "pOldRenderTarget->LockRect failed in SetRenderTarget\n"; return hr; } hr = pOldRenderTarget->UnlockRect(); if(FAILED(hr)) { g_Globals.ErrorFile() << "pOldRenderTarget->UnlockRect failed in SetRenderTarget\n"; return hr; } }*/ return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetRenderTarget(THIS_ DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget) { *ppRenderTarget = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->GetRenderTarget(RenderTargetIndex, &BaseSurface); if(FAILED(hr) || BaseSurface == NULL) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "GetRenderTarget called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppRenderTarget = NewSurface; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetDepthStencilSurface(THIS_ IDirect3DSurface9* pNewZStencil) { if(pNewZStencil == NULL) { return m_pDevice->SetDepthStencilSurface(NULL); } else { return m_pDevice->SetDepthStencilSurface(pNewZStencil->GetSurface9()); } } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetDepthStencilSurface(THIS_ IDirect3DSurface9** ppZStencilSurface) { *ppZStencilSurface = NULL; D3D9Base::LPDIRECT3DSURFACE9 BaseSurface = NULL; HRESULT hr = m_pDevice->GetDepthStencilSurface(&BaseSurface); if(FAILED(hr) || BaseSurface == NULL) { return hr; } D3D9Wrapper::IDirect3DSurface9* NewSurface = D3D9Wrapper::IDirect3DSurface9::GetSurface(BaseSurface); if(DebuggingSurfaceCreation) { g_Globals.InfoFile() << "GetDepthStencilSurface called. D3D9Base: " << String::UnsignedIntAsHex(UINT(BaseSurface)) << " D3D9Wrapper: " << String::UnsignedIntAsHex(UINT(NewSurface)) << endl; } if(NewSurface == NULL) { BaseSurface->Release(); return E_OUTOFMEMORY; } *ppZStencilSurface = NewSurface; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::BeginScene(THIS) { ReportBeginScene(); return m_pDevice->BeginScene(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::EndScene(THIS) { ReportEndScene(); return m_pDevice->EndScene(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::Clear(THIS_ DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil) { ReportClear(Count, pRects, Flags, Color, Z, Stencil); return m_pDevice->Clear(Count, pRects, Flags, Color, Z, Stencil); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetTransform(THIS_ D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix) { HRESULT hr = m_pDevice->SetTransform(State, pMatrix); ReportSetTransform(State, pMatrix); return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetTransform(THIS_ D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix) { return m_pDevice->GetTransform(State, pMatrix); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::MultiplyTransform(THIS_ D3DTRANSFORMSTATETYPE a,CONST D3DMATRIX *b) { g_Globals.UnreportedFile() << "MultiplyTransform\n"; return m_pDevice->MultiplyTransform(a, b); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetViewport(THIS_ CONST D3DVIEWPORT9* pViewport) { if(!SkipSetViewport) { ReportSetViewport(pViewport); } return m_pDevice->SetViewport(pViewport); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetViewport(THIS_ D3DVIEWPORT9* pViewport) { return m_pDevice->GetViewport(pViewport); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetMaterial(THIS_ CONST D3DMATERIAL9* pMaterial) { ReportSetMaterial(pMaterial); return m_pDevice->SetMaterial(pMaterial); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetMaterial(THIS_ D3DMATERIAL9* pMaterial) { return m_pDevice->GetMaterial(pMaterial); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetLight(THIS_ DWORD Index,CONST D3DLIGHT9 *Light) { ReportSetLight(Index, Light); return m_pDevice->SetLight(Index, Light); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetLight(THIS_ DWORD Index,D3DLIGHT9* Light) { return m_pDevice->GetLight(Index, Light); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::LightEnable(THIS_ DWORD Index,BOOL Enable) { ReportLightEnable(Index, Enable); return m_pDevice->LightEnable(Index, Enable); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetLightEnable(THIS_ DWORD Index,BOOL* pEnable) { return m_pDevice->GetLightEnable(Index, pEnable); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetClipPlane(THIS_ DWORD Index,CONST float* pPlane) { return m_pDevice->SetClipPlane(Index, pPlane); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetClipPlane(THIS_ DWORD Index,float* pPlane) { return m_pDevice->GetClipPlane(Index, pPlane); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetRenderState(THIS_ D3DRENDERSTATETYPE State,DWORD Value) { if(!SkipSetRenderState) { ReportSetRenderState(State, Value); } return m_pDevice->SetRenderState(State, Value); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetRenderState(THIS_ D3DRENDERSTATETYPE State,DWORD* pValue) { return m_pDevice->GetRenderState(State, pValue); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateStateBlock(THIS_ D3DSTATEBLOCKTYPE Type,IDirect3DStateBlock9** ppSB) { g_Globals.UnreportedFile() << "CreateStateBlock\n"; return m_pDevice->CreateStateBlock(Type, ppSB); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::BeginStateBlock(THIS) { g_Globals.UnreportedFile() << "BeginStateBlock\n"; return m_pDevice->BeginStateBlock(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::EndStateBlock(THIS_ IDirect3DStateBlock9** ppSB) { return m_pDevice->EndStateBlock(ppSB); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetClipStatus(THIS_ CONST D3DCLIPSTATUS9* pClipStatus) { return m_pDevice->SetClipStatus(pClipStatus); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetClipStatus(THIS_ D3DCLIPSTATUS9* pClipStatus) { return m_pDevice->GetClipStatus(pClipStatus); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetTexture(THIS_ DWORD Stage,IDirect3DBaseTexture9** ppTexture) { *ppTexture = NULL; D3D9Base::LPDIRECT3DBASETEXTURE9 BaseTexture = NULL; HRESULT hr = m_pDevice->GetTexture(Stage, &BaseTexture); if(FAILED(hr) || BaseTexture == NULL) { return hr; } D3D9Wrapper::IDirect3DBaseTexture9* NewTexture = D3D9Wrapper::IDirect3DBaseTexture9::GetBaseTexture(BaseTexture); if(NewTexture == NULL) { BaseTexture->Release(); return E_OUTOFMEMORY; } *ppTexture = NewTexture; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetTexture(THIS_ DWORD Stage,IDirect3DBaseTexture9* pTexture) { if(pTexture == NULL) { D3D9Base::LPDIRECT3DSURFACE9 Surfaces[1]; Surfaces[0] = NULL; ReportSetTexture(Stage, (HANDLE *)Surfaces, 1); } else { D3DRESOURCETYPE Type = pTexture->GetType(); switch( Type ) { case D3D9Base::D3DRTYPE_TEXTURE: { D3D9Base::IDirect3DTexture9* BaseTexture = ((D3D9Wrapper::IDirect3DTexture9*)pTexture)->GetTexture9(); /*D3D9Base::LPDIRECT3DSURFACE9 TopLevelSurface[1]; BaseTexture->GetSurfaceLevel(0, &TopLevelSurface[0]); ReportSetTexture(Stage, (HANDLE *)TopLevelSurface, 1); D3D9Base::LPDIRECT3DSURFACE9 TopLevelSurfaceTest; BaseTexture->GetSurfaceLevel(0, &TopLevelSurfaceTest); g_Globals.ErrorFile() << "SetTexture: pTexture=" << pTexture << " BaseTexture=" << BaseTexture << " TopLevelSurface=" << TopLevelSurfaceTest << endl; TopLevelSurface[0]->Release();*/ D3D9Base::LPDIRECT3DSURFACE9 Surfaces[1]; Surfaces[0] = (D3D9Base::LPDIRECT3DSURFACE9)BaseTexture; ReportSetTexture(Stage, (HANDLE *)Surfaces, 1); //g_Globals.ErrorFile() << "SetTexture: pTexture=" << pTexture << " BaseTexture=" << BaseTexture << endl; } break; case D3D9Base::D3DRTYPE_VOLUMETEXTURE: g_Globals.UnreportedFile() << "Volume Set Texture\n"; break; case D3D9Base::D3DRTYPE_CUBETEXTURE: //g_Globals.UnreportedFile() << "Cube Set Texture\n"; break; } } if(pTexture && pTexture->GetType() == D3D9Base::D3DRTYPE_TEXTURE) { return m_pDevice->SetTexture(Stage, pTexture == 0 ? 0 : pTexture->GetBaseTexture9()); } else { return m_pDevice->SetTexture(Stage, (D3D9Base::IDirect3DBaseTexture9*)pTexture); } } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetTextureStageState(THIS_ DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue) { return m_pDevice->GetTextureStageState(Stage, Type, pValue); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetTextureStageState(THIS_ DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value) { ReportSetTextureStageState(Stage, Type, Value); return m_pDevice->SetTextureStageState(Stage, Type, Value); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetSamplerState(THIS_ DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD* pValue) { return m_pDevice->GetSamplerState(Sampler, Type, pValue); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetSamplerState(THIS_ DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value) { return m_pDevice->SetSamplerState(Sampler, Type, Value); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::ValidateDevice(THIS_ DWORD* pNumPasses) { return m_pDevice->ValidateDevice(pNumPasses); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetPaletteEntries(THIS_ UINT PaletteNumber,CONST PALETTEENTRY* pEntries) { return m_pDevice->SetPaletteEntries(PaletteNumber, pEntries); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetPaletteEntries(THIS_ UINT PaletteNumber,PALETTEENTRY* pEntries) { return m_pDevice->GetPaletteEntries(PaletteNumber, pEntries); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetCurrentTexturePalette(THIS_ UINT PaletteNumber) { return m_pDevice->SetCurrentTexturePalette(PaletteNumber); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetCurrentTexturePalette(THIS_ UINT *PaletteNumber) { return m_pDevice->GetCurrentTexturePalette( PaletteNumber); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetScissorRect(THIS_ CONST RECT* pRect) { return m_pDevice->SetScissorRect(pRect); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetScissorRect(THIS_ RECT* pRect) { return m_pDevice->GetScissorRect(pRect); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetSoftwareVertexProcessing(THIS_ BOOL bSoftware) { return m_pDevice->SetSoftwareVertexProcessing(bSoftware); } STDMETHODIMP_(BOOL) D3D9Wrapper::IDirect3DDevice9::GetSoftwareVertexProcessing(THIS) { return m_pDevice->GetSoftwareVertexProcessing(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetNPatchMode(THIS_ float nSegments) { return m_pDevice->SetNPatchMode(nSegments); } STDMETHODIMP_(float) D3D9Wrapper::IDirect3DDevice9::GetNPatchMode(THIS) { return m_pDevice->GetNPatchMode(); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawPrimitive(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount) { HRESULT hr = S_OK; if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); } hr = m_pDevice->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); if(ReportDrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount)) { if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); m_pDevice->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); } } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawIndexedPrimitive(THIS_ D3DPRIMITIVETYPE Type,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount) { if(PreRenderQuery(Type, primCount)) { return S_OK; } HRESULT hr = S_OK; if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); } hr = m_pDevice->DrawIndexedPrimitive(Type, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount); if(ReportDrawIndexedPrimitive(Type, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount)) { if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); m_pDevice->DrawIndexedPrimitive(Type, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount); } } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) { HRESULT hr = S_OK; if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); } hr = m_pDevice->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride); if(ReportDrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride)) { if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); m_pDevice->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride); } } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawIndexedPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) { HRESULT hr = S_OK; if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); } hr = m_pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); if(ReportDrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride)) { if(g_Globals.UsingNullPixelShader) { m_Overlay.SetNullPixelShader(); m_pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); } } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::ProcessVertices(THIS_ UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer9* pDestBuffer,IDirect3DVertexDeclaration9* pVertexDecl,DWORD Flags) { return m_pDevice->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer->GetVB9(), pVertexDecl, Flags); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateVertexDeclaration(THIS_ CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl) { //g_Globals.UnreportedFile() << "CreateVertexDeclaration\n"; return m_pDevice->CreateVertexDeclaration(pVertexElements, ppDecl); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetVertexDeclaration(THIS_ IDirect3DVertexDeclaration9* pDecl) { if(!SkipSetVertexDeclaration) { if(pDecl != NULL) { D3DVERTEXELEMENT9 Elements[64]; UINT ElementCount = 64; HRESULT hr = pDecl->GetDeclaration(Elements, &ElementCount); if(FAILED(hr)) { g_Globals.ErrorFile() << "GetDeclaration failed\n"; } else if(ElementCount > 0) { ReportSetVertexDeclaration(Elements, ElementCount); } } } return m_pDevice->SetVertexDeclaration(pDecl); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetVertexDeclaration(THIS_ IDirect3DVertexDeclaration9** ppDecl) { return m_pDevice->GetVertexDeclaration(ppDecl); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetFVF(THIS_ DWORD FVF) { ReportSetFVF(FVF); return m_pDevice->SetFVF(FVF); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetFVF(THIS_ DWORD* pFVF) { return m_pDevice->GetFVF(pFVF); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateVertexShader(THIS_ CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader) { HRESULT hr = m_pDevice->CreateVertexShader(pFunction, ppShader); if(!FAILED(hr)) { ReportCreateVertexShader(pFunction, *ppShader); } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetVertexShader(THIS_ IDirect3DVertexShader9* pShader) { ReportSetVertexShader(pShader); return m_pDevice->SetVertexShader(pShader); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetVertexShader(THIS_ IDirect3DVertexShader9** ppShader) { return m_pDevice->GetVertexShader(ppShader); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetVertexShaderConstantF(THIS_ UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) { if(!SkipVertexBufferConstants && !g_Globals.VideoCaptureMode) { ReportSetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } return m_pDevice->SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetVertexShaderConstantF(THIS_ UINT StartRegister,float* pConstantData,UINT Vector4fCount) { return m_pDevice->GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetVertexShaderConstantI(THIS_ UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) { g_Globals.UnreportedFile() << "SetVertexShaderConstantI\n"; return m_pDevice->SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetVertexShaderConstantI(THIS_ UINT StartRegister,int* pConstantData,UINT Vector4iCount) { return m_pDevice->GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetVertexShaderConstantB(THIS_ UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) { g_Globals.UnreportedFile() << "SetVertexShaderConstantB\n"; return m_pDevice->SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetVertexShaderConstantB(THIS_ UINT StartRegister,BOOL* pConstantData,UINT BoolCount) { return m_pDevice->GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetStreamSource(THIS_ UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride) { if(pStreamData != NULL) { if(!SkipSetStreamSource) { ReportSetStreamSource(StreamNumber, pStreamData->GetVB9(), OffsetInBytes, Stride); } return m_pDevice->SetStreamSource(StreamNumber, pStreamData->GetVB9(), OffsetInBytes, Stride); } else { return m_pDevice->SetStreamSource(StreamNumber, NULL, OffsetInBytes, Stride); } } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetStreamSource(THIS_ UINT StreamNumber,IDirect3DVertexBuffer9** ppStreamData,UINT* pOffsetInBytes,UINT* pStride) { g_Globals.ErrorFile() << "GetStreamSource called, duplicate vertex array.\n"; *ppStreamData = NULL; D3D9Base::LPDIRECT3DVERTEXBUFFER9 BaseVB = NULL; HRESULT hr = m_pDevice->GetStreamSource(StreamNumber, &BaseVB, pOffsetInBytes, pStride); if( FAILED(hr) || BaseVB == NULL ) { return hr; } D3D9Wrapper::IDirect3DVertexBuffer9* NewVB = D3D9Wrapper::IDirect3DVertexBuffer9::GetVertexBuffer(BaseVB); if( NewVB == NULL ) { BaseVB->Release(); return E_OUTOFMEMORY; } *ppStreamData = NewVB; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetStreamSourceFreq(THIS_ UINT StreamNumber, UINT FrequencyParameter) { //g_Globals.UnreportedFile() << "SetStreamSourceFreq: " << StreamNumber << ", " << Setting << endl; ReportSetStreamSourceFreq(StreamNumber, FrequencyParameter); return m_pDevice->SetStreamSourceFreq(StreamNumber, FrequencyParameter); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetStreamSourceFreq(THIS_ UINT StreamNumber,UINT* pSetting) { return m_pDevice->GetStreamSourceFreq(StreamNumber, pSetting); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetIndices(THIS_ IDirect3DIndexBuffer9* pIndexData) { if(!SkipSetIndices) { ReportSetIndices(NULL == pIndexData ? NULL : pIndexData->GetIB9()); } return m_pDevice->SetIndices(NULL == pIndexData ? NULL : pIndexData->GetIB9()); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetIndices(THIS_ IDirect3DIndexBuffer9** ppIndexData) { g_Globals.ErrorFile() << "GetIndices called, duplicate index array.\n"; *ppIndexData = NULL; D3D9Base::LPDIRECT3DINDEXBUFFER9 BaseIB = NULL; HRESULT hr = m_pDevice->GetIndices(&BaseIB); if( FAILED(hr) || BaseIB == NULL ) { return hr; } D3D9Wrapper::IDirect3DIndexBuffer9* NewIB = D3D9Wrapper::IDirect3DIndexBuffer9::GetIndexBuffer(BaseIB); if( NewIB == NULL ) { BaseIB->Release(); return E_OUTOFMEMORY; } *ppIndexData = NewIB; return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreatePixelShader(THIS_ CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader) { HRESULT hr = m_pDevice->CreatePixelShader(pFunction, ppShader); if(!FAILED(hr)) { ReportCreatePixelShader(pFunction, *ppShader); } return hr; } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetPixelShader(THIS_ IDirect3DPixelShader9* pShader) { ReportSetPixelShader(pShader); return m_pDevice->SetPixelShader(pShader); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetPixelShader(THIS_ IDirect3DPixelShader9** ppShader) { return m_pDevice->GetPixelShader(ppShader); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetPixelShaderConstantF(THIS_ UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) { ReportSetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); return m_pDevice->SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetPixelShaderConstantF(THIS_ UINT StartRegister,float* pConstantData,UINT Vector4fCount) { return m_pDevice->GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetPixelShaderConstantI(THIS_ UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) { g_Globals.UnreportedFile() << "SetPixelShaderConstantI\n"; return m_pDevice->SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetPixelShaderConstantI(THIS_ UINT StartRegister,int* pConstantData,UINT Vector4iCount) { return m_pDevice->GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::SetPixelShaderConstantB(THIS_ UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) { ReportSetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); return m_pDevice->SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::GetPixelShaderConstantB(THIS_ UINT StartRegister,BOOL* pConstantData,UINT BoolCount) { return m_pDevice->GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawRectPatch(THIS_ UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo) { g_Globals.UnreportedFile() << "DrawRectPatch\n"; return m_pDevice->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DrawTriPatch(THIS_ UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo) { g_Globals.UnreportedFile() << "DrawTriPatch\n"; return m_pDevice->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::DeletePatch(THIS_ UINT Handle) { return m_pDevice->DeletePatch(Handle); } STDMETHODIMP D3D9Wrapper::IDirect3DDevice9::CreateQuery(THIS_ D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery) { //g_Globals.UnreportedFile() << "CreateQuery\n"; HRESULT hr = m_pDevice->CreateQuery(Type, ppQuery); return hr; }
35.073318
273
0.728374
[ "render", "object" ]
2e81546dc4d30e6c24f9e1acf685d4ed572e39d0
15,175
h
C
private/shell/browseui/util.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/browseui/util.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/browseui/util.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#ifndef _UTIL_H_ #define _UTIL_H_ #include <shldispp.h> int IsVK_TABCycler(MSG *pMsg); BOOL IsVK_CtlTABCycler(MSG *pMsg); #ifdef __cplusplus //=--------------------------------------------------------------------------= // allocates a temporary buffer that will disappear when it goes out of scope // NOTE: be careful of that -- make sure you use the string in the same or // nested scope in which you created this buffer. people should not use this // class directly. use the macro(s) below. // class TempBuffer { #ifdef DEBUG const DWORD* _pdwSigniture; const static DWORD s_dummy; #endif public: TempBuffer(ULONG cBytes) { #ifdef DEBUG _pdwSigniture = &s_dummy; #endif m_pBuf = (cBytes <= 120) ? &m_szTmpBuf : LocalAlloc(LMEM_FIXED, cBytes); m_fHeapAlloc = (cBytes > 120); } ~TempBuffer() { if (m_pBuf && m_fHeapAlloc) LocalFree(m_pBuf); } void *GetBuffer() { return m_pBuf; } private: void *m_pBuf; // we'll use this temp buffer for small cases. // char m_szTmpBuf[120]; unsigned m_fHeapAlloc:1; }; #endif // __cplusplus #ifdef __cplusplus extern "C" { #endif //=--------------------------------------------------------------------------= // string helpers. // // given and ANSI String, copy it into a wide buffer. // be careful about scoping when using this macro! // // how to use the below two macros: // // ... // LPSTR pszA; // pszA = MyGetAnsiStringRoutine(); // MAKE_WIDEPTR_FROMANSI(pwsz, pszA); // MyUseWideStringRoutine(pwsz); // ... // // similarily for MAKE_ANSIPTR_FROMWIDE. note that the first param does not // have to be declared, and no clean up must be done. // #define MAKE_WIDEPTR_FROMANSI(ptrname, ansistr) \ long __l##ptrname = (lstrlen(ansistr) + 1) * sizeof(WCHAR); \ TempBuffer __TempBuffer##ptrname(__l##ptrname); \ MultiByteToWideChar(CP_ACP, 0, ansistr, -1, (LPWSTR)__TempBuffer##ptrname.GetBuffer(), __l##ptrname); \ LPWSTR ptrname = (LPWSTR)__TempBuffer##ptrname.GetBuffer() #define MAKE_ANSIPTR_FROMWIDE(ptrname, widestr) \ long __l##ptrname = (lstrlenW(widestr) + 1) * 2 * sizeof(char); \ TempBuffer __TempBuffer##ptrname(__l##ptrname); \ WideCharToMultiByte(CP_ACP, 0, widestr, -1, (LPSTR)__TempBuffer##ptrname.GetBuffer(), __l##ptrname, NULL, NULL); \ LPSTR ptrname = (LPSTR)__TempBuffer##ptrname.GetBuffer() BOOL __cdecl _FormatMessage(LPCWSTR szTemplate, LPWSTR szBuf, UINT cchBuf, ...); HRESULT IUnknown_FileSysChange(IUnknown* punk, DWORD dwEvent, LPCITEMIDLIST* ppidl); HRESULT QueryService_SID_IBandProxy(IUnknown * punkParent, REFIID riid, IBandProxy ** ppbp, void **ppvObj); HRESULT CreateIBandProxyAndSetSite(IUnknown * punkParent, REFIID riid, IBandProxy ** ppbp, void **ppvObj); DWORD GetPreferedDropEffect(IDataObject *pdtobj); HRESULT _SetPreferedDropEffect(IDataObject *pdtobj, DWORD dwEffect); #ifdef DEBUG int SearchDWP(DWORD_PTR *pdwBuf, int cbBuf, DWORD_PTR dwVal); #endif #define REGVALUE_STREAMSA "Streams" #define REGVALUE_STREAMS TEXT(REGVALUE_STREAMSA) #define SZ_REGKEY_TYPEDCMDMRU TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU") #define SZ_REGKEY_TYPEDURLMRU TEXT("Software\\Microsoft\\Internet Explorer\\TypedURLs") #define SZ_REGVAL_MRUENTRY TEXT("url%lu") #define SZ_REGKEY_INETCPL_POLICIES TEXT("Software\\Policies\\Microsoft\\Internet Explorer\\Control Panel") #define SZ_REGVALUE_RESETWEBSETTINGS TEXT("ResetWebSettings") #define SZ_REGKEY_IE_POLICIES TEXT("Software\\Policies\\Microsoft\\Internet Explorer\\Main") #define SZ_REGVALUE_IEREPAIR TEXT("Repair IE Option") #define SZ_REGKEY_ACTIVE_SETUP TEXT("Software\\Microsoft\\Active Setup") #define SZ_REGVALUE_DISABLE_REPAIR TEXT("DisableRepair") #if 0 BOOL IsIERepairOn(); #endif BOOL IsResetWebSettingsEnabled(void); HRESULT GetMRUEntry(HKEY hKey, DWORD dwMRUIndex, LPTSTR pszMRUEntry, DWORD cchMRUEntry, LPITEMIDLIST * ppidl); extern UINT g_cfURL; extern UINT g_cfHIDA; extern UINT g_cfFileDescA; extern UINT g_cfFileDescW; extern UINT g_cfFileContents; extern const CLSID g_clsidNull; // for those that want a NULL clsid. void InitClipboardFormats(); // raymondc's futile attempt to reduce confusion // // EICH_KBLAH = a registry key named blah // EICH_SBLAH = a win.ini section named blah #define EICH_UNKNOWN 0xFFFFFFFF #define EICH_KINET 0x00000002 #define EICH_KINETMAIN 0x00000004 #define EICH_KWIN 0x00000008 #define EICH_KWINPOLICY 0x00000010 #define EICH_KWINEXPLORER 0x00000020 #define EICH_SSAVETASKBAR 0x00000040 #define EICH_SWINDOWMETRICS 0x00000080 #define EICH_SPOLICY 0x00000100 #define EICH_SSHELLMENU 0x00000200 #define EICH_KWINEXPLSMICO 0x00000400 #define EICH_SWINDOWS 0x00000800 DWORD SHIsExplorerIniChange(WPARAM wParam, LPARAM lParam); STDAPI_(HKEY) SHGetExplorerHkey(); #define GEN_DEBUGSTRW(str) ((str) ? (str) : L"<Null Str>") #define GEN_DEBUGSTRA(str) ((str) ? (str) : "<Null Str>") #ifdef UNICODE #define GEN_DEBUGSTR GEN_DEBUGSTRW #else // UNICODE #define GEN_DEBUGSTR GEN_DEBUGSTRA #endif // UNICODE void _InitAppGlobals(); BOOL _InitComCtl32(); void ReleaseStgMediumHGLOBAL(STGMEDIUM *pstg); void* DataObj_GetDataOfType(IDataObject* pdtobj, UINT cfType, STGMEDIUM *pstg); HRESULT RootCreateFromPath(LPCTSTR pszPath, LPITEMIDLIST * ppidl); extern DEFFOLDERSETTINGS g_dfs; STDAPI_(void) SaveDefaultFolderSettings(UINT flags); STDAPI_(void) GetCabState(CABINETSTATE *pcs); //------------------------------------------------------------------------- //*** Reg_GetStrs -- read registry strings into struct fields struct regstrs { LPTSTR name; // registry name int off; // struct offset }; BOOL ViewIDFromViewMode(UINT uViewMode, SHELLVIEWID *pvid); void Reg_GetStrs(HKEY hkey, const struct regstrs *tab, TCHAR *szBuf, int cchBuf, void *pv); void IEPlaySound(LPCTSTR pszSound, BOOL fSysSound); HRESULT DropOnMailRecipient(IDataObject *pdtobj, DWORD grfKeyState); HRESULT SendDocToMailRecipient(LPCITEMIDLIST pidl, UINT uiCodePage, DWORD grfKeyState, IUnknown *pUnkSite); #ifdef DEBUG void Dbg_DumpMenu(LPCTSTR psz, HMENU hmenu); #else #define Dbg_DumpMenu(psz, hmenu) #endif extern const LARGE_INTEGER c_li0; extern BOOL g_fNewNotify; // BUGBUG:: Need to handle two different implementations of SHChangeRegister... typedef ULONG (* PFNSHCHANGENOTIFYREGISTER)(HWND hwnd, int fSources, LONG fEvents, UINT wMsg, int cEntries, SHChangeNotifyEntry *pshcne); typedef BOOL (* PFNSHCHANGENOTIFYDEREGISTER)(unsigned long ulID); ULONG RegisterNotify(HWND hwnd, UINT nMsg, LPCITEMIDLIST pidl, DWORD dwEvents, UINT uFlags, BOOL fRecursive); STDAPI_(void) DetectRegisterNotify(void); int PropBag_ReadInt4(IPropertyBag* pPropBag, LPWSTR pszKey, int iDefault); HINSTANCE HinstShdocvw(); HINSTANCE HinstShell32(); HRESULT CreateFromRegKey(LPCTSTR pszKey, LPCTSTR pszValue, REFIID riid, void **ppv); extern const VARIANT c_vaEmpty; // // BUGBUG: Remove this ugly const to non-const casting if we can // figure out how to put const in IDL files. // #define PVAREMPTY ((VARIANT*)&c_vaEmpty) BOOL ILIsBrowsable(LPCITEMIDLIST pidl, BOOL *pfISFolder); STDAPI_(LPITEMIDLIST) IEILCreate(UINT cbSize); BOOL GetInfoTipEx(IShellFolder* psf, DWORD dwFlags, LPCITEMIDLIST pidl, LPTSTR pszText, int cchTextMax); BOOL IsBrowsableShellExt(LPCITEMIDLIST pidl); void OpenFolderPidl(LPCITEMIDLIST pidl); void OpenFolderPath(LPCTSTR pszPath); int WINAPI _SHHandleUpdateImage( LPCITEMIDLIST pidlExtra ); extern BOOL g_fICWCheckComplete; BOOL CheckSoftwareUpdateUI( HWND hwndOwner, IShellBrowser *pisb ); BOOL CheckRunICW(LPCTSTR); #ifdef DEBUG LPTSTR Dbg_PidlStr(LPCITEMIDLIST pidl, LPTSTR pszBuffer, DWORD cchBufferSize); #else // DEBUG #define Dbg_PidlStr(pidl, pszBuffer, cchBufferSize) ((LPTSTR)NULL) #endif // DEBUG HRESULT SavePidlAsLink(IUnknown* punkSite, IStream *pstm, LPCITEMIDLIST pidl); HRESULT LoadPidlAsLink(IUnknown* punkSite, IStream *pstm, LPITEMIDLIST *ppidl); #define ADJUST_TO_WCHAR_POS 0 #define ADJUST_TO_TCHAR_POS 1 int AdjustECPosition(char *psz, int iPos, int iType); HRESULT ContextMenu_GetCommandStringVerb(LPCONTEXTMENU pcm, UINT idCmd, LPTSTR pszVerb, int cchVerb); BOOL ExecItemFromFolder(HWND hwnd, LPCSTR pszVerb, IShellFolder* psf, LPCITEMIDLIST pidlItem); // See if a give URL is actually present as an installed entry STDAPI_(BOOL) CallCoInternetQueryInfo(LPCTSTR pszURL, QUERYOPTION QueryOption); #define UrlIsInstalledEntry(pszURL) CallCoInternetQueryInfo(pszURL, QUERY_IS_INSTALLEDENTRY) BOOL IsSubscribableA(LPCSTR pszUrl); BOOL IsSubscribableW(LPCWSTR pwzUrl); HRESULT IURLQualifyW(IN LPCWSTR pcwzURL, DWORD dwFlags, OUT LPWSTR pwzTranslatedURL, LPBOOL pbWasSearchURL, LPBOOL pbWasCorrected); #ifdef UNICODE #define IsSubscribable IsSubscribableW #define IURLQualifyT IURLQualifyW #else // UNICODE #define IsSubscribable IsSubscribableA #define IURLQualifyT IURLQualifyA #endif // UNICODE #define IURLQualifyA IURLQualify HDPA GetSortedIDList(LPITEMIDLIST pidl); void FreeSortedIDList(HDPA hdpa); //#define StopWatch StopWatchT int GetColorComponent(LPSTR *ppsz); COLORREF RegGetColorRefString( HKEY hkey, LPTSTR RegValue, COLORREF Value); LRESULT SetHyperlinkCursor(IShellFolder* pShellFolder, LPCITEMIDLIST pidl); HRESULT StrCmpIWithRoot(LPCTSTR szDispNameIn, BOOL fTotalStrCmp, LPTSTR * ppszCachedRoot); STDAPI UpdateSubscriptions(); enum TRI_STATE { TRI_UNKNOWN = 2, TRI_TRUE = TRUE, TRI_FALSE = FALSE }; LONG OpenRegUSKey(LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); HWND GetTrayWindow(); #define STREAMSIZE_UNKNOWN 0xFFFFFFFF HRESULT SaveStreamHeader(IStream *pstm, DWORD dwSignature, DWORD dwVersion, DWORD dwSize); HRESULT LoadStreamHeader(IStream *pstm, DWORD dwSignature, DWORD dwStartVersion, DWORD dwEndVersion, DWORD * pdwSize, DWORD * pdwVersionOut); // _FrameTrack flags #define TRACKHOT 0x0001 #define TRACKEXPAND 0x0002 #define TRACKNOCHILD 0x0004 void FrameTrack(HDC hdc, LPRECT prc, UINT uFlags); #ifdef __cplusplus //+------------------------------------------------------------------------- // This function scans the document for the given HTML tag and returns the // result in a collection. //-------------------------------------------------------------------------- interface IHTMLDocument2; interface IHTMLElementCollection; HRESULT GetDocumentTags(IHTMLDocument2* pHTMLDocument, LPOLESTR pszTagName, IHTMLElementCollection** ppTagsCollection); // CMenuList: a small class that tracks whether a given hmenu belongs // to the frame or the object, so the messages can be // dispatched correctly. class CMenuList { public: CMenuList(void); ~CMenuList(void); void Set(HMENU hmenuShared, HMENU hmenuFrame); void AddMenu(HMENU hmenu); void RemoveMenu(HMENU hmenu); BOOL IsObjectMenu(HMENU hmenu); #ifdef DEBUG void Dump(LPCTSTR pszMsg); #endif private: HDSA _hdsa; }; }; #endif #ifdef __cplusplus class CAssociationList { public: // // WARNING: We don't want a destructor on this because then it can't // be a global object without bringing in the CRT main. So // we can't free the DSA in a destructor. The DSA memory will be // freed by the OS when the process detaches. If this // class is ever dynamically allocated (ie not a static) then // we will need to free the DSA. // // ~CAssociationList(); BOOL Add(DWORD dwKey, LPVOID lpData); void Delete(DWORD dwKey); HRESULT Find(DWORD dwKey, LPVOID* ppData); protected: int FindEntry(DWORD dwKey); struct ASSOCDATA { DWORD dwKey; LPVOID lpData; }; HDSA _hdsa; }; #endif STDAPI_(void) DrawMenuItem(DRAWITEMSTRUCT* pdi, LPCTSTR lpszMenuText, UINT iIcon); STDAPI_(LRESULT) MeasureMenuItem(MEASUREITEMSTRUCT *lpmi, LPCTSTR lpszMenuText); void FireEventSz(LPCTSTR szEvent); #ifndef UNICODE void FireEventSzW(LPCWSTR szEvent); #else #define FireEventSzW FireEventSz #endif // comctl32.dll doesn't really implement Str_SetPtrW. STDAPI_(BOOL) Str_SetPtrPrivateW(WCHAR * UNALIGNED * ppwzCurrent, LPCWSTR pwzNew); // This function is similar to Str_SetPtrPrivateW but it is compatible with API's // that use LocalAlloc for string memory STDAPI_(BOOL) SetStr(WCHAR * UNALIGNED * ppwzCurrent, LPCWSTR pwzNew); // Review chrisny: this can be moved into an object easily to handle generic droptarget, dropcursor // , autoscrool, etc. . . STDAPI_(void) _DragEnter(HWND hwndTarget, const POINTL ptStart, IDataObject *pdtObject); STDAPI_(void) _DragMove(HWND hwndTarget, const POINTL ptStart); #define Str_SetPtrW Str_SetPtrPrivateW STDAPI_(BOOL) _MenuCharMatch(LPCTSTR lpsz, TCHAR ch, BOOL fIgnoreAmpersand); STDAPI GetNavigateTarget(IShellFolder *psf, LPCITEMIDLIST pidl, LPITEMIDLIST *ppidl, DWORD *pdwAttribs); STDAPI_(BOOL) DoDragDropWithInternetShortcut(IOleCommandTarget *pcmdt, LPITEMIDLIST pidl, HWND hwnd); STDAPI_(BSTR) SysAllocStringA(LPCSTR); #ifdef UNICODE #define SysAllocStringT(psz) SysAllocString(psz) #else #define SysAllocStringT(psz) SysAllocStringA(psz) #endif void EnableOKButton(HWND hDlg, int id, LPTSTR pszText); BOOL IsExplorerWindow(HWND hwnd); BOOL IsFolderWindow(HWND hwnd); BOOL WasOpenedAsBrowser(IUnknown *punkSite); STDAPI_(LPCITEMIDLIST) VariantToConstIDList(const VARIANT *pv); STDAPI_(LPITEMIDLIST) VariantToIDList(const VARIANT *pv); STDAPI VariantToBuffer(const VARIANT* pvar, void *pv, UINT cb); STDAPI VariantToGUID(VARIANT *pvar, LPGUID pguid); STDAPI InitVariantFromBuffer(VARIANT *pvar, const void *pv, UINT cb); STDAPI_(BOOL) InitVariantFromIDList(VARIANT* pvar, LPCITEMIDLIST pidl); STDAPI_(BOOL) InitVariantFromGUID(VARIANT *pvar, GUID *pguid); STDAPI_(void) InitVariantFromIDListInProc(VARIANT *pvar, LPCITEMIDLIST pidl); STDAPI_(HWND) GetTopLevelAncestor(HWND hWnd); STDAPI SHNavigateToFavorite(IShellFolder* psf, LPCITEMIDLIST pidl, IUnknown* punkSite, DWORD dwFlags); STDAPI SHGetTopBrowserWindow(IUnknown* punk, HWND* phwnd); STDAPI_(void) UpdateButtonArray(TBBUTTON *ptbDst, const TBBUTTON *ptbSrc, int ctb, LONG_PTR lStrOffset); STDAPI_(BOOL) DoesAppWantUrl(LPCTSTR pszCmdLine); STDAPI SHCreateThreadRef(LONG *pcRef, IUnknown **ppunk); BOOL ILIsFolder(LPCITEMIDLIST pidl); HRESULT URLToCacheFile(LPCWSTR pszUrl, LPWSTR pszFile, int cchFile); #ifdef DEBUG void DebugDumpPidl(DWORD dwDumpFlag, LPTSTR pszOutputString, LPCITEMIDLIST pidl); #else #define DebugDumpPidl(p, q, w) #endif STDAPI_(LPITEMIDLIST) SafeILClone(LPCITEMIDLIST pidl); #define ILClone SafeILClone #endif // _UTIL_H_
34.805046
142
0.721647
[ "object" ]
2e8444aac87a46b62335d4d572b6b09a76a05434
6,056
c
C
trans/src/hppa/code_here.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
trans/src/hppa/code_here.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
trans/src/hppa/code_here.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2011, The TenDRA Project. * Copyright 1997, United Kingdom Secretary of State for Defence. * * See doc/copyright/ for the full copyright terms. */ /* * This contains procedures :- * * regofval, fregofval: to see if an exp is a load_tag that has been * allocated to a register. * * regoperand, freoperand: to evaluate an exp into a register using make_code * * code_here: calls make_code and ensures that any internal * exit labels are tied up after the call * * The procedures regoperand and fregoperand evaluate their exp parameter * into a single register using make_code. This register is returned. * An initial test with regofval checks to see if the exp is already * in a register. */ #include <assert.h> #include <stdio.h> #include <shared/check.h> #include <local/ash.h> #include <tdf/shape.h> #include <tdf/tag.h> #include <main/print.h> #include <construct/installtypes.h> #include <construct/dec.h> #include <construct/ash.h> #include <construct/exp.h> #include "procrec.h" #include "addr.h" #include "labels.h" #include "make_code.h" #include "bits.h" #include "locate.h" #include "regexps.h" #include "reg.h" #include "inst_fmt.h" #include "hppains.h" #include "special.h" #include "regable.h" #include "guard.h" #include "move.h" #include "code_here.h" /* * The procedure regofval checks to see if an exp is a load_tag that has * been allocated into a fixpnt register and if so return it or else R_NO_REG. */ int regofval(exp e) { exp dc = child(e); if (e->tag == name_tag && dc->tag == ident_tag) /* ident tag */ { if ((props(dc) & defer_bit) != 0) { return regofval(child(dc)); } if ((props(dc) & inreg_bits) != 0) { return isvar(dc) ? (-no(dc)) : (no(dc)); } return R_NO_REG; } else if ( (e->tag == val_tag && no(e) == 0) #if 0 || e->tag == clear_tag || e->tag== top_tag #endif ) { return 0; } else { return R_NO_REG; } } static int fregofval(exp e) { exp dc = child(e); if (e->tag == name_tag && dc->tag == ident_tag) { if ((props(dc) & infreg_bits) != 0) { return no(dc); } return R_NO_REG; } else { return R_NO_REG; } } /* calls make_code and tie up any internal exit labels */ static int make_code_here(exp e, space sp, where dest) { makeans mka; mka = make_code(e, sp, dest, 0); if (mka.lab != 0) { clear_all(); outlab("L$$",mka.lab); } return mka.regmove; } /* return reg if 'e' e can easily go to one reg only */ static int is_reg_operand(exp e, space sp) { int x; ans aa; UNUSED(sp); x = regofval(e); if (x >= 0 && x < R_NO_REG) return x; /* x is a register for e */ if (e->tag == cont_tag) { x = regofval(child(e)); if (x < 0) return -x; } aa = iskept(e); if (discrim ( aa ) == inreg && regalt(aa) != 0) { /* the same expression has already been * evaluated into a reg */ return regalt(aa); } if (discrim ( aa ) == notinreg) { instore is; is = insalt(aa); if (is.adval && is.b.offset == 0) { int r = is.b.base; /* the same expression has already been evaluated into a reg */ return r; } } return R_NO_REG; /* exprssion can go to many regs just as easily */ } int reg_operand(exp e, space sp) { int reg; reg = is_reg_operand(e, sp); if (reg == R_NO_REG || reg == GR0) { /* allow make_code_here to evaluate e into reg of its choice */ ans aa; where w; reg = -1; setsomeregalt(aa, &reg); w.answhere = aa; w.ashwhere = ashof(sh(e)); make_code_here(e, sp, w); assert(reg!=-1); keepreg(e, reg); return reg; } else { /* e was found easily in a reg */ assert(IS_FIXREG(reg)); return reg; } } /* like reg_operand(), but to specified reg */ void reg_operand_here(exp e, space sp, int this_reg) { int reg; assert(IS_FIXREG(this_reg) && this_reg != GR0); /* variable fix reg */ reg = is_reg_operand(e, sp); if (reg == R_NO_REG || reg == GR0) { /* evaluate to this_reg */ where w; w.ashwhere = ashof(sh(e)); setregalt(w.answhere, this_reg); make_code_here(e, sp, w); } else { /* e was found easily in a reg, move to this_reg if needed */ assert(IS_FIXREG(reg)); if (reg != this_reg) rr_ins(i_copy,reg,this_reg); } keepreg(e, this_reg); } int freg_operand(exp e, space sp, int reg) { int x = fregofval(e); ans aa; where w; freg fr; w.ashwhere = ashof(sh(e)); fr.dble = (w.ashwhere.ashsize == 64) ? 1 : 0; if (x >= 0 && x < R_NO_REG) { return x; } if (e->tag == cont_tag) { x = fregofval(child(e)); if (x < R_NO_REG) { return x; } } else if (e->tag == apply_tag) { fr.fr = R_FR4; setfregalt(aa, fr); asm_comment("freg_operand: call of float point result proc"); w.answhere = aa; /* w.ashwhere already correctly set up above */ make_code(e, sp, w, 0); return R_FR4; /* float point proc calls give result in %fr4 */ } aa = iskept(e); if (discrim ( aa ) == infreg) { /* e already evaluated in fl reg */ return regalt(aa) /* cheat */ ; } fr.fr = reg; setfregalt(aa, fr); w.answhere = aa; make_code_here(e, sp, w); keepexp(e, aa); return reg; } /* * The procedure code_here calls make_code and ensures that * any internal exit labels are tied up after the call. * Optimises the case where the value of 'e' is in a register. */ int code_here(exp e, space sp, where dest) { int reg; reg = is_reg_operand(e, sp); if (reg == R_NO_REG || reg == GR0) { return make_code_here(e, sp, dest); } else { /* +++ do in make_code maybe */ /* +++ for reals as well */ /* e was found easily in a reg */ ans aa; assert(IS_FIXREG(reg)); assert(ashof(sh(e)).ashsize <= 32); setregalt(aa, reg); move(aa, dest, guardreg(reg, sp).fixed, 1); return reg; } }
17.970326
78
0.590819
[ "shape" ]
2e84db935b326e94253953afcac11a8bfddafe6f
2,242
c
C
Pratica 1/Leonardo Baptistella/1/ex_1.c
Amari9/GitNadir
45b83fe32538ecbdf1ad75b7565d5c2108665b5e
[ "MIT" ]
null
null
null
Pratica 1/Leonardo Baptistella/1/ex_1.c
Amari9/GitNadir
45b83fe32538ecbdf1ad75b7565d5c2108665b5e
[ "MIT" ]
null
null
null
Pratica 1/Leonardo Baptistella/1/ex_1.c
Amari9/GitNadir
45b83fe32538ecbdf1ad75b7565d5c2108665b5e
[ "MIT" ]
null
null
null
/* This code will be used to calculate the sum, multiplication, division and average for real numbers. Author: Leonardo Baptistella 10/10/2018 */ #include <stdio.h> //vector float num[2]; float pesos[2]; //functions float soma(float *num); float mult(float *num); float div(float *num); float med(float *num, float *pesos); float ins_v3(float *num); //used to insert three values on vector float ins_v2(float *num); //used to insert two values on vector float ins_p(float *pesos); //used to insert three values on vector int main (void){ int op=0; float res=0; printf("[1](Sum)\n[2](Multiplication)\n[3](Division)\n[4](Average)\nChoose an operation:"); scanf("%d",&op); if (op==1){ ins_v3(num); res=soma(num); printf("Result: %f\n",res); } if (op==2){ ins_v3(num); res=mult(num); printf("Result: %f\n",res); } if (op==3){ ins_v2(num); res=div(num); printf("Result: %f\n",res); } if (op==4){ ins_v3(num); ins_p(pesos); res=med(num,pesos); printf("Result: %f\n",res); } return 0; } //this function insert three values on vector float ins_v3 (float *num){ for (int i = 0; i < 3; i++){ printf("Insert a number: "); scanf("%f",&num[i]); } } //this function insert three weights on vector float ins_p (float *pesos){ for (int i = 0; i < 3; i++){ printf("Insert a weight: "); scanf("%f",&pesos[i]); } } //this function insert two values on vector float ins_v2 (float *num){ for (int i = 0; i < 2; i++){ printf("Insert a number: "); scanf("%f",&num[i]); } } //this function return the sum of three numbers float soma(float *n){ return (num[0]+num[1]+num[2]); } //this function return the multiplication of three numbers float mult(float *n){ return ((num[0])*(num[1])*(num[2])); } //this function return the division of two numbers float div(float *n){ if (n[1] != 0){ return (num[0]/num[1]); }else{ printf("Does not exist!!!\n"); return(0); } } //this function return the poderated average of three numbers float med(float *num, float *pesos){ float sum = 0; for (int i = 0; i < 3; ++i) { printf("peso %f\n",pesos[i] );printf("num %f\n",num[i] ); } return (((num[0]*(pesos[0]))+(num[1]*(pesos[1]))+(num[2]*(pesos[2])))/(pesos[0]+pesos[1]+pesos[2])); }
20.198198
102
0.623996
[ "vector" ]
2e866dcfc177b06756cc7f2d5b1b13cc7941fc6b
3,687
h
C
optimize.h
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
optimize.h
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
optimize.h
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
// Utility functions for optimizing multi-dimensional nonlinear functions. #ifndef OPTIMIZE_H_ #define OPTIMIZE_H_ #include <math.h> #include <stdio.h> #include <vector> namespace pik { namespace optimize { template <typename T> std::vector<T> operator+(const std::vector<T>& x, const std::vector<T>& y) { std::vector<T> z(x.size()); for (int i = 0; i < x.size(); ++i) { z[i] = x[i] + y[i]; } return z; } template <typename T> std::vector<T> operator-(const std::vector<T>& x, const std::vector<T>& y) { std::vector<T> z(x.size()); for (int i = 0; i < x.size(); ++i) { z[i] = x[i] - y[i]; } return z; } template <typename T> std::vector<T> operator*(T v, const std::vector<T>& x) { std::vector<T> y(x.size()); for (int i = 0; i < x.size(); ++i) { y[i] = v * x[i]; } return y; } template <typename T> T operator*(const std::vector<T>& x, const std::vector<T>& y) { T r = 0.0; for (int i = 0; i < x.size(); ++i) { r += x[i] * y[i]; } return r; } // Implementation of the Scaled Conjugate Gradient method described in the // following paper: // Moller, M. "A Scaled Conjugate Gradient Algorithm for Fast Supervised // Learning", Neural Networks, Vol. 6. pp. 525-533, 1993 // http://sci2s.ugr.es/keel/pdf/algorithm/articulo/moller1990.pdf // // The Function template parameter is a class that has the following method: // // // Returns the value of the function at point w and sets *df to be the // // negative gradient vector of the function at point w. // double Compute(const vector<double>& w, vector<double>* df) const; // // Returns a vector w, such that |df(w)| < grad_norm_threshold. template<typename T, typename Function> std::vector<T> OptimizeWithScaledConjugateGradientMethod( const Function& f, const std::vector<T>& w0, const T grad_norm_threshold, int max_iters) { const int n = w0.size(); const T rsq_threshold = grad_norm_threshold * grad_norm_threshold; const T sigma0 = static_cast<T>(0.0001); T lambda = static_cast<T>(0.000001); std::vector<T> w(w0); std::vector<T> p(n); std::vector<T> r(n); T fw = f.Compute(w, &r); T rsq = r * r; T psq = rsq; T mu = rsq; p = r; for (int k = 1; rsq > rsq_threshold; ++k) { if (max_iters > 0 && k > max_iters) break; T sigma = sigma0 / sqrt(psq); std::vector<T> r2(n); std::vector<T> w2 = w + (sigma * p); f.Compute(w2, &r2); T delta = (mu - (p * r2)) / sigma; T delta1 = delta + lambda * psq; if (delta1 <= 0) { lambda = -2.0 * delta / psq; delta1 = delta + lambda * psq; } bool success = true; T alpha; T fw1; T Delta; std::vector<T> w1(n); std::vector<T> r1(n); do { alpha = mu / delta1; w1 = w + (alpha * p); fw1 = f.Compute(w1, &r1); Delta = 2 * (fw - fw1) / (mu * alpha); success = (fw1 <= fw); if (!success) { lambda += delta1 * (1 - Delta) / psq; delta1 = delta + lambda * psq; } } while (!success); T r1sq = r1 * r1; T beta = k % n == 0 ? 0.0 : (r1sq - (r1 * r)) / mu; #if SCG_DEBUG printf("Step %3d fw=%10.2f |dfw|=%7.3f |p|=%6.2f " "delta=%9.6f lambda=%6.4f mu=%8.4f alpha=%8.4f " "beta=%5.3f Delta=%5.3f\n", k, fw, sqrt(rsq), sqrt(psq), delta, lambda, mu, alpha, beta, Delta); #endif if (Delta >= 0.75) { lambda *= 0.25; } else if (Delta < 0.25) { lambda += delta1 * (1 - Delta) / psq; } w = w1; fw = fw1; r = r1; rsq = r1sq; p = r + (beta * p); psq = p * p; mu = p * r; } return w; } } // namespace optimize } // namespace pik #endif // OPTIMIZE_H_
25.427586
76
0.564416
[ "vector", "3d" ]
2e8ab5c4b5a686c6ddd80e3f4b464a50a2e311d6
2,393
h
C
atomic.h
tstullich/redner
aaae9f1dee97173fc409ceb0941966d3c2d2feb2
[ "MIT" ]
2
2021-06-04T13:27:44.000Z
2022-03-16T06:21:15.000Z
atomic.h
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
null
null
null
atomic.h
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
null
null
null
#pragma once #include "redner.h" #include "vector.h" #include "matrix.h" // Portable atomic operations that works on both CPU and GPU // Partly inspired by https://github.com/mbitsnbites/atomic #if defined(USE_MSVC_INTRINSICS) #include "atomic_msvc.h" #endif DEVICE inline int atomic_increment(int *addr) { #ifdef __CUDA_ARCH__ return atomicAdd(addr, 1) + 1; #else #if defined(USE_GCC_INTRINSICS) return __atomic_add_fetch(addr, 1, __ATOMIC_SEQ_CST); #elif defined(USE_MSVC_INTRINSICS) return atomic::msvc::interlocked<int>::increment(addr); #else assert(false); return 0; #endif #endif } template <typename T0, typename T1> DEVICE inline T0 atomic_add(T0 &target, T1 source) { #ifdef __CUDA_ARCH__ return atomicAdd(&target, (T0)source); #else T0 old_val; T0 new_val; do { old_val = target; new_val = old_val + source; #if defined(USE_GCC_INTRINSICS) } while (!__atomic_compare_exchange(&target, &old_val, &new_val, true, std::memory_order::memory_order_seq_cst, std::memory_order::memory_order_seq_cst)); #elif defined(USE_MSVC_INTRINSICS) } while(old_val != atomic::msvc::interlocked<T0>::compare_exchange(&target, new_val, old_val)); #else assert(false); } while(false); #endif return old_val; #endif } template <typename T0, typename T1> DEVICE inline T0 atomic_add(T0 *target, T1 source) { return atomic_add(*target, source); } template <typename T0, typename T1> DEVICE inline void atomic_add(T0 *target, const TVector2<T1> &source) { atomic_add(target[0], (T0)source[0]); atomic_add(target[1], (T0)source[1]); } template <typename T0, typename T1> DEVICE inline void atomic_add(T0 *target, const TVector3<T1> &source) { atomic_add(target[0], (T0)source[0]); atomic_add(target[1], (T0)source[1]); atomic_add(target[2], (T0)source[2]); } template <typename T0, typename T1> DEVICE inline void atomic_add(T0 *target, const TMatrix3x3<T1> &source) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { atomic_add(target[3 * i + j], (T0)source(i, j)); } } } template <typename T0, typename T1> DEVICE inline void atomic_add(T0 *target, const TMatrix4x4<T1> &source) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { atomic_add(target[4 * i + j], (T0)source(i, j)); } } }
25.189474
99
0.665692
[ "vector" ]
2e8abc6e54abfc00d3e64638ae3109f093c39ff1
7,376
h
C
3rdParty/V8/v5.7.492.77/src/debug/debug-interface.h
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
1
2019-08-11T04:06:49.000Z
2019-08-11T04:06:49.000Z
3rdParty/V8/v5.7.492.77/src/debug/debug-interface.h
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
null
null
null
3rdParty/V8/v5.7.492.77/src/debug/debug-interface.h
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
1
2021-07-12T06:29:34.000Z
2021-07-12T06:29:34.000Z
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_DEBUG_DEBUG_INTERFACE_H_ #define V8_DEBUG_DEBUG_INTERFACE_H_ #include <functional> #include "include/v8-debug.h" #include "include/v8-util.h" #include "include/v8.h" #include "src/debug/interface-types.h" namespace v8 { namespace debug { /** * An event details object passed to the debug event listener. */ class EventDetails : public v8::Debug::EventDetails { public: /** * Event type. */ virtual v8::DebugEvent GetEvent() const = 0; /** * Access to execution state and event data of the debug event. Don't store * these cross callbacks as their content becomes invalid. */ virtual Local<Object> GetExecutionState() const = 0; virtual Local<Object> GetEventData() const = 0; /** * Get the context active when the debug event happened. Note this is not * the current active context as the JavaScript part of the debugger is * running in its own context which is entered at this point. */ virtual Local<Context> GetEventContext() const = 0; /** * Client data passed with the corresponding callback when it was * registered. */ virtual Local<Value> GetCallbackData() const = 0; virtual ~EventDetails() {} }; /** * Debug event callback function. * * \param event_details object providing information about the debug event * * A EventCallback does not take possession of the event data, * and must not rely on the data persisting after the handler returns. */ typedef void (*EventCallback)(const EventDetails& event_details); bool SetDebugEventListener(Isolate* isolate, EventCallback that, Local<Value> data = Local<Value>()); /** * Debugger is running in its own context which is entered while debugger * messages are being dispatched. This is an explicit getter for this * debugger context. Note that the content of the debugger context is subject * to change. The Context exists only when the debugger is active, i.e. at * least one DebugEventListener or MessageHandler is set. */ Local<Context> GetDebugContext(Isolate* isolate); /** * Run a JavaScript function in the debugger. * \param fun the function to call * \param data passed as second argument to the function * With this call the debugger is entered and the function specified is called * with the execution state as the first argument. This makes it possible to * get access to information otherwise not available during normal JavaScript * execution e.g. details on stack frames. Receiver of the function call will * be the debugger context global object, however this is a subject to change. * The following example shows a JavaScript function which when passed to * v8::Debug::Call will return the current line of JavaScript execution. * * \code * function frame_source_line(exec_state) { * return exec_state.frame(0).sourceLine(); * } * \endcode */ // TODO(dcarney): data arg should be a MaybeLocal MaybeLocal<Value> Call(Local<Context> context, v8::Local<v8::Function> fun, Local<Value> data = Local<Value>()); /** * Enable/disable LiveEdit functionality for the given Isolate * (default Isolate if not provided). V8 will abort if LiveEdit is * unexpectedly used. LiveEdit is enabled by default. */ void SetLiveEditEnabled(Isolate* isolate, bool enable); // Schedule a debugger break to happen when JavaScript code is run // in the given isolate. void DebugBreak(Isolate* isolate); // Remove scheduled debugger break in given isolate if it has not // happened yet. void CancelDebugBreak(Isolate* isolate); /** * Returns array of internal properties specific to the value type. Result has * the following format: [<name>, <value>,...,<name>, <value>]. Result array * will be allocated in the current context. */ MaybeLocal<Array> GetInternalProperties(Isolate* isolate, Local<Value> value); enum ExceptionBreakState { NoBreakOnException = 0, BreakOnUncaughtException = 1, BreakOnAnyException = 2 }; /** * Defines if VM will pause on exceptions or not. * If BreakOnAnyExceptions is set then VM will pause on caught and uncaught * exception, if BreakOnUncaughtException is set then VM will pause only on * uncaught exception, otherwise VM won't stop on any exception. */ void ChangeBreakOnException(Isolate* isolate, ExceptionBreakState state); enum StepAction { StepOut = 0, // Step out of the current function. StepNext = 1, // Step to the next statement in the current function. StepIn = 2, // Step into new functions invoked or the next statement // in the current function. StepFrame = 3 // Step into a new frame or return to previous frame. }; void PrepareStep(Isolate* isolate, StepAction action); void ClearStepping(Isolate* isolate); /** * Out-of-memory callback function. * The function is invoked when the heap size is close to the hard limit. * * \param data the parameter provided during callback installation. */ typedef void (*OutOfMemoryCallback)(void* data); void SetOutOfMemoryCallback(Isolate* isolate, OutOfMemoryCallback callback, void* data); /** * Native wrapper around v8::internal::Script object. */ class Script { public: v8::Isolate* GetIsolate() const; ScriptOriginOptions OriginOptions() const; bool WasCompiled() const; int Id() const; int LineOffset() const; int ColumnOffset() const; std::vector<int> LineEnds() const; MaybeLocal<String> Name() const; MaybeLocal<String> SourceURL() const; MaybeLocal<String> SourceMappingURL() const; MaybeLocal<Value> ContextData() const; MaybeLocal<String> Source() const; bool IsWasm() const; bool GetPossibleBreakpoints(const debug::Location& start, const debug::Location& end, std::vector<debug::Location>* locations) const; /** * script parameter is a wrapper v8::internal::JSObject for * v8::internal::Script. * This function gets v8::internal::Script from v8::internal::JSObject and * wraps it with DebugInterface::Script. * Returns empty local if not called with a valid wrapper of * v8::internal::Script. */ static MaybeLocal<Script> Wrap(Isolate* isolate, v8::Local<v8::Object> script); private: int GetSourcePosition(const debug::Location& location) const; }; // Specialization for wasm Scripts. class WasmScript : public Script { public: static WasmScript* Cast(Script* script); int NumFunctions() const; int NumImportedFunctions() const; debug::WasmDisassembly DisassembleFunction(int function_index) const; }; void GetLoadedScripts(Isolate* isolate, PersistentValueVector<Script>& scripts); MaybeLocal<UnboundScript> CompileInspectorScript(Isolate* isolate, Local<String> source); typedef std::function<void(debug::PromiseDebugActionType type, int id, void* data)> AsyncTaskListener; void SetAsyncTaskListener(Isolate* isolate, AsyncTaskListener listener, void* data); int EstimatedValueSize(Isolate* isolate, v8::Local<v8::Value> value); } // namespace debug } // namespace v8 #endif // V8_DEBUG_DEBUG_INTERFACE_H_
33.680365
80
0.713937
[ "object", "vector" ]
2e8aec2f16d7d8b46d44edc07ef50771022be34f
661
h
C
SoftwareEngineering/feneley_project4/TennisModel.h
mikefeneley/school
5156f4537ca76782e7ad6df3c5ffe7b9fb5038da
[ "MIT" ]
1
2021-04-21T16:54:04.000Z
2021-04-21T16:54:04.000Z
SoftwareEngineering/feneley_project4_part1/TennisModel.h
mikefeneley/school
5156f4537ca76782e7ad6df3c5ffe7b9fb5038da
[ "MIT" ]
null
null
null
SoftwareEngineering/feneley_project4_part1/TennisModel.h
mikefeneley/school
5156f4537ca76782e7ad6df3c5ffe7b9fb5038da
[ "MIT" ]
null
null
null
#ifndef TENNIS_MODEL #define TENNIS_MODEL #include <QRect> #include <QPoint> #include <math.h> #include "Constants.h" /** * TennisModel.h * * Acts as a model for a game of virtual tennis in * the MVC pattern. * */ class TennisModel { public: TennisModel(); void ResetBall(); void InvertX(); void InvertY(); int Player1_Score(); int Player2_Score(); double BallX(); double BallY(); double X_Direction(); double Y_Direction(); public: QRect player1; QRect player2; QPointF ball; int player1_score; int player2_score; double x_direction; double y_direction; }; #endif
15.022727
51
0.635401
[ "model" ]
2e8e2255752f19dd5a34df471acc9c385a9b3926
4,499
h
C
ess/include/alibabacloud/ess/model/CreateScalingRuleRequest.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ess/include/alibabacloud/ess/model/CreateScalingRuleRequest.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ess/include/alibabacloud/ess/model/CreateScalingRuleRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_ESS_MODEL_CREATESCALINGRULEREQUEST_H_ #define ALIBABACLOUD_ESS_MODEL_CREATESCALINGRULEREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/ess/EssExport.h> namespace AlibabaCloud { namespace Ess { namespace Model { class ALIBABACLOUD_ESS_EXPORT CreateScalingRuleRequest : public RpcServiceRequest { public: struct StepAdjustment { float metricIntervalLowerBound; float metricIntervalUpperBound; int scalingAdjustment; }; public: CreateScalingRuleRequest(); ~CreateScalingRuleRequest(); std::vector<StepAdjustment> getStepAdjustment()const; void setStepAdjustment(const std::vector<StepAdjustment>& stepAdjustment); std::string getScalingGroupId()const; void setScalingGroupId(const std::string& scalingGroupId); bool getDisableScaleIn()const; void setDisableScaleIn(bool disableScaleIn); int getInitialMaxSize()const; void setInitialMaxSize(int initialMaxSize); std::string getAccessKeyId()const; void setAccessKeyId(const std::string& accessKeyId); std::string getScalingRuleName()const; void setScalingRuleName(const std::string& scalingRuleName); int getCooldown()const; void setCooldown(int cooldown); std::string getPredictiveValueBehavior()const; void setPredictiveValueBehavior(const std::string& predictiveValueBehavior); int getScaleInEvaluationCount()const; void setScaleInEvaluationCount(int scaleInEvaluationCount); std::string getScalingRuleType()const; void setScalingRuleType(const std::string& scalingRuleType); std::string getMetricName()const; void setMetricName(const std::string& metricName); std::string getPredictiveScalingMode()const; void setPredictiveScalingMode(const std::string& predictiveScalingMode); std::string getResourceOwnerAccount()const; void setResourceOwnerAccount(const std::string& resourceOwnerAccount); int getAdjustmentValue()const; void setAdjustmentValue(int adjustmentValue); int getEstimatedInstanceWarmup()const; void setEstimatedInstanceWarmup(int estimatedInstanceWarmup); std::string getOwnerAccount()const; void setOwnerAccount(const std::string& ownerAccount); int getPredictiveTaskBufferTime()const; void setPredictiveTaskBufferTime(int predictiveTaskBufferTime); std::string getAdjustmentType()const; void setAdjustmentType(const std::string& adjustmentType); long getOwnerId()const; void setOwnerId(long ownerId); int getPredictiveValueBuffer()const; void setPredictiveValueBuffer(int predictiveValueBuffer); int getScaleOutEvaluationCount()const; void setScaleOutEvaluationCount(int scaleOutEvaluationCount); int getMinAdjustmentMagnitude()const; void setMinAdjustmentMagnitude(int minAdjustmentMagnitude); float getTargetValue()const; void setTargetValue(float targetValue); private: std::vector<StepAdjustment> stepAdjustment_; std::string scalingGroupId_; bool disableScaleIn_; int initialMaxSize_; std::string accessKeyId_; std::string scalingRuleName_; int cooldown_; std::string predictiveValueBehavior_; int scaleInEvaluationCount_; std::string scalingRuleType_; std::string metricName_; std::string predictiveScalingMode_; std::string resourceOwnerAccount_; int adjustmentValue_; int estimatedInstanceWarmup_; std::string ownerAccount_; int predictiveTaskBufferTime_; std::string adjustmentType_; long ownerId_; int predictiveValueBuffer_; int scaleOutEvaluationCount_; int minAdjustmentMagnitude_; float targetValue_; }; } } } #endif // !ALIBABACLOUD_ESS_MODEL_CREATESCALINGRULEREQUEST_H_
37.181818
84
0.753279
[ "vector", "model" ]
2e8f83fd31786dcd7dc5f88e1b108373fd6e3b0e
14,188
c
C
src/hg/lib/genbank.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
171
2015-04-22T15:16:02.000Z
2022-03-18T20:21:53.000Z
src/hg/lib/genbank.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
60
2016-10-03T15:15:06.000Z
2022-03-30T15:21:52.000Z
src/hg/lib/genbank.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
80
2015-04-16T10:39:48.000Z
2022-03-29T16:36:30.000Z
/* genbank.c - Various functions for dealing with genbank data */ /* Copyright (C) 2014 The Regents of the University of California * See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */ #include "common.h" #include "hash.h" #include "psl.h" #include "linefile.h" #include "genbank.h" #include "dystring.h" #include "hgConfig.h" #include "hdb.h" #include "trackHub.h" char *refSeqSummaryTable = "refSeqSummary"; char *refSeqStatusTable = "refSeqStatus"; char *gbCdnaInfoTable = "gbCdnaInfo"; char *gbWarnTable = "gbWarn"; char *authorTable = "author"; char *descriptionTable = "description"; char *productNameTable = "productName"; char *organismTable = "organism"; char *cdsTable = "cds"; char *tissueTable = "tissue"; char *developmentTable = "development"; char *geneNameTable = "geneName"; char *refLinkTable = "refLink"; char *refPepTable = "refPep"; char *cellTable = "cell"; char *sourceTable = "source"; char *libraryTable = "library"; char *mrnaCloneTable = "mrnaClone"; char *sexTable = "sex"; char *keywordTable = "keyword"; char *gbSeqTable = "gbSeq"; char *gbExtFileTable = "gbExtFile"; char *imageCloneTable = "imageClone"; char *gbMiscDiffTable = "gbMiscDiff"; #define MYBUFSIZE 2048 static inline char *addDatabase(char *database, char *buffer, char *table) { safef(buffer, MYBUFSIZE, "%s.%s",database,table); return cloneString(buffer); } void initGenbankTableNames(char *database) /* read hg.conf to get alternate table names */ { static boolean inited = FALSE; if (inited) return; if (trackHubDatabase(database)) // don't remap the names on assembly hubs return; char *genbankDb = cfgOptionEnv("GENBANKDB", "genbankDb"); char buffer[MYBUFSIZE]; if (genbankDb == NULL) { // if there's no genbankDb specified, check to see if hgFixed has the table, else use the database struct sqlConnection *conn = hAllocConn(database); if (sqlTableExists(conn, "hgFixed.gbCdnaInfo")) genbankDb = "hgFixed"; else genbankDb = database; hFreeConn(&conn); } refSeqStatusTable = addDatabase(genbankDb, buffer, "refSeqStatus"); refSeqSummaryTable = addDatabase(genbankDb, buffer, "refSeqSummary"); gbSeqTable = addDatabase(genbankDb, buffer, "gbSeq"); gbExtFileTable = addDatabase(genbankDb, buffer, "gbExtFile"); gbCdnaInfoTable = addDatabase(genbankDb, buffer, "gbCdnaInfo"); authorTable = addDatabase(genbankDb, buffer, "author"); descriptionTable = addDatabase(genbankDb, buffer, "description"); productNameTable = addDatabase(genbankDb, buffer, "productName"); organismTable = addDatabase(genbankDb, buffer, "organism"); cdsTable = addDatabase(genbankDb, buffer, "cds"); tissueTable = addDatabase(genbankDb, buffer, "tissue"); developmentTable = addDatabase(genbankDb, buffer, "development"); geneNameTable = addDatabase(genbankDb, buffer, "geneName"); refLinkTable = addDatabase(genbankDb, buffer, "refLink"); cellTable = addDatabase(genbankDb, buffer, "cell"); sourceTable = addDatabase(genbankDb, buffer, "source"); libraryTable = addDatabase(genbankDb, buffer, "library"); mrnaCloneTable = addDatabase(genbankDb, buffer, "mrnaClone"); sexTable = addDatabase(genbankDb, buffer, "sex"); keywordTable = addDatabase(genbankDb, buffer, "keyword"); refPepTable = addDatabase(genbankDb, buffer, "refPep"); imageCloneTable = addDatabase(genbankDb, buffer, "imageClone"); gbMiscDiffTable = addDatabase(genbankDb, buffer, "gbMiscDiff"); gbWarnTable = addDatabase(genbankDb, buffer, "gbWarn"); inited = TRUE; } static char *JOIN_PREFIX = "join("; static char *COMPLEMENT_PREFIX = "complement("; static boolean convertCoord(char *numStr, int *coord) /* convert an CDS cooordinate, return false if invalid */ { char *endPtr; *coord = strtoul(numStr, &endPtr, 10); return ((*numStr != '\0') && (*endPtr == '\0')); } static boolean parseStartCds(char *startBuf, struct genbankCds* cds) /* parse a starting CDS coordinate */ { cds->startComplete = (startBuf[0] != '<'); if (!cds->startComplete) startBuf++; if (!convertCoord(startBuf, &cds->start)) return FALSE; cds->start--; /* convert to zero-based */ return TRUE; } static boolean parseEndCds(char *endBuf, struct genbankCds* cds) /* parse an ending CDS coordinate */ { cds->endComplete = (endBuf[0] != '>'); if (!cds->endComplete) endBuf++; return convertCoord(endBuf, &cds->end); } static boolean parseRange(char *cdsBuf, struct genbankCds* cds) /* parse a cds range in the for 221..617 */ { char *p1; /* find .. */ p1 = strchr(cdsBuf, '.'); if ((p1 == NULL) || (p1[1] != '.')) return FALSE; /* no .. */ *p1 = '\0'; p1 += 2; if (!parseStartCds(cdsBuf, cds)) return FALSE; return parseEndCds(p1, cds); } static boolean parseJoin(char *cdsBuf, struct genbankCds* cds) /* parse a join cds, taking the first and last coordinates in range */ { int len = strlen(cdsBuf); char *startPtr, *endPtr, *p; /* Pull out last number in join */ if (cdsBuf[len-1] != ')') return FALSE; /* no close paren */ cdsBuf[len-1] = '\0'; endPtr = strrchr(cdsBuf, '.'); if (endPtr == NULL) return FALSE; /* no preceeding dot */ endPtr++; /* Pull out first number */ startPtr = cdsBuf+strlen(JOIN_PREFIX); p = strchr(startPtr, '.'); if (p == NULL) return FALSE; /* no dot after number */ *p = '\0'; if (!parseStartCds(startPtr, cds)) return FALSE; /* invalid start */ return parseEndCds(endPtr, cds); } static boolean parseComplement(char *cdsBuf, struct genbankCds* cds) /* parse a complement cds, perhaps recursively parsing a join */ { int len = strlen(cdsBuf); char *p1 = cdsBuf+strlen(COMPLEMENT_PREFIX); if (cdsBuf[len-1] != ')') return FALSE; /* no closing paren */ cdsBuf[len-1] = '\0'; cds->complement = TRUE; if (startsWith(JOIN_PREFIX, p1)) return parseJoin(p1, cds); else return parseRange(p1, cds); } boolean genbankCdsParse(char *cdsStr, struct genbankCds* cds) /* Parse a genbank CDS, returning TRUE if it can be successfuly parsed, FALSE * if there are problems. If a join() is specified, the first and last * coordinates are used for the CDS. Incomplete CDS specifications will still * return the start or end. start/end are set to 0 on error. */ { static struct dyString* cdsBuf = NULL; /* buffer for CDS strings */ boolean isOk; if (cdsBuf == NULL) cdsBuf = dyStringNew(512); /* copy so that string can be modified without changing input */ dyStringClear(cdsBuf); dyStringAppend(cdsBuf, cdsStr); ZeroVar(cds); /* FIXME: complement handling is wrong here, but it should only occur in DNA*/ if (startsWith(JOIN_PREFIX, cdsBuf->string)) isOk = parseJoin(cdsBuf->string, cds); else if (startsWith(COMPLEMENT_PREFIX, cdsBuf->string)) isOk = parseComplement(cdsBuf->string, cds); else isOk = parseRange(cdsBuf->string, cds); if (!isOk) cds->start = cds->end = 0; return isOk; } boolean genbankParseCds(char *cdsStr, unsigned *cdsStart, unsigned *cdsEnd) /* Compatiblity function, genbankCdsParse is prefered. Parse a genbank CDS, * returning TRUE if it can be successfuly parsed, FALSE if there are * problems. If a join() is specified, the first and last coordinates are * used for the CDS. Incomplete CDS specifications will still return the * start or end. cdsStart and cdsEnd are set to -1 on error. */ { struct genbankCds cds; boolean isOk = genbankCdsParse(cdsStr, &cds); if (!isOk) cds.start = cds.end = -1; *cdsStart = cds.start; *cdsEnd = cds.end; return isOk; } static void checkAccLen(char *acc) /* check the length of an accession string */ { if (strlen(acc) > GENBANK_ACC_BUFSZ-1) errAbort("invalid Genbank/RefSeq accession (too long): \"%s\"", acc); } boolean genbankIsRefSeqAcc(char *acc) /* determine if a accession appears to be from RefSeq */ { /* NM_012345, NP_012345, NR_012345, etc */ return (strlen(acc) > 4) && (acc[0] == 'N') && (acc[2] == '_'); } boolean genbankIsRefSeqCodingMRnaAcc(char *acc) /* determine if a accession appears to be a protein-coding RefSeq * accession. */ { /* NM_012345 */ return (strlen(acc) > 4) && (acc[0] == 'N') && (acc[1] == 'M') && (acc[2] == '_'); } boolean genbankIsRefSeqNonCodingMRnaAcc(char *acc) /* determine if a accession appears to be a non-protein-coding RefSeq * accession. */ { return genbankIsRefSeqAcc(acc) && ! genbankIsRefSeqCodingMRnaAcc(acc); } char* genbankDropVer(char *outAcc, char *inAcc) /* strip the version from a genbank id. Input and output * strings maybe the same. Length is checked against * GENBANK_ACC_BUFSZ. */ { checkAccLen(inAcc); if (outAcc != inAcc) strcpy(outAcc, inAcc); chopPrefix(outAcc); return outAcc; } void genbankExceptionsHash(char *fileName, struct hash **retSelenocysteineHash, struct hash **retAltStartHash) /* Will read a genbank exceptions file, and return two hashes parsed out of * it filled with the accessions having the two exceptions we can handle, * selenocysteines, and alternative start codons. */ { struct lineFile *lf = lineFileOpen(fileName, TRUE); struct hash *scHash = *retSelenocysteineHash = hashNew(0); struct hash *altStartHash = *retAltStartHash = hashNew(0); char *row[3]; while (lineFileRowTab(lf, row)) { struct lineFile *lf = lineFileOpen(fileName, TRUE); char *row[3]; while (lineFileRow(lf, row)) { if (sameString(row[1], "translExcept") && (stringIn("aa:Sec", row[2]) != NULL)) hashAdd(scHash, row[0], row[2]); if (sameString(row[1], "exception") && sameString(row[2], "alternative_start_codon")) hashAdd(altStartHash, row[0], NULL); } } lineFileClose(&lf); } struct genbankCds genbankCdsToGenome(struct genbankCds* cds, struct psl *psl) /* Convert set cdsStart/end from mrna to genomic coordinates using an * alignment. Returns a genbankCds object with genomic (positive strand) * coordinates */ { // FIXME: this is used only by genePred code, but since frame was added, // genome mapping of CDS is computed both here and genePred.getFrame(). // this should really be unified. int nblks = psl->blockCount; int rnaCdsStart = cds->start, rnaCdsEnd = cds->end; int iBlk; struct genbankCds genomeCds; ZeroVar(&genomeCds); genomeCds.start = genomeCds.end = -1; char geneStrand = (psl->strand[1] == '\0') ? psl->strand[0] : ((psl->strand[0] != psl->strand[1]) ? '-' : '+'); /* use start/end completeness from CDS specification, and adjust if unaligned */ boolean startComplete = cds->startComplete, endComplete = cds->endComplete; if (psl->strand[0] == '-') { // swap CDS reverseIntRange(&rnaCdsStart, &rnaCdsEnd, psl->qSize); startComplete = cds->endComplete; endComplete = cds->startComplete; } /* find query block or gap containing start and map to target */ for (iBlk = 0; (iBlk < nblks) && (genomeCds.start < 0); iBlk++) { if (rnaCdsStart < psl->qStarts[iBlk]) { /* in gap before block, set to start of block */ genomeCds.start = psl->tStarts[iBlk]; startComplete = FALSE; } else if (rnaCdsStart < (psl->qStarts[iBlk] + psl->blockSizes[iBlk])) { /* in this block, map to target */ genomeCds.start = psl->tStarts[iBlk] + (rnaCdsStart - psl->qStarts[iBlk]); } } if (genomeCds.start < 0) { /* after last block, set after end of that block */ genomeCds.start = psl->tStarts[iBlk-1] + psl->blockSizes[iBlk-1]; startComplete = FALSE; } /* find query block or gap containing end and map to target */ for (iBlk = 0; (iBlk < nblks) && (genomeCds.end < 0); iBlk++) { if (rnaCdsEnd <= psl->qStarts[iBlk]) { /* in gap before block, set to start of gap */ if (iBlk == 0) genomeCds.end = psl->tStarts[0]; /* before first block */ else genomeCds.end = psl->tStarts[iBlk-1] + psl->blockSizes[iBlk-1]; endComplete = FALSE; } else if (rnaCdsEnd <= (psl->qStarts[iBlk] + psl->blockSizes[iBlk])) { /* in this block, map to target */ genomeCds.end = psl->tStarts[iBlk] + (rnaCdsEnd - psl->qStarts[iBlk]); } } if (genomeCds.end < 0) { /* after last block, set to end of that block */ genomeCds.end = psl->tStarts[nblks-1] + psl->blockSizes[nblks-1]; endComplete = FALSE; } if (genomeCds.start >= genomeCds.end) { // CDS not aligned genomeCds.start = genomeCds.end = psl->tStarts[nblks-1] + psl->blockSizes[nblks-1]; startComplete = endComplete = FALSE; } if (geneStrand == '+') { genomeCds.startComplete = startComplete; genomeCds.endComplete = endComplete; } else { genomeCds.startComplete = endComplete; genomeCds.endComplete = startComplete; } if (psl->strand[1] == '-') reverseIntRange(&genomeCds.start, &genomeCds.end, psl->tSize); return genomeCds; } /* Accession prefixes indicating patent sequences, taken from: * https://www.ncbi.nlm.nih.gov/Sequin/acc.html */ static char *genbankPatentPrefixes[] = { "E", "BD", "DD", "DI", "DJ", "DL", "DM", "FU", "FV", "FW", "FZ", "GB", "HV", "HW", "HZ", "LF", "LG", "LV", "LX", "LY", "LZ", "MA", "MB", "A", "AX", "CQ", "CS", "FB", "GM", "GN", "HA", "HB", "HC", "HD", "HH", "HI", "JA", "JB", "JC", "JD", "JE", "LP", "LQ", "MP", "MQ", "MR", "MS", "I", "AR", "DZ", "EA", "GC", "GP", "GV", "GX", "GY", "GZ", "HJ", "HK", "HL", "KH", "MI", NULL }; static struct hash *genbankPatentPrefixesHash = NULL; static void makeGenbankPatentPrefixHash(void) /* build hash of genbank accession prefixes on first uses */ { int i; genbankPatentPrefixesHash = hashNew(0); for (i = 0; genbankPatentPrefixes[i] != NULL; i++) hashAddInt(genbankPatentPrefixesHash, genbankPatentPrefixes[i], TRUE); } boolean isGenbankPatentAccession(char *acc) /* Is this an accession prefix allocated to patent sequences. */ { if (genbankPatentPrefixesHash == NULL) makeGenbankPatentPrefixHash(); if (strlen(acc) >= GENBANK_ACC_BUFSZ) return FALSE; // too big, shouldn't happen // drop numeric part char accbuf[GENBANK_ACC_BUFSZ]; safecpy(accbuf, sizeof(accbuf), acc); char *numPtr = skipToNumeric(accbuf); if (numPtr == NULL) return FALSE; // doesn't look like genbank acc *numPtr = '\0'; return hashLookup(genbankPatentPrefixesHash, accbuf) != NULL; }
31.954955
102
0.679729
[ "object" ]
2e9846d9562d17223c2c06c06a08a7088e341218
4,080
c
C
eBug2014 Slave Bootloader.cydsn/main.c
monash-wsrn/ebug2014-firmware
d7691dffe39feba4694b20739bcadd590c80f6f5
[ "MIT" ]
null
null
null
eBug2014 Slave Bootloader.cydsn/main.c
monash-wsrn/ebug2014-firmware
d7691dffe39feba4694b20739bcadd590c80f6f5
[ "MIT" ]
null
null
null
eBug2014 Slave Bootloader.cydsn/main.c
monash-wsrn/ebug2014-firmware
d7691dffe39feba4694b20739bcadd590c80f6f5
[ "MIT" ]
null
null
null
#include <project.h> #include <stdio.h> #include <stdarg.h> static char LCD_Top[17]; static char LCD_Bottom[17]; void print_top(const char *fmt, ...) { va_list args; va_start(args,fmt); vsnprintf(LCD_Top,sizeof(LCD_Top),fmt,args); va_end(args); } void print_bot(const char *fmt, ...) { va_list args; va_start(args,fmt); vsnprintf(LCD_Bottom,sizeof(LCD_Bottom),fmt,args); va_end(args); } volatile uint8 persist __attribute__((section(".noinit"))); __attribute__((constructor(101))) void boot() { if(*(uint32*)0x3004!=0x3011) //make sure reset vector is set correctly in bootloadable { persist=2; return; } if(CY_GET_REG8(CYREG_PHUB_CFGMEM23_CFG1)&CY_RESET_SW) //software reset { if(persist==1) { persist=0; asm("B 0x3010"); //TODO determine address of bootloadable (dynamically) } } else persist=0; } static void run_app_isr() { persist=1; CySoftwareReset(); } static void LCD_Update() { LCD_Position(0,0); LCD_PrintString(LCD_Top); LCD_Position(1,0); LCD_PrintString(LCD_Bottom); } static void flashing_failed() { LEDB_Control=0; LEDR_Control=0x7f; LCD_Update(); CyDelay(500); persist=2; CySoftwareReset(); //TODO clear first row (number 0x30 currently) to prevent half programmed bootloadable from running } static void rx_isr() { uint8 l=link_rx_length; link_RX; switch(link_rx_packet[0]) { case 0x10: //print on LCD line 0 memcpy(LCD_Top,link_rx_packet+1,l-1<16?l-1:16); break; case 0x11: //print on LCD line 1 memcpy(LCD_Bottom,link_rx_packet+1,l-1<16?l-1:16); break; case 0x12: //clear screen LCD_ClearDisplay(); //TODO this can take too long break; case 0xf0: //programming data { print_top("Flashing Slave: "); uint8 *packet=link_rx_packet+1; uint16 *header=(uint16*)packet; static uint8 first=1; //are we waiting for welcome packet? static uint16 n_rows=1024; static uint16 first_row=0; static uint16 row=0; //current row being buffered static uint8 seq=0; //packet number in current row if(first) { first=0; if(*header!=0xff00) //ensure first packet is welcome packet { print_top("Error flashing: "); print_bot("Not welcome %04x",*header); flashing_failed(); } first_row=row=header[1]; //first row to program //TODO ensure first row is past end of bootloader (0x30 rows currently) n_rows=header[2]; if(*(uint32*)(packet+6)!=*(reg32*)CYDEV_PANTHER_DEVICE_ID) //verify JTAG ID { print_top("Error flashing: "); print_bot("Wrong JTAG ID "); CyDelay(500); print_bot("0x%08x ",*(uint32*)(packet+6)); flashing_failed(); } CySetTemp(); //once should be enough if temp doesn't change by more than 10C } else { //TODO timeout (if no packets for a while then bail and restart) uint16 packet_row=(*header)&0x3ff; uint8 packet_seq=(*header)>>10; if(packet_row!=row||packet_seq!=seq) { print_top("Error flashing: "); print_bot("Wrong row/seq no"); flashing_failed(); } static uint8 row_buffer[256]; memcpy(row_buffer+seq*30,packet+2,seq==8?16:30); if(seq++==8) //last packet for row { uint8 progress=(row-first_row)*8/n_rows; LEDB_Control=(1<<progress)-1; print_bot("Row %3d/%d ",row-first_row+1,n_rows); CyWriteRowData(row>>8,row&0xff,row_buffer); seq=0; row++; if(row==first_row+n_rows) { LEDB_Control=0; LEDG_Control=0x7f; run_app_StartEx(run_app_isr); } } } uint8 ACK=0xf0; while(link_TX_busy()); link_TX_copy(&ACK,1); //send ack back to master break; } } } int main() { CyGlobalIntEnable; link_Start(); link_rx_ready_StartEx(rx_isr); LCD_Start(); lcd_refresh_StartEx(LCD_Update); if(persist!=2) run_app_StartEx(run_app_isr); LED_centre_SetDriveMode(LED_centre_DM_STRONG); for(;;) CY_PM_WFI; }
23.448276
101
0.637255
[ "vector", "3d" ]
2ea491101a40f17877ab397eb880d0b046941a93
2,710
h
C
chap1/NetworkRenderer.h
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
chap1/NetworkRenderer.h
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
chap1/NetworkRenderer.h
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
#ifndef J_NETWORKRENDERER_H #define J_NETWORKRENDERER_H #include "Display.h" #include "Network.h" #include "SFML/Graphics/Font.hpp" namespace J{ class NetworkRenderer{ public: NetworkRenderer(Display & display, J::Network & network); ~NetworkRenderer(); void updateNetworkStructure(); void updateInputImage(const Mnist::ImageSet::Image & image); void updateLabel(int label, bool isCorrect); void showBackprop(const Mnist::ImageSet::Image & image, const std::vector<Eigen::MatrixXd> & deltaNablaWeights, const std::vector<Eigen::VectorXd> & deltaNablaBiases); void showWeightedImage(const Eigen::VectorXd & weightedImage, size_t width, size_t height, size_t layerIndex, size_t nodeIndex); private: static sf::Color OutlineColor; static sf::Color FillColor; static sf::Color HilightColor; static sf::Color ConnectionColor; static float DefaultCircleDrawRadius; static unsigned int DefaultRenderMargin; class NodeStyler{ public: virtual ~NodeStyler() = default; virtual void styleNode(sf::CircleShape & shape, int column, int nodeIndex) = 0; }; class DefaultNodeStyler : public NodeStyler{ public: void styleNode(sf::CircleShape & shape, int column, int nodeIndex); }; class HilightingNodeStyler : public NodeStyler{ public: HilightingNodeStyler(const std::vector<Eigen::MatrixXd> & deltaNablaWeights, const std::vector<Eigen::VectorXd> & deltaNablaBiases); void styleNode(sf::CircleShape & shape, int column, int nodeIndex); private: const std::vector<Eigen::MatrixXd> & m_deltaNablaWeights; const std::vector<Eigen::VectorXd> & m_deltaNablaBiases; }; class ConnectionStyler{ public: virtual ~ConnectionStyler() = default; virtual void styleConnection(size_t layerIndex, size_t nodeIndex, size_t inputNodeIndex, sf::Vertex & startVertex, sf::Vertex & endVertex) = 0; }; class WeightedConnectionStyler : public ConnectionStyler{ public: WeightedConnectionStyler(const std::vector<NetworkLayer> & layers); void styleConnection(size_t layerIndex, size_t nodeIndex, size_t inputNodeIndex, sf::Vertex & startVertex, sf::Vertex & endVertex); private: std::vector<Eigen::MatrixXd> m_layerWeights; }; void updateNetworkStructure(NodeStyler & nodeStyler, ConnectionStyler & connectionStyler); std::shared_ptr<sf::VertexArray> generateConnectionLines(ConnectionStyler & connectionStyler); void calculateNodeParameters(); Display & m_display; const J::Network & m_network; sf::Font m_font; unsigned int m_renderMargin; float m_circleDrawRadius; std::vector<std::vector<sf::Vector2f> > m_nodePositions; }; } #endif
32.650602
170
0.736162
[ "shape", "vector" ]
2eb02f1a63a04fd1c1adabb18872c31ad8c39d70
3,310
h
C
WSEExternal/include/Common/Base/hkBase.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Common/Base/hkBase.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Common/Base/hkBase.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKBASE_HKBASE_H #define HKBASE_HKBASE_H #include <Common/Base/Types/hkBaseTypes.h> // C4100 'identifier' : unreferenced formal parameter // a function need not use all its arguments // C4127 conditional expression is constant // constant conditionals are often used inside asserts // C4505 'function' : unreferenced local function has been removed // lots of inline functions are not used in a compilation unit // C4510 'class' : default constructor could not be generated // C4511 'class' : copy constructor could not be generated // C4512 'class' : assignment operator could not be generated // many classes are not designed with value semantics // C4514 unreferenced inline/local function has been removed // lots of inline functions are not used in a compilation unit // C4714 force inlined function not inlined. This warning is only disabled in debug modes. # pragma warning(push) # pragma warning(disable: 4100 4127 4324 4505 4510 4511 4512 4514) //# pragma warning(disable: 1684 981 1419 1418 271 1572 128 ) // Intel compiler warnings # if defined(HK_DEBUG) # pragma warning(disable: 4714) # endif # ifndef _CRT_SECURE_NO_DEPRECATE # define _CRT_SECURE_NO_DEPRECATE 1 # endif # ifndef _CRT_NONSTDC_NO_DEPRECATE # define _CRT_NONSTDC_NO_DEPRECATE 1 # endif #include <Common/Base/Memory/hkThreadMemory.h> #include <Common/Base/Object/hkBaseObject.h> #include <Common/Base/Object/hkReferencedObject.h> #include <Common/Base/Object/hkSingleton.h> #if !defined(HK_PLATFORM_PS3_SPU) #include <Common/Base/System/Io/OStream/hkOStream.h> /* <todo> remove */ #endif #include <Common/Base/System/Error/hkError.h> #include <Common/Base/Container/Array/hkArray.h> #include <Common/Base/Container/Array/hkSmallArray.h> #include <Common/Base/Math/hkMath.h> #include <Common/Base/Container/String/hkString.h> /* <todo> remove, move static functions elsewhere */ #include <Common/Base/Container/String/hkStringPtr.h> #include <Common/Base/Memory/hkThreadMemory.inl> #include <Common/Base/UnitTest/hkUnitTest.h> #endif // HKBASE_HKBASE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20090704) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
38.488372
247
0.751057
[ "object" ]
2eb6c43e447c17934422e5f42a055ca0873388b3
2,414
h
C
comparisons/Box2D/Testbed/Tests/GroundPlane.h
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
71
2021-09-08T13:16:43.000Z
2022-03-27T10:23:33.000Z
comparisons/Box2D/Testbed/Tests/GroundPlane.h
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
4
2021-09-08T00:16:20.000Z
2022-01-05T17:44:08.000Z
comparisons/Box2D/Testbed/Tests/GroundPlane.h
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
2
2021-09-18T15:15:38.000Z
2021-09-21T15:15:38.000Z
#pragma once #include <array> #include <cmath> #include <iostream> #include <vector> class GroundPlane : public Test { protected: float displacement_scale; public: GroundPlane(float displacement_scale = 10.0) : displacement_scale(displacement_scale) { m_world->SetGravity(b2Vec2(0, -9.8)); float friction_coeff = 0.0; float restitution_coeff = 1.0; float density = 1.0f; { // Define the ground b2BodyDef groundBodyDef; groundBodyDef.type = b2_staticBody; groundBodyDef.position.Set(-10, 30); // Create the ground b2Body* ground = m_world->CreateBody(&groundBodyDef); // Define the ground shape b2EdgeShape groundShape; // Add the shape fixtures to the line body groundShape.Set(b2Vec2(-20, 0), b2Vec2(20, 0)); b2Fixture* fixture = ground->CreateFixture(&groundShape, density); fixture->SetFriction(friction_coeff); fixture->SetRestitution(restitution_coeff); } { // Define the line b2BodyDef lineBodyDef; lineBodyDef.type = b2_dynamicBody; lineBodyDef.bullet = true; lineBodyDef.position.Set(-10.0f, 50.0f); lineBodyDef.angle = 3.14 / 4; lineBodyDef.linearVelocity = b2Vec2(0, -displacement_scale); b2Body* line = m_world->CreateBody(&lineBodyDef); // Define the line shape b2EdgeShape lineShape; // Add the shape fixtures to the line body lineShape.Set(b2Vec2(-10, 0.5), b2Vec2(10, 1.0)); b2Fixture* fixture = line->CreateFixture(&lineShape, density); fixture->SetFriction(friction_coeff); fixture->SetRestitution(restitution_coeff); } } static Test* Create() { return new GroundPlane(); } virtual void Step(Settings* settings) override { static bool firstCall = true; if (firstCall) { settings->enableSleep = false; settings->hz = 120; // 1 / 1e-3; settings->velocityIterations = 300; settings->positionIterations = 300; settings->drawContactPoints = true; settings->drawContactImpulse = true; firstCall = false; } Test::Step(settings); } };
30.175
78
0.582022
[ "shape", "vector" ]
2eb7d2bb658911f0da9bfc6497dccc5ed7663af7
1,413
h
C
chrome/browser/usb/usb_tab_helper.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
chrome/browser/usb/usb_tab_helper.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/usb/usb_tab_helper.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "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 CHROME_BROWSER_USB_USB_TAB_HELPER_H_ #define CHROME_BROWSER_USB_USB_TAB_HELPER_H_ #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "mojo/public/cpp/bindings/pending_receiver.h" // Per-tab owner of USB services provided to render frames within that tab. class UsbTabHelper : public content::WebContentsUserData<UsbTabHelper> { public: static UsbTabHelper* GetOrCreateForWebContents( content::WebContents* web_contents); UsbTabHelper(const UsbTabHelper&) = delete; UsbTabHelper& operator=(const UsbTabHelper&) = delete; ~UsbTabHelper() override; void IncrementConnectionCount(); void DecrementConnectionCount(); bool IsDeviceConnected() const; private: explicit UsbTabHelper(content::WebContents* web_contents); friend class content::WebContentsUserData<UsbTabHelper>; void NotifyIsDeviceConnectedChanged(bool is_device_connected) const; // Initially no device is connected, type int is used as there can be many // devices connected to single UsbTabHelper. int device_connection_count_ = 0; content::WebContents* web_contents_; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; #endif // CHROME_BROWSER_USB_USB_TAB_HELPER_H_
32.860465
76
0.795471
[ "render" ]
2eb80097c58ce4709e49e08f8c25d01ce8bbb0ee
1,349
h
C
Build/src/include/Blocks/LayerMesh.h
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
Build/src/include/Blocks/LayerMesh.h
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
Build/src/include/Blocks/LayerMesh.h
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <vector> #include <array> #include <typedefs.h> #include "Block.h" #include <Utils/VertexArray.h> #include <Utils/VertexBuffer.h> #include <Utils/IndexBuffer.h> namespace GameEngine { class Layer; typedef std::array<std::array<std::array<Block, CHUNK_SIZE_X>, CHUNK_SIZE_Y>, CHUNK_SIZE_Z>* LayerDataTypePtr; LayerDataTypePtr m_GetLayerDataForMeshing(int cx, int cz); class LayerMesh { public: LayerMesh(); ~LayerMesh(); bool ConstructMesh(Layer* layer, const glm::vec3& chunk_pos); std::uint32_t m_VerticesCount; std::uint32_t m_TransparentVerticesCount; std::uint32_t m_ModelVerticesCount; VertexArray m_VAO; VertexArray m_TransparentVAO; VertexArray m_ModelVAO; private: void AddFace(Layer* layer, BlockFaceType face_type, const glm::vec3& position, BlockType type, uint8_t light_level = 0, bool buffer = true); std::vector<Vertex> m_Vertices; std::vector<Vertex> m_TransparentVertices; std::vector<Vertex> m_ModelVertices; glm::vec4 m_TopFace[4]; glm::vec4 m_BottomFace[4]; glm::vec4 m_ForwardFace[4]; glm::vec4 m_BackFace[4]; glm::vec4 m_LeftFace[4]; glm::vec4 m_RightFace[4]; VertexBuffer m_VBO; VertexBuffer m_TransparentVBO; // Vertex buffer for trasparent blocks VertexBuffer m_ModelVBO; // Vertex buffer for trasparent blocks }; }
24.527273
121
0.750185
[ "vector" ]
2eb80974ef63cb61bc38003b748a5f8224945920
4,447
h
C
samples/simdjson-demo/src/main/native/benchmarks.h
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
50
2021-09-23T07:20:44.000Z
2022-03-30T05:05:43.000Z
samples/simdjson-demo/src/main/native/benchmarks.h
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
21
2021-11-01T09:27:50.000Z
2022-03-08T02:43:57.000Z
samples/simdjson-demo/src/main/native/benchmarks.h
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
7
2021-10-09T03:00:07.000Z
2022-02-11T02:15:29.000Z
/* * Copyright 1999-2021 Alibaba Group Holding 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 BENCHMAKRS_H #define BENCHMAKRS_H #include "simdjson.h" #include <vector> #include <string> namespace simdjson { template<typename StringType=std::string_view> struct twitter_user { uint64_t id{}; StringType screen_name{}; template<typename OtherStringType> bool operator==(const twitter_user<OtherStringType> &other) const { return id == other.id && screen_name == other.screen_name; } }; template<typename StringType=std::string_view> struct tweet { StringType created_at{}; uint64_t id{}; StringType result{}; uint64_t in_reply_to_status_id{}; twitter_user<StringType> user{}; uint64_t retweet_count{}; uint64_t favorite_count{}; template<typename OtherStringType> simdjson_really_inline bool operator==(const tweet<OtherStringType> &other) const { return created_at == other.created_at && id == other.id && result == other.result && in_reply_to_status_id == other.in_reply_to_status_id && user == other.user && retweet_count == other.retweet_count && favorite_count == other.favorite_count; } template<typename OtherStringType> simdjson_really_inline bool operator!=(const tweet<OtherStringType> &other) const { return !(*this == other); } }; template<typename StringType> struct top_tweet_result { int64_t retweet_count{}; StringType screen_name{}; StringType text{}; template<typename OtherStringType> simdjson_really_inline bool operator==(const top_tweet_result<OtherStringType> &other) const { return retweet_count == other.retweet_count && screen_name == other.screen_name && text == other.text; } template<typename OtherStringType> simdjson_really_inline bool operator!=(const top_tweet_result<OtherStringType> &other) const { return !(*this == other); } }; struct point { double x; double y; double z; point() : x(0), y(0), z(0) {} point(double xv, double yv, double zv) : x(xv), y(yv), z(zv) {} void set(double xv, double yv, double zv) { x = xv; y = yv; z = zv; } }; class Benchmarks { public: static void distinctuserid_recursive(simdjson::simdjson_result<simdjson::dom::element> & result, std::vector<int64_t> & answer); static void distinctuserid(simdjson::simdjson_result<simdjson::dom::element> & result, std::vector<int64_t> & answer); static void distinctuserid(simdjson::padded_string & content, std::vector<int64_t> & answer); static void distinctuserid(simdjson::dom::parser &parser, simdjson::padded_string & content, std::vector<int64_t> & answer); static void kostya(simdjson::simdjson_result<simdjson::dom::element> & dom, std::vector<simdjson::point> & result); static void kostya(simdjson::padded_string & content, std::vector<simdjson::point> & result); static void kostya(simdjson::dom::parser &parser, simdjson::padded_string & content, std::vector<simdjson::point> & result); static void top_tweet(simdjson::simdjson_result<simdjson::dom::element> &dom, int64_t max_retweet_count, top_tweet_result<std::string_view> &result); static void top_tweet(simdjson::padded_string & content, int64_t max_retweet_count, top_tweet_result<std::string_view> &result); static void top_tweet(simdjson::dom::parser &parser, simdjson::padded_string & content, int64_t max_retweet_count, top_tweet_result<std::string_view> &result); static void partial_tweets(simdjson::simdjson_result<simdjson::dom::element> &dom, std::vector<tweet<std::string_view>> &result); static void partial_tweets(simdjson::padded_string & content, std::vector<tweet<std::string_view>> &result); static void partial_tweets(simdjson::dom::parser &parser, simdjson::padded_string & content, std::vector<tweet<std::string_view>> &result); }; } #endif
38.336207
163
0.719586
[ "vector" ]
2ebae4081e6ca869afa3b4502c7e11c20dab95fc
3,954
h
C
ios/headers/BCVideo.h
appcelerator-modules/ti.brightcove
2bc96ee618f9dba431ac97aeb66c555da7e46799
[ "Apache-2.0" ]
2
2016-02-07T23:10:53.000Z
2021-08-09T17:13:16.000Z
ProviderResilience-iOS/BCVideo.h
t2health/ProviderResilience-iOS
31e91d65e1f9e6e7120619a6c25f38e0225ada57
[ "NASA-1.3" ]
1
2016-07-28T02:19:44.000Z
2016-07-28T02:19:44.000Z
ProviderResilience-iOS/BCVideo.h
t2health/ProviderResilience-iOS
31e91d65e1f9e6e7120619a6c25f38e0225ada57
[ "NASA-1.3" ]
1
2015-07-20T21:39:45.000Z
2015-07-20T21:39:45.000Z
/* 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: 1. The permission granted herein does not extend to commercial use of the Software by entities primarily engaged in providing online video and related services; and 2. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #import <Foundation/Foundation.h> #import "BCRendition.h" /** @brief The BCVideo model object This object contains properties describing a video in the Brightcove system. It is returned either singly or as part of the items array of a BCItemCollection from video-related API calls. You do not typically instantiate a BCVideo object in your code. */ @interface BCVideo : NSObject { NSString *name; long long videoId; NSString *referenceId; long long accountId; NSString *shortDescription; NSString *longDescription; NSString *FLVURL; NSArray *renditions; BCRendition *videoFullLength; NSDate *creationDate; NSDate *publishedDate; NSDate *lastModifiedDate; BCItemState itemState; NSDate *startDate; NSDate *endDate; NSString *linkURL; NSString *linkText; NSArray *tags; NSString *videoStillURL; NSString *thumbnailURL; long long length; BCEconomics economics; BOOL geoFiltered; NSArray *geoFilteredCountries; BOOL geoFilterExclude; NSArray *cuePoints; long long playsTotal; long long playsTrailingWeek; NSDictionary *customFields; } @property (nonatomic, retain) NSString *name; @property (nonatomic, assign) long long videoId; @property (nonatomic, retain) NSString *referenceId; @property (nonatomic, assign) long long accountId; @property (nonatomic, retain) NSString *shortDescription; @property (nonatomic, retain) NSString *longDescription; @property (nonatomic, retain) NSString *FLVURL; @property (nonatomic, retain) NSArray *renditions; @property (nonatomic, retain) BCRendition *videoFullLength; @property (nonatomic, retain) NSDate *creationDate; @property (nonatomic, retain) NSDate *publishedDate; @property (nonatomic, retain) NSDate *lastModifiedDate; @property (nonatomic, assign) BCItemState itemState; @property (nonatomic, retain) NSDate *startDate; @property (nonatomic, retain) NSDate *endDate; @property (nonatomic, retain) NSString *linkURL; @property (nonatomic, retain) NSString *linkText; @property (nonatomic, retain) NSArray *tags; @property (nonatomic, retain) NSString *videoStillURL; @property (nonatomic, retain) NSString *thumbnailURL; @property (nonatomic, assign) long long length; @property (nonatomic, assign) BCEconomics economics; @property (nonatomic, assign) BOOL geoFiltered; @property (nonatomic, retain) NSArray *geoFilteredCountries; @property (nonatomic, assign) BOOL geoFilterExclude; @property (nonatomic, retain) NSArray *cuePoints; @property (nonatomic, assign) long long playsTotal; @property (nonatomic, assign) long long playsTrailingWeek; @property (nonatomic, retain) NSDictionary *customFields; + (BCVideo *) initFromDictionary:(NSDictionary *) dict; + (NSDictionary *) toDictionary:(BCVideo *) video; /** @brief Compare BCVideos This is the method used to compare a BCVideo to another BCVideo instance. */ - (BOOL)isEqualToBCVideo:(id)object; @end
35.621622
84
0.780728
[ "object", "model" ]
2ebc458637a533894c3ebff85713a5b1a6e06016
8,734
h
C
mace/core/tensor.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
1
2021-11-21T20:05:25.000Z
2021-11-21T20:05:25.000Z
mace/core/tensor.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
null
null
null
mace/core/tensor.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACE_CORE_TENSOR_H_ #define MACE_CORE_TENSOR_H_ #include <algorithm> #include <functional> #include <memory> #include <numeric> #include <string> #include <utility> #include <vector> #include "mace/core/memory/buffer.h" #include "mace/core/ops/ops_utils.h" #include "mace/core/runtime/runtime.h" #include "mace/core/types.h" #include "mace/utils/logging.h" #ifdef MACE_ENABLE_NEON // Avoid over-bound accessing memory #define MACE_EXTRA_BUFFER_PAD_SIZE 64 #else #define MACE_EXTRA_BUFFER_PAD_SIZE 0 #endif namespace mace { #define MACE_SINGLE_ARG(...) __VA_ARGS__ #define MACE_CASE(TYPE, STATEMENTS) \ case DataTypeToEnum<TYPE>::value: { \ typedef TYPE T; \ STATEMENTS; \ break; \ } #if defined(MACE_ENABLE_NEON) && defined(__ANDROID__) \ || defined(MACE_ENABLE_FP16) #define MACE_TYPE_ENUM_SWITCH_CASE_FLOAT16(STATEMENTS) \ MACE_CASE(float16_t, MACE_SINGLE_ARG(STATEMENTS)) #else #define MACE_TYPE_ENUM_SWITCH_CASE_FLOAT16(STATEMENTS) #endif #ifdef MACE_ENABLE_BFLOAT16 #define MACE_TYPE_ENUM_SWITCH_CASE_BFLOAT16(STATEMENTS) \ MACE_CASE(BFloat16, MACE_SINGLE_ARG(STATEMENTS)) #else #define MACE_TYPE_ENUM_SWITCH_CASE_BFLOAT16(STATEMENTS) #endif // MACE_ENABLE_BFLOAT16 #ifdef MACE_ENABLE_MTK_APU #define MACE_TYPE_ENUM_SWITCH_CASE_INT16(STATEMENTS) \ MACE_CASE(int16_t, MACE_SINGLE_ARG(STATEMENTS)) #else #define MACE_TYPE_ENUM_SWITCH_CASE_INT16(STATEMENTS) #endif // MACE_ENABLE_MTK_APU #if MACE_ENABLE_OPENCL #define MACE_TYPE_ENUM_SWITCH_CASE_OPENCL(STATEMENTS) \ MACE_CASE(half, MACE_SINGLE_ARG(STATEMENTS)) #else #define MACE_TYPE_ENUM_SWITCH_CASE_OPENCL(STATEMENTS) #endif // MACE_ENABLE_OPENCL #define MACE_TYPE_ENUM_SWITCH( \ TYPE_ENUM, STATEMENTS, INVALID_STATEMENTS, DEFAULT_STATEMENTS) \ switch (TYPE_ENUM) { \ MACE_CASE(float, MACE_SINGLE_ARG(STATEMENTS)) \ MACE_CASE(uint8_t, MACE_SINGLE_ARG(STATEMENTS)) \ MACE_CASE(int32_t, MACE_SINGLE_ARG(STATEMENTS)) \ MACE_TYPE_ENUM_SWITCH_CASE_FLOAT16(STATEMENTS) \ MACE_TYPE_ENUM_SWITCH_CASE_BFLOAT16(STATEMENTS) \ MACE_TYPE_ENUM_SWITCH_CASE_INT16(STATEMENTS) \ MACE_TYPE_ENUM_SWITCH_CASE_OPENCL(STATEMENTS) \ case DT_INVALID: \ INVALID_STATEMENTS; \ break; \ default: \ DEFAULT_STATEMENTS; \ break; \ } // `TYPE_ENUM` will be converted to template `T` in `STATEMENTS` #define MACE_RUN_WITH_TYPE_ENUM(TYPE_ENUM, STATEMENTS) \ MACE_TYPE_ENUM_SWITCH(TYPE_ENUM, STATEMENTS, LOG(FATAL) << "Invalid type"; \ , LOG(FATAL) << "Unknown type: " << TYPE_ENUM;) class Tensor { friend class Runtime; public: explicit Tensor(Runtime *runtime, DataType dt, MemoryType mem_type, const std::vector<index_t> &shape = std::vector<index_t>(), const bool is_weight = false, const std::string name = "", const BufferContentType content_type = IN_OUT_CHANNEL) : shape_(shape), runtime_(runtime), buffer_(std::make_shared<Buffer>(mem_type, dt)), unused_(false), name_(name), is_weight_(is_weight), scale_(0.f), zero_point_(0), minval_(0.f), maxval_(0.f), data_format_(DataFormat::NONE), content_type_(content_type) { MACE_CHECK(dtype() != DataType::DT_INVALID); } explicit Tensor(Runtime *runtime, DataType dt, const std::vector<index_t> &shape = std::vector<index_t>(), const bool is_weight = false, const std::string name = "", const BufferContentType content_type = IN_OUT_CHANNEL) : shape_(shape), runtime_(runtime), buffer_(std::make_shared<Buffer>(runtime->GetUsedMemoryType(), dt)), unused_(false), name_(name), is_weight_(is_weight), scale_(0.f), zero_point_(0), minval_(0.f), maxval_(0.f), data_format_(DataFormat::NONE), content_type_(content_type) { MACE_CHECK(dtype() != DataType::DT_INVALID); } ~Tensor() {} std::string name() const; DataType dtype() const; void SetDtype(DataType dtype); bool unused() const; const std::vector<index_t> &shape() const; std::vector<index_t> max_shape() const; index_t max_size() const; index_t raw_max_size() const; void SetShapeConfigured(const std::vector<index_t> &shape_configured); void SetContentType(BufferContentType content_type, unsigned int content_param = 0); void GetContentType(BufferContentType *content_type, unsigned int *content_param) const; const std::vector<index_t> &buffer_shape() const; index_t dim_size() const; index_t dim(unsigned int index) const; index_t size() const; index_t raw_size() const; MemoryType memory_type() const; void set_data_format(DataFormat data_format); DataFormat data_format() const; index_t buffer_offset() const; Runtime *GetCurRuntime() const; template<typename T> const T *data() const { MACE_CHECK_NOTNULL(buffer_); return buffer_->data<T>(); } template<typename T> T *mutable_data() { MACE_CHECK_NOTNULL(buffer_); return buffer_->mutable_data<T>(); } const void *raw_data() const; void *raw_mutable_data(); template<typename T> const T *memory() const { MACE_CHECK_NOTNULL(buffer_); return buffer_->memory<T>(); } template<typename T> T *mutable_memory() const { MACE_CHECK_NOTNULL(buffer_); return buffer_->mutable_memory<T>(); } void MarkUnused(); void Clear(); void Reshape(const std::vector<index_t> &shape); MaceStatus Resize(const std::vector<index_t> &shape); // Make this tensor reuse other tensor's buffer. // This tensor has the same dtype, shape and buffer shape. // It could be reshaped later (with buffer shape unchanged). void ReuseTensorBuffer(const Tensor &other); MaceStatus ResizeLike(const Tensor &other); MaceStatus ResizeLike(const Tensor *other); void CopyBytes(const void *src, size_t bytes); template<typename T> void Copy(const T *src, index_t length) { MACE_CHECK(length == size(), "copy src and dst with different size."); CopyBytes(static_cast<const void *>(src), sizeof(T) * length); } void Copy(const Tensor &other); size_t SizeOfType() const; Buffer *UnderlyingBuffer() const; void DebugPrint() const; void Map(bool wait_for_finish) const; void UnMap() const; class MappingGuard { public: explicit MappingGuard(const Tensor *tensor, bool wait_for_finish = true); explicit MappingGuard(MappingGuard &&other); ~MappingGuard(); private: const Tensor *tensor_; MACE_DISABLE_COPY_AND_ASSIGN(MappingGuard); }; bool is_weight() const; float scale() const; int32_t zero_point() const; // hexagon now uses min/max instead of scale and zero float minval() const; float maxval() const; void SetScale(float scale); void SetZeroPoint(int32_t zero_point); void SetIsWeight(bool is_weight); void SetMinVal(float minval); void SetMaxVal(float maxval); private: std::vector<index_t> shape_; Runtime *runtime_; std::vector<index_t> shape_configured_; std::shared_ptr<Buffer> buffer_; bool unused_; std::string name_; bool is_weight_; float scale_; int32_t zero_point_; float minval_; float maxval_; DataFormat data_format_; // used for 4D input/output tensor BufferContentType content_type_; unsigned int content_param_; // TODO(luxuhui): remove it MACE_DISABLE_COPY_AND_ASSIGN(Tensor); }; } // namespace mace #endif // MACE_CORE_TENSOR_H_
32.71161
78
0.664644
[ "shape", "vector" ]
2ebdc6d5a76e60a33d6a271ff158258a61b7908c
13,105
c
C
runtime/musl-lkl/lkl/drivers/gpu/drm/udl/udl_fb.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
11
2022-02-05T12:12:43.000Z
2022-03-08T08:09:08.000Z
runtime/musl-lkl/lkl/drivers/gpu/drm/udl/udl_fb.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
null
null
null
runtime/musl-lkl/lkl/drivers/gpu/drm/udl/udl_fb.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
1
2022-02-22T20:32:22.000Z
2022-02-22T20:32:22.000Z
/* * Copyright (C) 2012 Red Hat * * based in parts on udlfb.c: * Copyright (C) 2009 Roberto De Ioris <roberto@unbit.it> * Copyright (C) 2009 Jaya Kumar <jayakumar.lkml@gmail.com> * Copyright (C) 2009 Bernie Thompson <bernie@plugable.com> * * This file is subject to the terms and conditions of the GNU General Public * License v2. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/fb.h> #include <linux/dma-buf.h> #include <linux/mem_encrypt.h> #include <drm/drmP.h> #include <drm/drm_crtc.h> #include <drm/drm_crtc_helper.h> #include "udl_drv.h" #include <drm/drm_fb_helper.h> #define DL_DEFIO_WRITE_DELAY (HZ/20) /* fb_deferred_io.delay in jiffies */ static int fb_defio = 0; /* Optionally enable experimental fb_defio mmap support */ static int fb_bpp = 16; module_param(fb_bpp, int, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP); module_param(fb_defio, int, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP); struct udl_fbdev { struct drm_fb_helper helper; struct udl_framebuffer ufb; int fb_count; }; #define DL_ALIGN_UP(x, a) ALIGN(x, a) #define DL_ALIGN_DOWN(x, a) ALIGN_DOWN(x, a) /** Read the red component (0..255) of a 32 bpp colour. */ #define DLO_RGB_GETRED(col) (uint8_t)((col) & 0xFF) /** Read the green component (0..255) of a 32 bpp colour. */ #define DLO_RGB_GETGRN(col) (uint8_t)(((col) >> 8) & 0xFF) /** Read the blue component (0..255) of a 32 bpp colour. */ #define DLO_RGB_GETBLU(col) (uint8_t)(((col) >> 16) & 0xFF) /** Return red/green component of a 16 bpp colour number. */ #define DLO_RG16(red, grn) (uint8_t)((((red) & 0xF8) | ((grn) >> 5)) & 0xFF) /** Return green/blue component of a 16 bpp colour number. */ #define DLO_GB16(grn, blu) (uint8_t)(((((grn) & 0x1C) << 3) | ((blu) >> 3)) & 0xFF) /** Return 8 bpp colour number from red, green and blue components. */ #define DLO_RGB8(red, grn, blu) ((((red) << 5) | (((grn) & 3) << 3) | ((blu) & 7)) & 0xFF) #if 0 static uint8_t rgb8(uint32_t col) { uint8_t red = DLO_RGB_GETRED(col); uint8_t grn = DLO_RGB_GETGRN(col); uint8_t blu = DLO_RGB_GETBLU(col); return DLO_RGB8(red, grn, blu); } static uint16_t rgb16(uint32_t col) { uint8_t red = DLO_RGB_GETRED(col); uint8_t grn = DLO_RGB_GETGRN(col); uint8_t blu = DLO_RGB_GETBLU(col); return (DLO_RG16(red, grn) << 8) + DLO_GB16(grn, blu); } #endif int udl_handle_damage(struct udl_framebuffer *fb, int x, int y, int width, int height) { struct drm_device *dev = fb->base.dev; struct udl_device *udl = dev->dev_private; int i, ret; char *cmd; cycles_t start_cycles, end_cycles; int bytes_sent = 0; int bytes_identical = 0; struct urb *urb; int aligned_x; int bpp = fb->base.format->cpp[0]; if (!fb->active_16) return 0; if (!fb->obj->vmapping) { ret = udl_gem_vmap(fb->obj); if (ret == -ENOMEM) { DRM_ERROR("failed to vmap fb\n"); return 0; } if (!fb->obj->vmapping) { DRM_ERROR("failed to vmapping\n"); return 0; } } aligned_x = DL_ALIGN_DOWN(x, sizeof(unsigned long)); width = DL_ALIGN_UP(width + (x-aligned_x), sizeof(unsigned long)); x = aligned_x; if ((width <= 0) || (x + width > fb->base.width) || (y + height > fb->base.height)) return -EINVAL; start_cycles = get_cycles(); urb = udl_get_urb(dev); if (!urb) return 0; cmd = urb->transfer_buffer; for (i = y; i < y + height ; i++) { const int line_offset = fb->base.pitches[0] * i; const int byte_offset = line_offset + (x * bpp); const int dev_byte_offset = (fb->base.width * bpp * i) + (x * bpp); if (udl_render_hline(dev, bpp, &urb, (char *) fb->obj->vmapping, &cmd, byte_offset, dev_byte_offset, width * bpp, &bytes_identical, &bytes_sent)) goto error; } if (cmd > (char *) urb->transfer_buffer) { /* Send partial buffer remaining before exiting */ int len = cmd - (char *) urb->transfer_buffer; ret = udl_submit_urb(dev, urb, len); bytes_sent += len; } else udl_urb_completion(urb); error: atomic_add(bytes_sent, &udl->bytes_sent); atomic_add(bytes_identical, &udl->bytes_identical); atomic_add(width*height*bpp, &udl->bytes_rendered); end_cycles = get_cycles(); atomic_add(((unsigned int) ((end_cycles - start_cycles) >> 10)), /* Kcycles */ &udl->cpu_kcycles_used); return 0; } static int udl_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { unsigned long start = vma->vm_start; unsigned long size = vma->vm_end - vma->vm_start; unsigned long offset; unsigned long page, pos; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) return -EINVAL; offset = vma->vm_pgoff << PAGE_SHIFT; if (offset > info->fix.smem_len || size > info->fix.smem_len - offset) return -EINVAL; pos = (unsigned long)info->fix.smem_start + offset; pr_notice("mmap() framebuffer addr:%lu size:%lu\n", pos, size); /* We don't want the framebuffer to be mapped encrypted */ vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot); while (size > 0) { page = vmalloc_to_pfn((void *)pos); if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) return -EAGAIN; start += PAGE_SIZE; pos += PAGE_SIZE; if (size > PAGE_SIZE) size -= PAGE_SIZE; else size = 0; } /* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by remap_pfn_range() */ return 0; } /* * It's common for several clients to have framebuffer open simultaneously. * e.g. both fbcon and X. Makes things interesting. * Assumes caller is holding info->lock (for open and release at least) */ static int udl_fb_open(struct fb_info *info, int user) { struct udl_fbdev *ufbdev = info->par; struct drm_device *dev = ufbdev->ufb.base.dev; struct udl_device *udl = dev->dev_private; /* If the USB device is gone, we don't accept new opens */ if (drm_dev_is_unplugged(udl->ddev)) return -ENODEV; ufbdev->fb_count++; #ifdef CONFIG_DRM_FBDEV_EMULATION if (fb_defio && (info->fbdefio == NULL)) { /* enable defio at last moment if not disabled by client */ struct fb_deferred_io *fbdefio; fbdefio = kmalloc(sizeof(struct fb_deferred_io), GFP_KERNEL); if (fbdefio) { fbdefio->delay = DL_DEFIO_WRITE_DELAY; fbdefio->deferred_io = drm_fb_helper_deferred_io; } info->fbdefio = fbdefio; fb_deferred_io_init(info); } #endif pr_notice("open /dev/fb%d user=%d fb_info=%p count=%d\n", info->node, user, info, ufbdev->fb_count); return 0; } /* * Assumes caller is holding info->lock mutex (for open and release at least) */ static int udl_fb_release(struct fb_info *info, int user) { struct udl_fbdev *ufbdev = info->par; ufbdev->fb_count--; #ifdef CONFIG_DRM_FBDEV_EMULATION if ((ufbdev->fb_count == 0) && (info->fbdefio)) { fb_deferred_io_cleanup(info); kfree(info->fbdefio); info->fbdefio = NULL; info->fbops->fb_mmap = udl_fb_mmap; } #endif pr_warn("released /dev/fb%d user=%d count=%d\n", info->node, user, ufbdev->fb_count); return 0; } static struct fb_ops udlfb_ops = { .owner = THIS_MODULE, DRM_FB_HELPER_DEFAULT_OPS, .fb_fillrect = drm_fb_helper_sys_fillrect, .fb_copyarea = drm_fb_helper_sys_copyarea, .fb_imageblit = drm_fb_helper_sys_imageblit, .fb_mmap = udl_fb_mmap, .fb_open = udl_fb_open, .fb_release = udl_fb_release, }; static int udl_user_framebuffer_dirty(struct drm_framebuffer *fb, struct drm_file *file, unsigned flags, unsigned color, struct drm_clip_rect *clips, unsigned num_clips) { struct udl_framebuffer *ufb = to_udl_fb(fb); int i; int ret = 0; drm_modeset_lock_all(fb->dev); if (!ufb->active_16) goto unlock; if (ufb->obj->base.import_attach) { ret = dma_buf_begin_cpu_access(ufb->obj->base.import_attach->dmabuf, DMA_FROM_DEVICE); if (ret) goto unlock; } for (i = 0; i < num_clips; i++) { ret = udl_handle_damage(ufb, clips[i].x1, clips[i].y1, clips[i].x2 - clips[i].x1, clips[i].y2 - clips[i].y1); if (ret) break; } if (ufb->obj->base.import_attach) { ret = dma_buf_end_cpu_access(ufb->obj->base.import_attach->dmabuf, DMA_FROM_DEVICE); } unlock: drm_modeset_unlock_all(fb->dev); return ret; } static void udl_user_framebuffer_destroy(struct drm_framebuffer *fb) { struct udl_framebuffer *ufb = to_udl_fb(fb); if (ufb->obj) drm_gem_object_put_unlocked(&ufb->obj->base); drm_framebuffer_cleanup(fb); kfree(ufb); } static const struct drm_framebuffer_funcs udlfb_funcs = { .destroy = udl_user_framebuffer_destroy, .dirty = udl_user_framebuffer_dirty, }; static int udl_framebuffer_init(struct drm_device *dev, struct udl_framebuffer *ufb, const struct drm_mode_fb_cmd2 *mode_cmd, struct udl_gem_object *obj) { int ret; ufb->obj = obj; drm_helper_mode_fill_fb_struct(dev, &ufb->base, mode_cmd); ret = drm_framebuffer_init(dev, &ufb->base, &udlfb_funcs); return ret; } static int udlfb_create(struct drm_fb_helper *helper, struct drm_fb_helper_surface_size *sizes) { struct udl_fbdev *ufbdev = container_of(helper, struct udl_fbdev, helper); struct drm_device *dev = ufbdev->helper.dev; struct fb_info *info; struct drm_framebuffer *fb; struct drm_mode_fb_cmd2 mode_cmd; struct udl_gem_object *obj; uint32_t size; int ret = 0; if (sizes->surface_bpp == 24) sizes->surface_bpp = 32; mode_cmd.width = sizes->surface_width; mode_cmd.height = sizes->surface_height; mode_cmd.pitches[0] = mode_cmd.width * ((sizes->surface_bpp + 7) / 8); mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp, sizes->surface_depth); size = mode_cmd.pitches[0] * mode_cmd.height; size = ALIGN(size, PAGE_SIZE); obj = udl_gem_alloc_object(dev, size); if (!obj) goto out; ret = udl_gem_vmap(obj); if (ret) { DRM_ERROR("failed to vmap fb\n"); goto out_gfree; } info = drm_fb_helper_alloc_fbi(helper); if (IS_ERR(info)) { ret = PTR_ERR(info); goto out_gfree; } info->par = ufbdev; ret = udl_framebuffer_init(dev, &ufbdev->ufb, &mode_cmd, obj); if (ret) goto out_gfree; fb = &ufbdev->ufb.base; ufbdev->helper.fb = fb; strcpy(info->fix.id, "udldrmfb"); info->screen_base = ufbdev->ufb.obj->vmapping; info->fix.smem_len = size; info->fix.smem_start = (unsigned long)ufbdev->ufb.obj->vmapping; info->fbops = &udlfb_ops; drm_fb_helper_fill_fix(info, fb->pitches[0], fb->format->depth); drm_fb_helper_fill_var(info, &ufbdev->helper, sizes->fb_width, sizes->fb_height); DRM_DEBUG_KMS("allocated %dx%d vmal %p\n", fb->width, fb->height, ufbdev->ufb.obj->vmapping); return ret; out_gfree: drm_gem_object_put_unlocked(&ufbdev->ufb.obj->base); out: return ret; } static const struct drm_fb_helper_funcs udl_fb_helper_funcs = { .fb_probe = udlfb_create, }; static void udl_fbdev_destroy(struct drm_device *dev, struct udl_fbdev *ufbdev) { drm_fb_helper_unregister_fbi(&ufbdev->helper); drm_fb_helper_fini(&ufbdev->helper); drm_framebuffer_unregister_private(&ufbdev->ufb.base); drm_framebuffer_cleanup(&ufbdev->ufb.base); drm_gem_object_put_unlocked(&ufbdev->ufb.obj->base); } int udl_fbdev_init(struct drm_device *dev) { struct udl_device *udl = dev->dev_private; int bpp_sel = fb_bpp; struct udl_fbdev *ufbdev; int ret; ufbdev = kzalloc(sizeof(struct udl_fbdev), GFP_KERNEL); if (!ufbdev) return -ENOMEM; udl->fbdev = ufbdev; drm_fb_helper_prepare(dev, &ufbdev->helper, &udl_fb_helper_funcs); ret = drm_fb_helper_init(dev, &ufbdev->helper, 1); if (ret) goto free; ret = drm_fb_helper_single_add_all_connectors(&ufbdev->helper); if (ret) goto fini; /* disable all the possible outputs/crtcs before entering KMS mode */ drm_helper_disable_unused_functions(dev); ret = drm_fb_helper_initial_config(&ufbdev->helper, bpp_sel); if (ret) goto fini; return 0; fini: drm_fb_helper_fini(&ufbdev->helper); free: kfree(ufbdev); return ret; } void udl_fbdev_cleanup(struct drm_device *dev) { struct udl_device *udl = dev->dev_private; if (!udl->fbdev) return; udl_fbdev_destroy(dev, udl->fbdev); kfree(udl->fbdev); udl->fbdev = NULL; } void udl_fbdev_unplug(struct drm_device *dev) { struct udl_device *udl = dev->dev_private; struct udl_fbdev *ufbdev; if (!udl->fbdev) return; ufbdev = udl->fbdev; drm_fb_helper_unlink_fbi(&ufbdev->helper); } struct drm_framebuffer * udl_fb_user_fb_create(struct drm_device *dev, struct drm_file *file, const struct drm_mode_fb_cmd2 *mode_cmd) { struct drm_gem_object *obj; struct udl_framebuffer *ufb; int ret; uint32_t size; obj = drm_gem_object_lookup(file, mode_cmd->handles[0]); if (obj == NULL) return ERR_PTR(-ENOENT); size = mode_cmd->pitches[0] * mode_cmd->height; size = ALIGN(size, PAGE_SIZE); if (size > obj->size) { DRM_ERROR("object size not sufficient for fb %d %zu %d %d\n", size, obj->size, mode_cmd->pitches[0], mode_cmd->height); return ERR_PTR(-ENOMEM); } ufb = kzalloc(sizeof(*ufb), GFP_KERNEL); if (ufb == NULL) return ERR_PTR(-ENOMEM); ret = udl_framebuffer_init(dev, ufb, mode_cmd, to_udl_bo(obj)); if (ret) { kfree(ufb); return ERR_PTR(-EINVAL); } return &ufb->base; }
24.820076
121
0.694697
[ "object" ]
2ec568ff1fa089624caee552cb17f4f2df85b8f1
66,089
c
C
build/externals/build_sparsehash/experimental/libchash.c
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
20
2015-05-08T02:43:27.000Z
2018-03-08T11:08:17.000Z
build/externals/build_sparsehash/experimental/libchash.c
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
5
2015-05-06T23:43:04.000Z
2015-08-13T19:14:37.000Z
build/externals/build_sparsehash/experimental/libchash.c
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
4
2015-05-19T02:37:29.000Z
2021-06-09T02:28:20.000Z
/* Copyright (c) 1998 - 2005, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. 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. * * --- * Author: Craig Silverstein * * This library is intended to be used for in-memory hash tables, * though it provides rudimentary permanent-storage capabilities. * It attempts to be fast, portable, and small. The best algorithm * to fulfill these goals is an internal probing hashing algorithm, * as in Knuth, _Art of Computer Programming_, vol III. Unlike * chained (open) hashing, it doesn't require a pointer for every * item, yet it is still constant time lookup in practice. * * Also to save space, we let the contents (both data and key) that * you insert be a union: if the key/data is small, we store it * directly in the hashtable, otherwise we store a pointer to it. * To keep you from having to figure out which, use KEY_PTR and * PTR_KEY to convert between the arguments to these functions and * a pointer to the real data. For instance: * char key[] = "ab", *key2; * HTItem *bck; HashTable *ht; * HashInsert(ht, PTR_KEY(ht, key), 0); * bck = HashFind(ht, PTR_KEY(ht, "ab")); * key2 = KEY_PTR(ht, bck->key); * * There are a rich set of operations supported: * AllocateHashTable() -- Allocates a hashtable structure and * returns it. * cchKey: if it's a positive number, then each key is a * fixed-length record of that length. If it's 0, * the key is assumed to be a \0-terminated string. * fSaveKey: normally, you are responsible for allocating * space for the key. If this is 1, we make a * copy of the key for you. * ClearHashTable() -- Removes everything from a hashtable * FreeHashTable() -- Frees memory used by a hashtable * * HashFind() -- takes a key (use PTR_KEY) and returns the * HTItem containing that key, or NULL if the * key is not in the hashtable. * HashFindLast() -- returns the item found by last HashFind() * HashFindOrInsert() -- inserts the key/data pair if the key * is not already in the hashtable, or * returns the appropraite HTItem if it is. * HashFindOrInsertItem() -- takes key/data as an HTItem. * HashInsert() -- adds a key/data pair to the hashtable. What * it does if the key is already in the table * depends on the value of SAMEKEY_OVERWRITE. * HashInsertItem() -- takes key/data as an HTItem. * HashDelete() -- removes a key/data pair from the hashtable, * if it's there. RETURNS 1 if it was there, * 0 else. * If you use sparse tables and never delete, the full data * space is available. Otherwise we steal -2 (maybe -3), * so you can't have data fields with those values. * HashDeleteLast() -- deletes the item returned by the last Find(). * * HashFirstBucket() -- used to iterate over the buckets in a * hashtable. DON'T INSERT OR DELETE WHILE * ITERATING! You can't nest iterations. * HashNextBucket() -- RETURNS NULL at the end of iterating. * * HashSetDeltaGoalSize() -- if you're going to insert 1000 items * at once, call this fn with arg 1000. * It grows the table more intelligently. * * HashSave() -- saves the hashtable to a file. It saves keys ok, * but it doesn't know how to interpret the data field, * so if the data field is a pointer to some complex * structure, you must send a function that takes a * file pointer and a pointer to the structure, and * write whatever you want to write. It should return * the number of bytes written. If the file is NULL, * it should just return the number of bytes it would * write, without writing anything. * If your data field is just an integer, not a * pointer, just send NULL for the function. * HashLoad() -- loads a hashtable. It needs a function that takes * a file and the size of the structure, and expects * you to read in the structure and return a pointer * to it. You must do memory allocation, etc. If * the data is just a number, send NULL. * HashLoadKeys() -- unlike HashLoad(), doesn't load the data off disk * until needed. This saves memory, but if you look * up the same key a lot, it does a disk access each * time. * You can't do Insert() or Delete() on hashtables that were loaded * from disk. * * See libchash.h for parameters you can modify. Make sure LOG_WORD_SIZE * is defined correctly for your machine! (5 for 32 bit words, 6 for 64). */ #include <google/sparsehash/sparseconfig.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* for strcmp, memcmp, etc */ #include <sys/types.h> /* ULTRIX needs this for in.h */ #include <netinet/in.h> /* for reading/writing hashtables */ #include <assert.h> #include "libchash.h" /* all the types */ /* if keys are stored directly but cchKey is less than sizeof(ulong), */ /* this cuts off the bits at the end */ char grgKeyTruncMask[sizeof(ulong)][sizeof(ulong)]; #define KEY_TRUNC(ht, key) \ ( STORES_PTR(ht) || (ht)->cchKey == sizeof(ulong) \ ? (key) : ((key) & *(ulong *)&(grgKeyTruncMask[(ht)->cchKey][0])) ) /* round num up to a multiple of wordsize. (LOG_WORD_SIZE-3 is in bytes) */ #define WORD_ROUND(num) ( ((num-1) | ((1<<(LOG_WORD_SIZE-3))-1)) + 1 ) #define NULL_TERMINATED 0 /* val of cchKey if keys are null-term strings */ /* Useful operations we do to keys: compare them, copy them, free them */ #define KEY_CMP(ht, key1, key2) ( !STORES_PTR(ht) ? (key1) - (key2) : \ (key1) == (key2) ? 0 : \ HashKeySize(ht) == NULL_TERMINATED ? \ strcmp((char *)key1, (char *)key2) :\ memcmp((void *)key1, (void *)key2, \ HashKeySize(ht)) ) #define COPY_KEY(ht, keyTo, keyFrom) do \ if ( !STORES_PTR(ht) || !(ht)->fSaveKeys ) \ (keyTo) = (keyFrom); /* just copy pointer or info */\ else if ( (ht)->cchKey == NULL_TERMINATED ) /* copy 0-term.ed str */\ { \ (keyTo) = (ulong)HTsmalloc( WORD_ROUND(strlen((char *)(keyFrom))+1) ); \ strcpy((char *)(keyTo), (char *)(keyFrom)); \ } \ else \ { \ (keyTo) = (ulong) HTsmalloc( WORD_ROUND((ht)->cchKey) ); \ memcpy( (char *)(keyTo), (char *)(keyFrom), (ht)->cchKey); \ } \ while ( 0 ) #define FREE_KEY(ht, key) do \ if ( STORES_PTR(ht) && (ht)->fSaveKeys ) \ if ( (ht)->cchKey == NULL_TERMINATED ) \ HTfree((char *)(key), WORD_ROUND(strlen((char *)(key))+1)); \ else \ HTfree((char *)(key), WORD_ROUND((ht)->cchKey)); \ while ( 0 ) /* the following are useful for bitmaps */ /* Format is like this (if 1 word = 4 bits): 3210 7654 ba98 fedc ... */ typedef ulong HTBitmapPart; /* this has to be unsigned, for >> */ typedef HTBitmapPart HTBitmap[1<<LOG_BM_WORDS]; typedef ulong HTOffset; /* something big enough to hold offsets */ #define BM_BYTES(cBuckets) /* we must ensure it's a multiple of word size */\ ( (((cBuckets) + 8*sizeof(ulong)-1) >> LOG_WORD_SIZE) << (LOG_WORD_SIZE-3) ) #define MOD2(i, logmod) ( (i) & ((1<<(logmod))-1) ) #define DIV_NUM_ENTRIES(i) ( (i) >> LOG_WORD_SIZE ) #define MOD_NUM_ENTRIES(i) ( MOD2(i, LOG_WORD_SIZE) ) #define MODBIT(i) ( ((ulong)1) << MOD_NUM_ENTRIES(i) ) #define TEST_BITMAP(bm, i) ( (bm)[DIV_NUM_ENTRIES(i)] & MODBIT(i) ? 1 : 0 ) #define SET_BITMAP(bm, i) (bm)[DIV_NUM_ENTRIES(i)] |= MODBIT(i) #define CLEAR_BITMAP(bm, i) (bm)[DIV_NUM_ENTRIES(i)] &= ~MODBIT(i) /* the following are useful for reading and writing hashtables */ #define READ_UL(fp, data) \ do { \ long _ul; \ fread(&_ul, sizeof(_ul), 1, (fp)); \ data = ntohl(_ul); \ } while (0) #define WRITE_UL(fp, data) \ do { \ long _ul = htonl((long)(data)); \ fwrite(&_ul, sizeof(_ul), 1, (fp)); \ } while (0) /* Moves data from disk to memory if necessary. Note dataRead cannot be * * NULL, because then we might as well (and do) load the data into memory */ #define LOAD_AND_RETURN(ht, loadCommand) /* lC returns an HTItem * */ \ if ( !(ht)->fpData ) /* data is stored in memory */ \ return (loadCommand); \ else /* must read data off of disk */ \ { \ int cchData; \ HTItem *bck; \ if ( (ht)->bckData.data ) free((char *)(ht)->bckData.data); \ ht->bckData.data = (ulong)NULL; /* needed if loadCommand fails */ \ bck = (loadCommand); \ if ( bck == NULL ) /* loadCommand failed: key not found */ \ return NULL; \ else \ (ht)->bckData = *bck; \ fseek(ht->fpData, (ht)->bckData.data, SEEK_SET); \ READ_UL((ht)->fpData, cchData); \ (ht)->bckData.data = (ulong)(ht)->dataRead((ht)->fpData, cchData); \ return &((ht)->bckData); \ } /* ======================================================================== */ /* UTILITY ROUTINES */ /* ---------------------- */ /* HTsmalloc() -- safe malloc * allocates memory, or crashes if the allocation fails. */ static void *HTsmalloc(unsigned long size) { void *retval; if ( size == 0 ) return NULL; retval = (void *)malloc(size); if ( !retval ) { fprintf(stderr, "HTsmalloc: Unable to allocate %lu bytes of memory\n", size); exit(1); } return retval; } /* HTscalloc() -- safe calloc * allocates memory and initializes it to 0, or crashes if * the allocation fails. */ static void *HTscalloc(unsigned long size) { void *retval; retval = (void *)calloc(size, 1); if ( !retval && size > 0 ) { fprintf(stderr, "HTscalloc: Unable to allocate %lu bytes of memory\n", size); exit(1); } return retval; } /* HTsrealloc() -- safe calloc * grows the amount of memory from a source, or crashes if * the allocation fails. */ static void *HTsrealloc(void *ptr, unsigned long new_size, long delta) { if ( ptr == NULL ) return HTsmalloc(new_size); ptr = realloc(ptr, new_size); if ( !ptr && new_size > 0 ) { fprintf(stderr, "HTsrealloc: Unable to reallocate %lu bytes of memory\n", new_size); exit(1); } return ptr; } /* HTfree() -- keep track of memory use * frees memory using free, but updates count of how much memory * is being used. */ static void HTfree(void *ptr, unsigned long size) { if ( size > 0 ) /* some systems seem to not like freeing NULL */ free(ptr); } /*************************************************************************\ | HTcopy() | | Sometimes we interpret data as a ulong. But ulongs must be | | aligned on some machines, so instead of casting we copy. | \*************************************************************************/ unsigned long HTcopy(char *ul) { unsigned long retval; memcpy(&retval, ul, sizeof(retval)); return retval; } /*************************************************************************\ | HTSetupKeyTrunc() | | If keys are stored directly but cchKey is less than | | sizeof(ulong), this cuts off the bits at the end. | \*************************************************************************/ static void HTSetupKeyTrunc(void) { int i, j; for ( i = 0; i < sizeof(unsigned long); i++ ) for ( j = 0; j < sizeof(unsigned long); j++ ) grgKeyTruncMask[i][j] = j < i ? 255 : 0; /* chars have 8 bits */ } /* ======================================================================== */ /* TABLE ROUTINES */ /* -------------------- */ /* The idea is that a hashtable with (logically) t buckets is divided * into t/M groups of M buckets each. (M is a constant set in * LOG_BM_WORDS for efficiency.) Each group is stored sparsely. * Thus, inserting into the table causes some array to grow, which is * slow but still constant time. Lookup involves doing a * logical-position-to-sparse-position lookup, which is also slow but * constant time. The larger M is, the slower these operations are * but the less overhead (slightly). * * To store the sparse array, we store a bitmap B, where B[i] = 1 iff * bucket i is non-empty. Then to look up bucket i we really look up * array[# of 1s before i in B]. This is constant time for fixed M. * * Terminology: the position of an item in the overall table (from * 1 .. t) is called its "location." The logical position in a group * (from 1 .. M ) is called its "position." The actual location in * the array (from 1 .. # of non-empty buckets in the group) is * called its "offset." * * The following operations are supported: * o Allocate an array with t buckets, all empty * o Free a array (but not whatever was stored in the buckets) * o Tell whether or not a bucket is empty * o Return a bucket with a given location * o Set the value of a bucket at a given location * o Iterate through all the buckets in the array * o Read and write an occupancy bitmap to disk * o Return how much memory is being allocated by the array structure */ #ifndef SparseBucket /* by default, each bucket holds an HTItem */ #define SparseBucket HTItem #endif typedef struct SparseBin { SparseBucket *binSparse; HTBitmap bmOccupied; /* bmOccupied[i] is 1 if bucket i has an item */ short cOccupied; /* size of binSparse; useful for iterators, eg */ } SparseBin; typedef struct SparseIterator { long posGroup; long posOffset; SparseBin *binSparse; /* state info, to avoid args for NextBucket() */ ulong cBuckets; } SparseIterator; #define LOG_LOW_BIN_SIZE ( LOG_BM_WORDS+LOG_WORD_SIZE ) #define SPARSE_GROUPS(cBuckets) ( (((cBuckets)-1) >> LOG_LOW_BIN_SIZE) + 1 ) /* we need a small function to figure out # of items set in the bm */ static HTOffset EntriesUpto(HTBitmapPart *bm, int i) { /* returns # of set bits in 0..i-1 */ HTOffset retval = 0; static HTOffset rgcBits[256] = /* # of bits set in one char */ {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; if ( i == 0 ) return 0; for ( ; i > sizeof(*bm)*8; i -= sizeof(*bm)*8, bm++ ) { /* think of it as loop unrolling */ #if LOG_WORD_SIZE >= 3 /* 1 byte per word, or more */ retval += rgcBits[*bm & 255]; /* get the low byte */ #if LOG_WORD_SIZE >= 4 /* at least 2 bytes */ retval += rgcBits[(*bm >> 8) & 255]; #if LOG_WORD_SIZE >= 5 /* at least 4 bytes */ retval += rgcBits[(*bm >> 16) & 255]; retval += rgcBits[(*bm >> 24) & 255]; #if LOG_WORD_SIZE >= 6 /* 8 bytes! */ retval += rgcBits[(*bm >> 32) & 255]; retval += rgcBits[(*bm >> 40) & 255]; retval += rgcBits[(*bm >> 48) & 255]; retval += rgcBits[(*bm >> 56) & 255]; #if LOG_WORD_SIZE >= 7 /* not a concern for a while... */ #error Need to rewrite EntriesUpto to support such big words #endif /* >8 bytes */ #endif /* 8 bytes */ #endif /* 4 bytes */ #endif /* 2 bytes */ #endif /* 1 byte */ } switch ( i ) { /* from 0 to 63 */ case 0: return retval; #if LOG_WORD_SIZE >= 3 /* 1 byte per word, or more */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: return (retval + rgcBits[*bm & ((1 << i)-1)]); #if LOG_WORD_SIZE >= 4 /* at least 2 bytes */ case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & ((1 << (i-8))-1)]); #if LOG_WORD_SIZE >= 5 /* at least 4 bytes */ case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & ((1 << (i-16))-1)]); case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & ((1 << (i-24))-1)]); #if LOG_WORD_SIZE >= 6 /* 8 bytes! */ case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] + rgcBits[(*bm >> 32) & ((1 << (i-32))-1)]); case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] + rgcBits[(*bm >> 32) & 255] + rgcBits[(*bm >> 40) & ((1 << (i-40))-1)]); case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] + rgcBits[(*bm >> 32) & 255] + rgcBits[(*bm >> 40) & 255] + rgcBits[(*bm >> 48) & ((1 << (i-48))-1)]); case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] + rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] + rgcBits[(*bm >> 32) & 255] + rgcBits[(*bm >> 40) & 255] + rgcBits[(*bm >> 48) & 255] + rgcBits[(*bm >> 56) & ((1 << (i-56))-1)]); #endif /* 8 bytes */ #endif /* 4 bytes */ #endif /* 2 bytes */ #endif /* 1 byte */ } assert("" == "word size is too big in EntriesUpto()"); return -1; } #define SPARSE_POS_TO_OFFSET(bm, i) ( EntriesUpto(&((bm)[0]), i) ) #define SPARSE_BUCKET(bin, location) \ ( (bin)[(location) >> LOG_LOW_BIN_SIZE].binSparse + \ SPARSE_POS_TO_OFFSET((bin)[(location)>>LOG_LOW_BIN_SIZE].bmOccupied, \ MOD2(location, LOG_LOW_BIN_SIZE)) ) /*************************************************************************\ | SparseAllocate() | | SparseFree() | | Allocates, sets-to-empty, and frees a sparse array. All you need | | to tell me is how many buckets you want. I return the number of | | buckets I actually allocated, setting the array as a parameter. | | Note that you have to set auxilliary parameters, like cOccupied. | \*************************************************************************/ static ulong SparseAllocate(SparseBin **pbinSparse, ulong cBuckets) { int cGroups = SPARSE_GROUPS(cBuckets); *pbinSparse = (SparseBin *) HTscalloc(sizeof(**pbinSparse) * cGroups); return cGroups << LOG_LOW_BIN_SIZE; } static SparseBin *SparseFree(SparseBin *binSparse, ulong cBuckets) { ulong iGroup, cGroups = SPARSE_GROUPS(cBuckets); for ( iGroup = 0; iGroup < cGroups; iGroup++ ) HTfree(binSparse[iGroup].binSparse, (sizeof(*binSparse[iGroup].binSparse) * binSparse[iGroup].cOccupied)); HTfree(binSparse, sizeof(*binSparse) * cGroups); return NULL; } /*************************************************************************\ | SparseIsEmpty() | | SparseFind() | | You give me a location (ie a number between 1 and t), and I | | return the bucket at that location, or NULL if the bucket is | | empty. It's OK to call Find() on an empty table. | \*************************************************************************/ static int SparseIsEmpty(SparseBin *binSparse, ulong location) { return !TEST_BITMAP(binSparse[location>>LOG_LOW_BIN_SIZE].bmOccupied, MOD2(location, LOG_LOW_BIN_SIZE)); } static SparseBucket *SparseFind(SparseBin *binSparse, ulong location) { if ( SparseIsEmpty(binSparse, location) ) return NULL; return SPARSE_BUCKET(binSparse, location); } /*************************************************************************\ | SparseInsert() | | You give me a location, and contents to put there, and I insert | | into that location and RETURN a pointer to the location. If | | bucket was already occupied, I write over the contents only if | | *pfOverwrite is 1. We set *pfOverwrite to 1 if there was someone | | there (whether or not we overwrote) and 0 else. | \*************************************************************************/ static SparseBucket *SparseInsert(SparseBin *binSparse, SparseBucket *bckInsert, ulong location, int *pfOverwrite) { SparseBucket *bckPlace; HTOffset offset; bckPlace = SparseFind(binSparse, location); if ( bckPlace ) /* means we replace old contents */ { if ( *pfOverwrite ) *bckPlace = *bckInsert; *pfOverwrite = 1; return bckPlace; } binSparse += (location >> LOG_LOW_BIN_SIZE); offset = SPARSE_POS_TO_OFFSET(binSparse->bmOccupied, MOD2(location, LOG_LOW_BIN_SIZE)); binSparse->binSparse = (SparseBucket *) HTsrealloc(binSparse->binSparse, sizeof(*binSparse->binSparse) * ++binSparse->cOccupied, sizeof(*binSparse->binSparse)); memmove(binSparse->binSparse + offset+1, binSparse->binSparse + offset, (binSparse->cOccupied-1 - offset) * sizeof(*binSparse->binSparse)); binSparse->binSparse[offset] = *bckInsert; SET_BITMAP(binSparse->bmOccupied, MOD2(location, LOG_LOW_BIN_SIZE)); *pfOverwrite = 0; return binSparse->binSparse + offset; } /*************************************************************************\ | SparseFirstBucket() | | SparseNextBucket() | | SparseCurrentBit() | | Iterate through the occupied buckets of a dense hashtable. You | | must, of course, have allocated space yourself for the iterator. | \*************************************************************************/ static SparseBucket *SparseNextBucket(SparseIterator *iter) { if ( iter->posOffset != -1 && /* not called from FirstBucket()? */ (++iter->posOffset < iter->binSparse[iter->posGroup].cOccupied) ) return iter->binSparse[iter->posGroup].binSparse + iter->posOffset; iter->posOffset = 0; /* start the next group */ for ( iter->posGroup++; iter->posGroup < SPARSE_GROUPS(iter->cBuckets); iter->posGroup++ ) if ( iter->binSparse[iter->posGroup].cOccupied > 0 ) return iter->binSparse[iter->posGroup].binSparse; /* + 0 */ return NULL; /* all remaining groups were empty */ } static SparseBucket *SparseFirstBucket(SparseIterator *iter, SparseBin *binSparse, ulong cBuckets) { iter->binSparse = binSparse; /* set it up for NextBucket() */ iter->cBuckets = cBuckets; iter->posOffset = -1; /* when we advance, we're at 0 */ iter->posGroup = -1; return SparseNextBucket(iter); } /*************************************************************************\ | SparseWrite() | | SparseRead() | | These are routines for storing a sparse hashtable onto disk. We | | store the number of buckets and a bitmap indicating which buckets | | are allocated (occupied). The actual contents of the buckets | | must be stored separately. | \*************************************************************************/ static void SparseWrite(FILE *fp, SparseBin *binSparse, ulong cBuckets) { ulong i, j; WRITE_UL(fp, cBuckets); for ( i = 0; i < SPARSE_GROUPS(cBuckets); i++ ) for ( j = 0; j < (1<<LOG_BM_WORDS); j++ ) WRITE_UL(fp, binSparse[i].bmOccupied[j]); } static ulong SparseRead(FILE *fp, SparseBin **pbinSparse) { ulong i, j, cBuckets; READ_UL(fp, cBuckets); /* actually, cBuckets is stored */ cBuckets = SparseAllocate(pbinSparse, cBuckets); for ( i = 0; i < SPARSE_GROUPS(cBuckets); i++ ) { for ( j = 0; j < (1<<LOG_BM_WORDS); j++ ) READ_UL(fp, (*pbinSparse)[i].bmOccupied[j]); (*pbinSparse)[i].cOccupied = SPARSE_POS_TO_OFFSET((*pbinSparse)[i].bmOccupied,1<<LOG_LOW_BIN_SIZE); (*pbinSparse)[i].binSparse = (SparseBucket *) HTsmalloc(sizeof(*((*pbinSparse)[i].binSparse)) * (*pbinSparse)[i].cOccupied); } return cBuckets; } /*************************************************************************\ | SparseMemory() | | SparseMemory() tells us how much memory is being allocated for | | the dense table. You need to tell me not only how many buckets | | there are, but how many are occupied. | \*************************************************************************/ static ulong SparseMemory(ulong cBuckets, ulong cOccupied) { return ( cOccupied * sizeof(SparseBucket) + SPARSE_GROUPS(cBuckets) * sizeof(SparseBin) ); } /* Just for fun, I also provide support for dense tables. These are * just regulr arrays. Access is fast, but they can get big. * Use Table(x) at the top of chash.h to decide which you want. * A disadvantage is we need to steal more of the data space for * indicating empty buckets. We choose -3. */ #ifndef DenseBucket /* by default, each bucket holds an HTItem */ #define DenseBucket HTItem #endif typedef struct DenseBin { /* needs to be a struct for C typing reasons */ DenseBucket *rgBuckets; /* A bin is an array of buckets */ } DenseBin; typedef struct DenseIterator { long pos; /* the actual iterator */ DenseBin *bin; /* state info, to avoid args for NextBucket() */ ulong cBuckets; } DenseIterator; #define DENSE_IS_EMPTY(bin, i) ( (bin)[i].data == EMPTY ) #define DENSE_SET_EMPTY(bin, i) (bin)[i].data = EMPTY /* fks-hash.h */ #define DENSE_SET_OCCUPIED(bin, i) (bin)[i].data = 1 /* not EMPTY */ static void DenseClear(DenseBin *bin, ulong cBuckets) { while ( cBuckets-- ) DENSE_SET_EMPTY(bin->rgBuckets, cBuckets); } static ulong DenseAllocate(DenseBin **pbin, ulong cBuckets) { *pbin = (DenseBin *) HTsmalloc(sizeof(*pbin)); (*pbin)->rgBuckets = (DenseBucket *) HTsmalloc(sizeof(*(*pbin)->rgBuckets) * cBuckets); DenseClear(*pbin, cBuckets); return cBuckets; } static DenseBin *DenseFree(DenseBin *bin, ulong cBuckets) { HTfree(bin->rgBuckets, sizeof(*bin->rgBuckets) * cBuckets); HTfree(bin, sizeof(*bin)); return NULL; } static int DenseIsEmpty(DenseBin *bin, ulong location) { return DENSE_IS_EMPTY(bin->rgBuckets, location); } static DenseBucket *DenseFind(DenseBin *bin, ulong location) { if ( DenseIsEmpty(bin, location) ) return NULL; return bin->rgBuckets + location; } static DenseBucket *DenseInsert(DenseBin *bin, DenseBucket *bckInsert, ulong location, int *pfOverwrite) { DenseBucket *bckPlace; bckPlace = DenseFind(bin, location); if ( bckPlace ) /* means something is already there */ { if ( *pfOverwrite ) *bckPlace = *bckInsert; *pfOverwrite = 1; /* set to 1 to indicate someone was there */ return bckPlace; } else { bin->rgBuckets[location] = *bckInsert; *pfOverwrite = 0; return bin->rgBuckets + location; } } static DenseBucket *DenseNextBucket(DenseIterator *iter) { for ( iter->pos++; iter->pos < iter->cBuckets; iter->pos++ ) if ( !DenseIsEmpty(iter->bin, iter->pos) ) return iter->bin->rgBuckets + iter->pos; return NULL; /* all remaining groups were empty */ } static DenseBucket *DenseFirstBucket(DenseIterator *iter, DenseBin *bin, ulong cBuckets) { iter->bin = bin; /* set it up for NextBucket() */ iter->cBuckets = cBuckets; iter->pos = -1; /* thus the next bucket will be 0 */ return DenseNextBucket(iter); } static void DenseWrite(FILE *fp, DenseBin *bin, ulong cBuckets) { ulong pos = 0, bit, bm; WRITE_UL(fp, cBuckets); while ( pos < cBuckets ) { bm = 0; for ( bit = 0; bit < 8*sizeof(ulong); bit++ ) { if ( !DenseIsEmpty(bin, pos) ) SET_BITMAP(&bm, bit); /* in fks-hash.h */ if ( ++pos == cBuckets ) break; } WRITE_UL(fp, bm); } } static ulong DenseRead(FILE *fp, DenseBin **pbin) { ulong pos = 0, bit, bm, cBuckets; READ_UL(fp, cBuckets); cBuckets = DenseAllocate(pbin, cBuckets); while ( pos < cBuckets ) { READ_UL(fp, bm); for ( bit = 0; bit < 8*sizeof(ulong); bit++ ) { if ( TEST_BITMAP(&bm, bit) ) /* in fks-hash.h */ DENSE_SET_OCCUPIED((*pbin)->rgBuckets, pos); else DENSE_SET_EMPTY((*pbin)->rgBuckets, pos); if ( ++pos == cBuckets ) break; } } return cBuckets; } static ulong DenseMemory(ulong cBuckets, ulong cOccupied) { return cBuckets * sizeof(DenseBucket); } /* ======================================================================== */ /* HASHING ROUTINES */ /* ---------------------- */ /* Implements a simple quadratic hashing scheme. We have a single hash * table of size t and a single hash function h(x). When inserting an * item, first we try h(x) % t. If it's occupied, we try h(x) + * i*(i-1)/2 % t for increasing values of i until we hit a not-occupied * space. To make this dynamic, we double the size of the hash table as * soon as more than half the cells are occupied. When deleting, we can * choose to shrink the hashtable when less than a quarter of the * cells are occupied, or we can choose never to shrink the hashtable. * For lookup, we check h(x) + i*(i-1)/2 % t (starting with i=0) until * we get a match or we hit an empty space. Note that as a result, * we can't make a cell empty on deletion, or lookups may end prematurely. * Instead we mark the cell as "deleted." We thus steal the value * DELETED as a possible "data" value. As long as data are pointers, * that's ok. * The hash increment we use, i(i-1)/2, is not the standard quadratic * hash increment, which is i^2. i(i-1)/2 covers the entire bucket space * when the hashtable size is a power of two, as it is for us. In fact, * the first n probes cover n distinct buckets; then it repeats. This * guarantees insertion will always succeed. * If you linear hashing, set JUMP in chash.h. You can also change * various other parameters there. */ /*************************************************************************\ | Hash() | | The hash function I use is due to Bob Jenkins (see | | http://burtleburtle.net/bob/hash/evahash.html | | According to http://burtleburtle.net/bob/c/lookup2.c, | | his implementation is public domain.) | | It takes 36 instructions, in 18 cycles if you're lucky. | | hashing depends on the fact the hashtable size is always a | | power of 2. cBuckets is probably ht->cBuckets. | \*************************************************************************/ #if LOG_WORD_SIZE == 5 /* 32 bit words */ #define mix(a,b,c) \ { \ a -= b; a -= c; a ^= (c>>13); \ b -= c; b -= a; b ^= (a<<8); \ c -= a; c -= b; c ^= (b>>13); \ a -= b; a -= c; a ^= (c>>12); \ b -= c; b -= a; b ^= (a<<16); \ c -= a; c -= b; c ^= (b>>5); \ a -= b; a -= c; a ^= (c>>3); \ b -= c; b -= a; b ^= (a<<10); \ c -= a; c -= b; c ^= (b>>15); \ } #ifdef WORD_HASH /* play with this on little-endian machines */ #define WORD_AT(ptr) ( *(ulong *)(ptr) ) #else #define WORD_AT(ptr) ( (ptr)[0] + ((ulong)(ptr)[1]<<8) + \ ((ulong)(ptr)[2]<<16) + ((ulong)(ptr)[3]<<24) ) #endif #elif LOG_WORD_SIZE == 6 /* 64 bit words */ #define mix(a,b,c) \ { \ a -= b; a -= c; a ^= (c>>43); \ b -= c; b -= a; b ^= (a<<9); \ c -= a; c -= b; c ^= (b>>8); \ a -= b; a -= c; a ^= (c>>38); \ b -= c; b -= a; b ^= (a<<23); \ c -= a; c -= b; c ^= (b>>5); \ a -= b; a -= c; a ^= (c>>35); \ b -= c; b -= a; b ^= (a<<49); \ c -= a; c -= b; c ^= (b>>11); \ a -= b; a -= c; a ^= (c>>12); \ b -= c; b -= a; b ^= (a<<18); \ c -= a; c -= b; c ^= (b>>22); \ } #ifdef WORD_HASH /* alpha is little-endian, btw */ #define WORD_AT(ptr) ( *(ulong *)(ptr) ) #else #define WORD_AT(ptr) ( (ptr)[0] + ((ulong)(ptr)[1]<<8) + \ ((ulong)(ptr)[2]<<16) + ((ulong)(ptr)[3]<<24) + \ ((ulong)(ptr)[4]<<32) + ((ulong)(ptr)[5]<<40) + \ ((ulong)(ptr)[6]<<48) + ((ulong)(ptr)[7]<<56) ) #endif #else /* neither 32 or 64 bit words */ #error This hash function can only hash 32 or 64 bit words. Sorry. #endif static ulong Hash(HashTable *ht, char *key, ulong cBuckets) { ulong a, b, c, cchKey, cchKeyOrig; cchKeyOrig = ht->cchKey == NULL_TERMINATED ? strlen(key) : ht->cchKey; a = b = c = 0x9e3779b9; /* the golden ratio; an arbitrary value */ for ( cchKey = cchKeyOrig; cchKey >= 3 * sizeof(ulong); cchKey -= 3 * sizeof(ulong), key += 3 * sizeof(ulong) ) { a += WORD_AT(key); b += WORD_AT(key + sizeof(ulong)); c += WORD_AT(key + sizeof(ulong)*2); mix(a,b,c); } c += cchKeyOrig; switch ( cchKey ) { /* deal with rest. Cases fall through */ #if LOG_WORD_SIZE == 5 case 11: c += (ulong)key[10]<<24; case 10: c += (ulong)key[9]<<16; case 9 : c += (ulong)key[8]<<8; /* the first byte of c is reserved for the length */ case 8 : b += WORD_AT(key+4); a+= WORD_AT(key); break; case 7 : b += (ulong)key[6]<<16; case 6 : b += (ulong)key[5]<<8; case 5 : b += key[4]; case 4 : a += WORD_AT(key); break; case 3 : a += (ulong)key[2]<<16; case 2 : a += (ulong)key[1]<<8; case 1 : a += key[0]; /* case 0 : nothing left to add */ #elif LOG_WORD_SIZE == 6 case 23: c += (ulong)key[22]<<56; case 22: c += (ulong)key[21]<<48; case 21: c += (ulong)key[20]<<40; case 20: c += (ulong)key[19]<<32; case 19: c += (ulong)key[18]<<24; case 18: c += (ulong)key[17]<<16; case 17: c += (ulong)key[16]<<8; /* the first byte of c is reserved for the length */ case 16: b += WORD_AT(key+8); a+= WORD_AT(key); break; case 15: b += (ulong)key[14]<<48; case 14: b += (ulong)key[13]<<40; case 13: b += (ulong)key[12]<<32; case 12: b += (ulong)key[11]<<24; case 11: b += (ulong)key[10]<<16; case 10: b += (ulong)key[ 9]<<8; case 9: b += (ulong)key[ 8]; case 8: a += WORD_AT(key); break; case 7: a += (ulong)key[ 6]<<48; case 6: a += (ulong)key[ 5]<<40; case 5: a += (ulong)key[ 4]<<32; case 4: a += (ulong)key[ 3]<<24; case 3: a += (ulong)key[ 2]<<16; case 2: a += (ulong)key[ 1]<<8; case 1: a += (ulong)key[ 0]; /* case 0: nothing left to add */ #endif } mix(a,b,c); return c & (cBuckets-1); } /*************************************************************************\ | Rehash() | | You give me a hashtable, a new size, and a bucket to follow, and | | I resize the hashtable's bin to be the new size, rehashing | | everything in it. I keep particular track of the bucket you pass | | in, and RETURN a pointer to where the item in the bucket got to. | | (If you pass in NULL, I return an arbitrary pointer.) | \*************************************************************************/ static HTItem *Rehash(HashTable *ht, ulong cNewBuckets, HTItem *bckWatch) { Table *tableNew; ulong iBucketFirst; HTItem *bck, *bckNew = NULL; ulong offset; /* the i in h(x) + i*(i-1)/2 */ int fOverwrite = 0; /* not an issue: there can be no collisions */ assert( ht->table ); cNewBuckets = Table(Allocate)(&tableNew, cNewBuckets); /* Since we RETURN the new position of bckWatch, we want * * to make sure it doesn't get moved due to some table * * rehashing that comes after it's inserted. Thus, we * * have to put it in last. This makes the loop weird. */ for ( bck = HashFirstBucket(ht); ; bck = HashNextBucket(ht) ) { if ( bck == NULL ) /* we're done iterating, so look at bckWatch */ { bck = bckWatch; if ( bck == NULL ) /* I guess bckWatch wasn't specified */ break; } else if ( bck == bckWatch ) continue; /* ignore if we see it during the iteration */ offset = 0; /* a new i for a new bucket */ for ( iBucketFirst = Hash(ht, KEY_PTR(ht, bck->key), cNewBuckets); !Table(IsEmpty)(tableNew, iBucketFirst); iBucketFirst = (iBucketFirst + JUMP(KEY_PTR(ht,bck->key), offset)) & (cNewBuckets-1) ) ; bckNew = Table(Insert)(tableNew, bck, iBucketFirst, &fOverwrite); if ( bck == bckWatch ) /* we're done with the last thing to do */ break; } Table(Free)(ht->table, ht->cBuckets); ht->table = tableNew; ht->cBuckets = cNewBuckets; ht->cDeletedItems = 0; return bckNew; /* new position of bckWatch, which was inserted last */ } /*************************************************************************\ | Find() | | Does the quadratic searching stuff. RETURNS NULL if we don't | | find an object with the given key, and a pointer to the Item | | holding the key, if we do. Also sets posLastFind. If piEmpty is | | non-NULL, we set it to the first open bucket we pass; helpful for | | doing a later insert if the search fails, for instance. | \*************************************************************************/ static HTItem *Find(HashTable *ht, ulong key, ulong *piEmpty) { ulong iBucketFirst; HTItem *item; ulong offset = 0; /* the i in h(x) + i*(i-1)/2 */ int fFoundEmpty = 0; /* set when we pass over an empty bucket */ ht->posLastFind = NULL; /* set up for failure: a new find starts */ if ( ht->table == NULL ) /* empty hash table: find is bound to fail */ return NULL; iBucketFirst = Hash(ht, KEY_PTR(ht, key), ht->cBuckets); while ( 1 ) /* now try all i > 0 */ { item = Table(Find)(ht->table, iBucketFirst); if ( item == NULL ) /* it's not in the table */ { if ( piEmpty && !fFoundEmpty ) *piEmpty = iBucketFirst; return NULL; } else { if ( IS_BCK_DELETED(item) ) /* always 0 ifdef INSERT_ONLY */ { if ( piEmpty && !fFoundEmpty ) { *piEmpty = iBucketFirst; fFoundEmpty = 1; } } else if ( !KEY_CMP(ht, key, item->key) ) /* must be occupied */ { ht->posLastFind = item; return item; /* we found it! */ } } iBucketFirst = ((iBucketFirst + JUMP(KEY_PTR(ht, key), offset)) & (ht->cBuckets-1)); } } /*************************************************************************\ | Insert() | | If an item with the key already exists in the hashtable, RETURNS | | a pointer to the item (replacing its data if fOverwrite is 1). | | If not, we find the first place-to-insert (which Find() is nice | | enough to set for us) and insert the item there, RETURNing a | | pointer to the item. We might grow the hashtable if it's getting | | full. Note we include buckets holding DELETED when determining | | fullness, because they slow down searching. | \*************************************************************************/ static ulong NextPow2(ulong x) /* returns next power of 2 > x, or 2^31 */ { if ( ((x << 1) >> 1) != x ) /* next power of 2 overflows */ x >>= 1; /* so we return highest power of 2 we can */ while ( (x & (x-1)) != 0 ) /* blacks out all but the top bit */ x &= (x-1); return x << 1; /* makes it the *next* power of 2 */ } static HTItem *Insert(HashTable *ht, ulong key, ulong data, int fOverwrite) { HTItem *item, bckInsert; ulong iEmpty; /* first empty bucket key probes */ if ( ht->table == NULL ) /* empty hash table: find is bound to fail */ return NULL; item = Find(ht, key, &iEmpty); ht->posLastFind = NULL; /* last operation is insert, not find */ if ( item ) { if ( fOverwrite ) item->data = data; /* key already matches */ return item; } COPY_KEY(ht, bckInsert.key, key); /* make our own copy of the key */ bckInsert.data = data; /* oh, and the data too */ item = Table(Insert)(ht->table, &bckInsert, iEmpty, &fOverwrite); if ( fOverwrite ) /* we overwrote a deleted bucket */ ht->cDeletedItems--; ht->cItems++; /* insert couldn't have overwritten */ if ( ht->cDeltaGoalSize > 0 ) /* closer to our goal size */ ht->cDeltaGoalSize--; if ( ht->cItems + ht->cDeletedItems >= ht->cBuckets * OCCUPANCY_PCT || ht->cDeltaGoalSize < 0 ) /* we must've overestimated # of deletes */ item = Rehash(ht, NextPow2((ulong)(((ht->cDeltaGoalSize > 0 ? ht->cDeltaGoalSize : 0) + ht->cItems) / OCCUPANCY_PCT)), item); return item; } /*************************************************************************\ | Delete() | | Removes the item from the hashtable, and if fShrink is 1, will | | shrink the hashtable if it's too small (ie even after halving, | | the ht would be less than half full, though in order to avoid | | oscillating table size, we insist that after halving the ht would | | be less than 40% full). RETURNS 1 if the item was found, 0 else. | | If fLastFindSet is true, then this function is basically | | DeleteLastFind. | \*************************************************************************/ static int Delete(HashTable *ht, ulong key, int fShrink, int fLastFindSet) { if ( !fLastFindSet && !Find(ht, key, NULL) ) return 0; SET_BCK_DELETED(ht, ht->posLastFind); /* find set this, how nice */ ht->cItems--; ht->cDeletedItems++; if ( ht->cDeltaGoalSize < 0 ) /* heading towards our goal of deletion */ ht->cDeltaGoalSize++; if ( fShrink && ht->cItems < ht->cBuckets * OCCUPANCY_PCT*0.4 && ht->cDeltaGoalSize >= 0 /* wait until we're done deleting */ && (ht->cBuckets >> 1) >= MIN_HASH_SIZE ) /* shrink */ Rehash(ht, NextPow2((ulong)((ht->cItems+ht->cDeltaGoalSize)/OCCUPANCY_PCT)), NULL); ht->posLastFind = NULL; /* last operation is delete, not find */ return 1; } /* ======================================================================== */ /* USER-VISIBLE API */ /* ---------------------- */ /*************************************************************************\ | AllocateHashTable() | | ClearHashTable() | | FreeHashTable() | | Allocate() allocates a hash table and sets up size parameters. | | Free() frees it. Clear() deletes all the items from the hash | | table, but frees not. | | cchKey is < 0 if the keys you send me are meant to be pointers | | to \0-terminated strings. Then -cchKey is the maximum key size. | | If cchKey < one word (ulong), the keys you send me are the keys | | themselves; else the keys you send me are pointers to the data. | | If fSaveKeys is 1, we copy any keys given to us to insert. We | | also free these keys when freeing the hash table. If it's 0, the | | user is responsible for key space management. | | AllocateHashTable() RETURNS a hash table; the others TAKE one. | \*************************************************************************/ HashTable *AllocateHashTable(int cchKey, int fSaveKeys) { HashTable *ht; ht = (HashTable *) HTsmalloc(sizeof(*ht)); /* set everything to 0 */ ht->cBuckets = Table(Allocate)(&ht->table, MIN_HASH_SIZE); ht->cchKey = cchKey <= 0 ? NULL_TERMINATED : cchKey; ht->cItems = 0; ht->cDeletedItems = 0; ht->fSaveKeys = fSaveKeys; ht->cDeltaGoalSize = 0; ht->iter = HTsmalloc( sizeof(TableIterator) ); ht->fpData = NULL; /* set by HashLoad, maybe */ ht->bckData.data = (ulong) NULL; /* this must be done */ HTSetupKeyTrunc(); /* in util.c */ return ht; } void ClearHashTable(HashTable *ht) { HTItem *bck; if ( STORES_PTR(ht) && ht->fSaveKeys ) /* need to free keys */ for ( bck = HashFirstBucket(ht); bck; bck = HashNextBucket(ht) ) { FREE_KEY(ht, bck->key); if ( ht->fSaveKeys == 2 ) /* this means key stored in one block */ break; /* ...so only free once */ } Table(Free)(ht->table, ht->cBuckets); ht->cBuckets = Table(Allocate)(&ht->table, MIN_HASH_SIZE); ht->cItems = 0; ht->cDeletedItems = 0; ht->cDeltaGoalSize = 0; ht->posLastFind = NULL; ht->fpData = NULL; /* no longer HashLoading */ if ( ht->bckData.data ) free( (char *)(ht)->bckData.data); ht->bckData.data = (ulong) NULL; } void FreeHashTable(HashTable *ht) { ClearHashTable(ht); if ( ht->iter ) HTfree(ht->iter, sizeof(TableIterator)); if ( ht->table ) Table(Free)(ht->table, ht->cBuckets); free(ht); } /*************************************************************************\ | HashFind() | | HashFindLast() | | HashFind(): looks in h(x) + i(i-1)/2 % t as i goes up from 0 | | until we either find the key or hit an empty bucket. RETURNS a | | pointer to the item in the hit bucket, if we find it, else | | RETURNS NULL. | | HashFindLast() returns the item returned by the last | | HashFind(), which may be NULL if the last HashFind() failed. | | LOAD_AND_RETURN reads the data from off disk, if necessary. | \*************************************************************************/ HTItem *HashFind(HashTable *ht, ulong key) { LOAD_AND_RETURN(ht, Find(ht, KEY_TRUNC(ht, key), NULL)); } HTItem *HashFindLast(HashTable *ht) { LOAD_AND_RETURN(ht, ht->posLastFind); } /*************************************************************************\ | HashFindOrInsert() | | HashFindOrInsertItem() | | HashInsert() | | HashInsertItem() | | HashDelete() | | HashDeleteLast() | | Pretty obvious what these guys do. Some take buckets (items), | | some take keys and data separately. All things RETURN the bucket | | (a pointer into the hashtable) if appropriate. | \*************************************************************************/ HTItem *HashFindOrInsert(HashTable *ht, ulong key, ulong dataInsert) { /* This is equivalent to Insert without samekey-overwrite */ return Insert(ht, KEY_TRUNC(ht, key), dataInsert, 0); } HTItem *HashFindOrInsertItem(HashTable *ht, HTItem *pItem) { return HashFindOrInsert(ht, pItem->key, pItem->data); } HTItem *HashInsert(HashTable *ht, ulong key, ulong data) { return Insert(ht, KEY_TRUNC(ht, key), data, SAMEKEY_OVERWRITE); } HTItem *HashInsertItem(HashTable *ht, HTItem *pItem) { return HashInsert(ht, pItem->key, pItem->data); } int HashDelete(HashTable *ht, ulong key) { return Delete(ht, KEY_TRUNC(ht, key), !FAST_DELETE, 0); } int HashDeleteLast(HashTable *ht) { if ( !ht->posLastFind ) /* last find failed */ return 0; return Delete(ht, 0, !FAST_DELETE, 1); /* no need to specify a key */ } /*************************************************************************\ | HashFirstBucket() | | HashNextBucket() | | Iterates through the items in the hashtable by iterating through | | the table. Since we know about deleted buckets and loading data | | off disk, and the table doesn't, our job is to take care of these | | things. RETURNS a bucket, or NULL after the last bucket. | \*************************************************************************/ HTItem *HashFirstBucket(HashTable *ht) { HTItem *retval; for ( retval = Table(FirstBucket)(ht->iter, ht->table, ht->cBuckets); retval; retval = Table(NextBucket)(ht->iter) ) if ( !IS_BCK_DELETED(retval) ) LOAD_AND_RETURN(ht, retval); return NULL; } HTItem *HashNextBucket(HashTable *ht) { HTItem *retval; while ( (retval=Table(NextBucket)(ht->iter)) ) if ( !IS_BCK_DELETED(retval) ) LOAD_AND_RETURN(ht, retval); return NULL; } /*************************************************************************\ | HashSetDeltaGoalSize() | | If we're going to insert 100 items, set the delta goal size to | | 100 and we take that into account when inserting. Likewise, if | | we're going to delete 10 items, set it to -100 and we won't | | rehash until all 100 have been done. It's ok to be wrong, but | | it's efficient to be right. Returns the delta value. | \*************************************************************************/ int HashSetDeltaGoalSize(HashTable *ht, int delta) { ht->cDeltaGoalSize = delta; #if FAST_DELETE == 1 || defined INSERT_ONLY if ( ht->cDeltaGoalSize < 0 ) /* for fast delete, we never */ ht->cDeltaGoalSize = 0; /* ...rehash after deletion */ #endif return ht->cDeltaGoalSize; } /*************************************************************************\ | HashSave() | | HashLoad() | | HashLoadKeys() | | Routines for saving and loading the hashtable from disk. We can | | then use the hashtable in two ways: loading it back into memory | | (HashLoad()) or loading only the keys into memory, in which case | | the data for a given key is loaded off disk when the key is | | retrieved. The data is freed when something new is retrieved in | | its place, so this is not a "lazy-load" scheme. | | The key is saved automatically and restored upon load, but the | | user needs to specify a routine for reading and writing the data. | | fSaveKeys is of course set to 1 when you read in a hashtable. | | HashLoad RETURNS a newly allocated hashtable. | | DATA_WRITE() takes an fp and a char * (representing the data | | field), and must perform two separate tasks. If fp is NULL, | | return the number of bytes written. If not, writes the data to | | disk at the place the fp points to. | | DATA_READ() takes an fp and the number of bytes in the data | | field, and returns a char * which points to wherever you've | | written the data. Thus, you must allocate memory for the data. | | Both dataRead and dataWrite may be NULL if you just wish to | | store the data field directly, as an integer. | \*************************************************************************/ void HashSave(FILE *fp, HashTable *ht, int (*dataWrite)(FILE *, char *)) { long cchData, posStart; HTItem *bck; /* File format: magic number (4 bytes) : cchKey (one word) : cItems (one word) : cDeletedItems (one word) : table info (buckets and a bitmap) : cchAllKeys (one word) Then the keys, in a block. If cchKey is NULL_TERMINATED, the keys are null-terminated too, otherwise this takes up cchKey*cItems bytes. Note that keys are not written for DELETED buckets. Then the data: : EITHER DELETED (one word) to indicate it's a deleted bucket, : OR number of bytes for this (non-empty) bucket's data (one word). This is not stored if dataWrite == NULL since the size is known to be sizeof(ul). Plus: : the data for this bucket (variable length) All words are in network byte order. */ fprintf(fp, "%s", MAGIC_KEY); WRITE_UL(fp, ht->cchKey); /* WRITE_UL, READ_UL, etc in fks-hash.h */ WRITE_UL(fp, ht->cItems); WRITE_UL(fp, ht->cDeletedItems); Table(Write)(fp, ht->table, ht->cBuckets); /* writes cBuckets too */ WRITE_UL(fp, 0); /* to be replaced with sizeof(key block) */ posStart = ftell(fp); for ( bck = HashFirstBucket(ht); bck; bck = HashNextBucket(ht) ) fwrite(KEY_PTR(ht, bck->key), 1, (ht->cchKey == NULL_TERMINATED ? strlen(KEY_PTR(ht, bck->key))+1 : ht->cchKey), fp); cchData = ftell(fp) - posStart; fseek(fp, posStart - sizeof(unsigned long), SEEK_SET); WRITE_UL(fp, cchData); fseek(fp, 0, SEEK_END); /* done with our sojourn at the header */ /* Unlike HashFirstBucket, TableFirstBucket iters through deleted bcks */ for ( bck = Table(FirstBucket)(ht->iter, ht->table, ht->cBuckets); bck; bck = Table(NextBucket)(ht->iter) ) if ( dataWrite == NULL || IS_BCK_DELETED(bck) ) WRITE_UL(fp, bck->data); else /* write cchData followed by the data */ { WRITE_UL(fp, (*dataWrite)(NULL, (char *)bck->data)); (*dataWrite)(fp, (char *)bck->data); } } static HashTable *HashDoLoad(FILE *fp, char * (*dataRead)(FILE *, int), HashTable *ht) { ulong cchKey; char szMagicKey[4], *rgchKeys; HTItem *bck; fread(szMagicKey, 1, 4, fp); if ( strncmp(szMagicKey, MAGIC_KEY, 4) ) { fprintf(stderr, "ERROR: not a hash table (magic key is %4.4s, not %s)\n", szMagicKey, MAGIC_KEY); exit(3); } Table(Free)(ht->table, ht->cBuckets); /* allocated in AllocateHashTable */ READ_UL(fp, ht->cchKey); READ_UL(fp, ht->cItems); READ_UL(fp, ht->cDeletedItems); ht->cBuckets = Table(Read)(fp, &ht->table); /* next is the table info */ READ_UL(fp, cchKey); rgchKeys = (char *) HTsmalloc( cchKey ); /* stores all the keys */ fread(rgchKeys, 1, cchKey, fp); /* We use the table iterator so we don't try to LOAD_AND_RETURN */ for ( bck = Table(FirstBucket)(ht->iter, ht->table, ht->cBuckets); bck; bck = Table(NextBucket)(ht->iter) ) { READ_UL(fp, bck->data); /* all we need if dataRead is NULL */ if ( IS_BCK_DELETED(bck) ) /* always 0 if defined(INSERT_ONLY) */ continue; /* this is why we read the data first */ if ( dataRead != NULL ) /* if it's null, we're done */ if ( !ht->fpData ) /* load data into memory */ bck->data = (ulong)dataRead(fp, bck->data); else /* store location of data on disk */ { fseek(fp, bck->data, SEEK_CUR); /* bck->data held size of data */ bck->data = ftell(fp) - bck->data - sizeof(unsigned long); } if ( ht->cchKey == NULL_TERMINATED ) /* now read the key */ { bck->key = (ulong) rgchKeys; rgchKeys = strchr(rgchKeys, '\0') + 1; /* read past the string */ } else { if ( STORES_PTR(ht) ) /* small keys stored directly */ bck->key = (ulong) rgchKeys; else memcpy(&bck->key, rgchKeys, ht->cchKey); rgchKeys += ht->cchKey; } } if ( !STORES_PTR(ht) ) /* keys are stored directly */ HTfree(rgchKeys - cchKey, cchKey); /* we've advanced rgchK to end */ return ht; } HashTable *HashLoad(FILE *fp, char * (*dataRead)(FILE *, int)) { HashTable *ht; ht = AllocateHashTable(0, 2); /* cchKey set later, fSaveKey should be 2! */ return HashDoLoad(fp, dataRead, ht); } HashTable *HashLoadKeys(FILE *fp, char * (*dataRead)(FILE *, int)) { HashTable *ht; if ( dataRead == NULL ) return HashLoad(fp, NULL); /* no reason not to load the data here */ ht = AllocateHashTable(0, 2); /* cchKey set later, fSaveKey should be 2! */ ht->fpData = fp; /* tells HashDoLoad() to only load keys */ ht->dataRead = dataRead; return HashDoLoad(fp, dataRead, ht); } /*************************************************************************\ | PrintHashTable() | | A debugging tool. Prints the entire contents of the hash table, | | like so: <bin #>: key of the contents. Returns number of bytes | | allocated. If time is not -1, we print it as the time required | | for the hash. If iForm is 0, we just print the stats. If it's | | 1, we print the keys and data too, but the keys are printed as | | ulongs. If it's 2, we print the keys correctly (as long numbers | | or as strings). | \*************************************************************************/ ulong PrintHashTable(HashTable *ht, double time, int iForm) { ulong cbData = 0, cbBin = 0, cItems = 0, cOccupied = 0; HTItem *item; printf("HASH TABLE.\n"); if ( time > -1.0 ) { printf("----------\n"); printf("Time: %27.2f\n", time); } for ( item = Table(FirstBucket)(ht->iter, ht->table, ht->cBuckets); item; item = Table(NextBucket)(ht->iter) ) { cOccupied++; /* this includes deleted buckets */ if ( IS_BCK_DELETED(item) ) /* we don't need you for anything else */ continue; cItems++; /* this is for a sanity check */ if ( STORES_PTR(ht) ) cbData += ht->cchKey == NULL_TERMINATED ? WORD_ROUND(strlen((char *)item->key)+1) : ht->cchKey; else cbBin -= sizeof(item->key), cbData += sizeof(item->key); cbBin -= sizeof(item->data), cbData += sizeof(item->data); if ( iForm != 0 ) /* we want the actual contents */ { if ( iForm == 2 && ht->cchKey == NULL_TERMINATED ) printf("%s/%lu\n", (char *)item->key, item->data); else if ( iForm == 2 && STORES_PTR(ht) ) printf("%.*s/%lu\n", (int)ht->cchKey, (char *)item->key, item->data); else /* either key actually is a ulong, or iForm == 1 */ printf("%lu/%lu\n", item->key, item->data); } } assert( cItems == ht->cItems ); /* sanity check */ cbBin = Table(Memory)(ht->cBuckets, cOccupied); printf("----------\n"); printf("%lu buckets (%lu bytes). %lu empty. %lu hold deleted items.\n" "%lu items (%lu bytes).\n" "%lu bytes total. %lu bytes (%2.1f%%) of this is ht overhead.\n", ht->cBuckets, cbBin, ht->cBuckets - cOccupied, cOccupied - ht->cItems, ht->cItems, cbData, cbData + cbBin, cbBin, cbBin*100.0/(cbBin+cbData)); return cbData + cbBin; }
42.94282
80
0.51647
[ "object" ]
2ec581bc04cf0afe3ec1240f3c2e2ae182dbe862
4,700
h
C
whipstitch/wsGraphics/wsRenderSystem.h
dsnettleton/whipstitch-game-engine
1c91a2e90274f18723141ec57d0cb4930bd29b25
[ "MIT" ]
null
null
null
whipstitch/wsGraphics/wsRenderSystem.h
dsnettleton/whipstitch-game-engine
1c91a2e90274f18723141ec57d0cb4930bd29b25
[ "MIT" ]
null
null
null
whipstitch/wsGraphics/wsRenderSystem.h
dsnettleton/whipstitch-game-engine
1c91a2e90274f18723141ec57d0cb4930bd29b25
[ "MIT" ]
null
null
null
/* * wsRenderSystem.h * * Created on: Sep 10, 2012 * Author: dsnettleton * * This file declares the class wsRenderSystem, which loads the OpenGL context using * GLEW (GL Extension Wrangler) to initialize all available extensions on the given * platform. * * wsRenderSystem is an engine subsytem, and must be initialized via the startUp() * function before it may be used. This is done through the engine startup command * wsInit(). * * This software is provided under the terms of the MIT license * Copyright (c) D. Scott Nettleton, 2013 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef WS_RENDER_SYSTEM_H_ #define WS_RENDER_SYSTEM_H_ #include "../wsConfig.h" #include "wsShader.h" #include "../wsUtils.h" #include "../wsAssets.h" #include "../wsPrimitives.h" #include "../wsGameFlow/wsScene.h" #ifndef WS_GLEW_INCLUDED_ #include "GL/glew.h" #define WS_GLEW_INCLUDED_ #endif struct wsMeshContainer { const wsMesh* mesh; #if WS_GRAPHICS_BACKEND == WS_BACKEND_OPENGL wsIndexArray* indexArrays; u32 numIndexArrays; u32 vertexArray; #endif wsMeshContainer(const wsMesh* my); ~wsMeshContainer(); }; class wsRenderSystem { private: i32 versionMajor; i32 versionMinor; i32 numExtensions; u32 drawFeatures; // Shader Variables wsShader** shaders; u32* shaderBuffers; u32* frameBufferObjects; u32* frameBufferTextures; wsCamera* hudCam; u32 renderMode, finalFramebuffer; i32 shaderWidth, shaderHeight; // Drawing components wsHashMap<u32>* imageIndices; wsHashMap<wsMeshContainer*>* meshes; wsOrderedHashMap<wsPanel*>* panels; u32 currentPostBuffer; u32 currentFBO; // True only when the startUp function has been called bool _mInitialized; // Private Methods void initializeShaders(u32 width, u32 height); public: /* Default Constructor and Deconstructor */ // As an engine subsystem, the renderer takes no action until explicitly // initialized via the startUp(...) function. // uninitialized via the shutDown() function. wsRenderSystem() : _mInitialized(false) {} ~wsRenderSystem() {} /* Setters and Getters */ bool isEnabled(u32 features) { return ((drawFeatures & features) == features); } u32 getRenderMode() { return renderMode; } void setRenderMode(const u32 my) { renderMode = my; } /* Operational Methods */ u32 addMesh(const char* filepath); // Adds a mesh and return the mesh's index u32 addPanel(const char* panelName, wsPanel* myPanel); void checkExtensions(); void clearScreen(); void disable(u32 renderingFeatures); void drawModels(wsHashMap<wsModel*>* models); void drawPanels(); void drawPost(); // Post-processing effects void drawScene(wsScene* myScene); void enable(u32 renderingFeatures); void loadIdentity(); void loadTexture(u32* index, const char* filename, bool autoSmooth = true, bool tiling = false); void modelviewMatrix(); void nextRenderMode(); void projectionMatrix(); void resize(const u32 newWidth, const u32 newHeight); void scanHUD(); // Use mouse position from wsInputs to test ui panels for events, etc. void setClearColor(const vec4& clearColor); void setClearColor(f32 r, f32 g, f32 b, f32 a); void setMaterial(const wsMaterial& mat); void setPrimMaterial(const wsPrimMaterial& mat); void swapBuffers(); void swapPostBuffer(); // Uninitializes the renderer void shutDown(); // Initializes the renderer void startUp(); }; extern wsRenderSystem wsRenderer; #endif /* WS_RENDER_SYSTEM_H_ */
35.338346
100
0.714468
[ "mesh" ]
2eca0f2a06b30510d165598520c1e564da631343
4,771
h
C
py/cxx/py_operators_p.h
Tomographer/tomographer
0a64927e639454175803c1746141bd9288af8b29
[ "MIT" ]
12
2015-09-24T02:25:11.000Z
2020-02-13T02:26:00.000Z
py/cxx/py_operators_p.h
Tomographer/tomographer
0a64927e639454175803c1746141bd9288af8b29
[ "MIT" ]
4
2015-10-12T15:48:55.000Z
2021-07-21T15:14:59.000Z
py/cxx/py_operators_p.h
Tomographer/tomographer
0a64927e639454175803c1746141bd9288af8b29
[ "MIT" ]
2
2015-10-12T15:32:29.000Z
2018-05-08T11:39:49.000Z
/* This file is part of the Tomographer project, which is distributed under the * terms of the MIT license. * * The MIT License (MIT) * * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef TOMOPY_PY_OPERATORS_P_H #define TOMOPY_PY_OPERATORS_P_H // // These overloads should probably feature in PyBind11 in some way, not sure if this is // provided by PyBind11 in some other way I haven't noticed... // class pyop { py::object o; public: pyop(py::object o_) : o(std::move(o_)) { } py::object object() const { return o; } }; // See https://docs.python.org/2/c-api/object.html#c.PyObject_RichCompare #define PY_OP_P_DEF_RICHCOMPARE_OPERATOR(CXXOP, PYOP) \ inline bool CXXOP(const pyop & a, const pyop & b) \ { \ PyObject *result_obj = \ PyObject_RichCompare(a.object().ptr(), b.object().ptr(), PYOP); \ if (result_obj == NULL) { \ throw py::error_already_set(); \ } \ return py::reinterpret_steal<py::bool_>(result_obj).cast<bool>(); \ } \ inline bool CXXOP(const pyop & a, const py::object & b) \ { return CXXOP( a, pyop(b) ) ; } \ inline bool CXXOP(const py::object & a, const pyop & b) \ { return CXXOP( pyop(a), b ) ; } PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator<, Py_LT) PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator<=, Py_LE) PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator==, Py_EQ) PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator!=, Py_NE) PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator>, Py_GT) PY_OP_P_DEF_RICHCOMPARE_OPERATOR(operator>=, Py_GE) #define PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(CXXOP, PYOPNAME) \ inline pyop CXXOP(const pyop & a, const pyop & b) \ { \ PyObject * result_obj = PyNumber_ ## PYOPNAME (a.object().ptr(), b.object().ptr()); \ if (result_obj == NULL) { \ throw py::error_already_set(); \ } \ return py::reinterpret_steal<py::object>(result_obj); \ } \ inline pyop CXXOP(const pyop & a, const py::object & b) \ { return CXXOP(a, pyop(b)); } \ inline pyop CXXOP(const py::object & a, const pyop & b) \ { return CXXOP(pyop(a), b); } PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator+, Add) PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator-, Subtract) PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator*, Multiply) PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator/, TrueDivide) // Note: true division like in Python 3 PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator%, Remainder) PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator<<, Lshift) // bitwise left shift PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator>>, Rshift) // bitwise right shift PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator&, And) // bitwise AND PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator|, Or) // bitwise OR PY_OP_P_DEF_BINARY_NUMBER_OPERATOR(operator^, Xor) // bitwise XOR #endif
45.875
97
0.607001
[ "object" ]
2edc6fc1d0119e9a13f15d193c6e77e8e49245da
5,228
h
C
src/SDLWrapper.h
CzechBlueBear/MidnightJewels
1bb8ddf17dbbbdf1bdc4c769be3e12c500fbe15f
[ "MIT" ]
null
null
null
src/SDLWrapper.h
CzechBlueBear/MidnightJewels
1bb8ddf17dbbbdf1bdc4c769be3e12c500fbe15f
[ "MIT" ]
null
null
null
src/SDLWrapper.h
CzechBlueBear/MidnightJewels
1bb8ddf17dbbbdf1bdc4c769be3e12c500fbe15f
[ "MIT" ]
null
null
null
#pragma once // C++ wrapper for SDL. // This is really just for fun and to make things look more object-y, // but there is no deeper reason at all. #include "SDL.h" #include <cstdint> #include <stdexcept> #include <optional> #include <functional> namespace SDL { /// Wraps SDL errors that are not reasonable to return in-band (panic-grade). class Error : public std::runtime_error { public: Error(const std::string &reason_) : std::runtime_error(reason_) {} }; //--- class OkAble { public: virtual bool Ok() const = 0; }; //--- /// Wraps SDL initialization; SDL_Init() is called on construction, /// and SDL_Quit() upon destruction. class Library { public: /// Calls SDL_Init(). Throws SDL::Error if this fails. Library(uint32_t initFlags = SDL_INIT_EVERYTHING); Library(const Library& src) = delete; ~Library(); static std::string getError() { return std::string(SDL_GetError()); } }; //--- class EventLoop { public: EventLoop(Library &libSDL_); ~EventLoop(); void Run(); /// Pushes a user event (with user-defined meaning) to the event stream. void PushUserEvent(int code, void* data1 = nullptr, void* data2 = nullptr); /// Flag to set to true to leave Run(). bool quitRequested = false; std::function<void(void)> OnRedraw; std::function<void(const SDL_KeyboardEvent&)> OnKey; std::function<void(const SDL_MouseMotionEvent&)> OnMouseMotion; std::function<void(const SDL_MouseButtonEvent&)> OnMouseButton; std::function<void(const SDL_UserEvent&)> OnUserEvent; std::function<void(int, int)> OnWindowResized; protected: Library &libSDL; }; //--- class Rect : public SDL_Rect { public: /** * Constructor, initializes everything to 0. */ Rect() { x = 0; y = 0; w = 0; h = 0; } /** * Constructor, sets explicitly both position (X, Y) and width and height (W, H). */ Rect(int x_, int y_, int w_, int h_) { x = x_; y = y_; w = w_; h = h_; } /** * Sets the rectangle position (X, Y) and its width and height (W, H). */ Rect &SetXYWH(int x_, int y_, int w_, int h_) { x = x_; y = y_; w = w_; h = h_; return *this; } operator SDL_Rect*() { return this; } operator SDL_Rect const*() const { return this; } }; //--- /// Base class for objects that wrap another object using its pointer. template<class T> class PtrWrapper : public virtual OkAble { public: /// Returns a pointer to the wrapped object (null if the wrapper is invalid). T* GetWrapped() { return wrapped; } /// Const-variant of GetWrapped(). const T* GetWrapped() const { return wrapped; } /// For automatical unwrapping when passing to a function that expects the pointer to the underlying object. operator T*() { return wrapped; } /// Const-variant of operator T*(). operator const T*() { return wrapped; } /// Basic implementation of Ok(), checks whether the wrapped object exists. bool Ok() const { return (wrapped != nullptr); } protected: /// Pointer to the wrapped object (plain pointer as it usually needs special allocation/freeing calls anyway). T* wrapped = nullptr; }; //--- class Surface : public PtrWrapper<SDL_Surface> { public: /// Constructor, equivalent to SDL_CreateRGBSurfaceWithFormat(). Surface(int width, int height, int depth, uint32_t format); Surface(const Surface& surface) = delete; /// Destructor, calls Discard(). ~Surface(); /// Frees the wrapped object (with SDL_FreeSurface()), leaving the wrapper invalid. void Discard(); SDL_PixelFormat* GetFormat() const { return wrapped ? wrapped->format : nullptr; } void* GetPixels() { return wrapped ? wrapped->pixels : 0; } int GetWidth() const { return wrapped ? wrapped->w : 0; } int GetHeight() const { return wrapped ? wrapped->h : 0; } int GetPitch() const { return wrapped ? wrapped->pitch : 0; } /// Blits a rectangle of pixels from this surface to the target surface. void blit(const SDL::Rect& srcRect, SDL::Surface& dest, SDL::Rect& destRect) const; }; //--- class Texture : public PtrWrapper<SDL_Texture> { public: Texture(SDL_Renderer* renderer, Surface& src); ~Texture(); }; //--- class Renderer : public PtrWrapper<SDL_Renderer> { public: Renderer(SDL_Window* window, int index, uint32_t flags); ~Renderer(); }; //--- /// Wraps SDL_Timer, allows to use a C++ lambda as the payload function. class Timer { public: enum class Type { kOneShot = 0, ///< Triggered only once. kRepeated = 1 ///< Triggered repeatedly in specified intervals. }; Timer(Timer::Type type, uint32_t interval, std::function<void(void)> payload); Timer(const Timer &src) = delete; ~Timer(); protected: /// ID of the SDL timer. SDL_TimerID timerId = 0; /// SDL callback that ensures calling our payload function. static uint32_t CallPayload(uint32_t interval, void* indirectThis); /// The interval set in the constructor. uint32_t interval = 0; Timer::Type type; /// The payload, called when the timer elapses (probably in a different thread). std::function<void(void)> payload; }; //--- class Window { public: Window(const std::string& title, int width, int height); Window(const Window&) = delete; ~Window(); uint32_t getID() { return SDL_GetWindowID(wnd); } private: SDL_Window* wnd = nullptr; SDL_GLContext ctx = nullptr; }; } // namespace SDL
22.34188
111
0.689174
[ "object" ]
2ee8aa5183c7b5a2e548ef0147a65a99ed50d18f
1,225
h
C
editor/src/Panels/PanelGroup.h
KyaZero/Wraith
6e084f46c3c6ca1bcbedb7950d33d10b546e6454
[ "MIT" ]
1
2021-06-27T14:46:46.000Z
2021-06-27T14:46:46.000Z
editor/src/Panels/PanelGroup.h
KyaZero/Wraith
6e084f46c3c6ca1bcbedb7950d33d10b546e6454
[ "MIT" ]
19
2021-10-29T19:20:40.000Z
2021-12-20T01:18:34.000Z
editor/src/Panels/PanelGroup.h
KyaZero/Wraith
6e084f46c3c6ca1bcbedb7950d33d10b546e6454
[ "MIT" ]
1
2021-06-27T15:09:52.000Z
2021-06-27T15:09:52.000Z
#pragma once #include "Panel.h" namespace Wraith { class PanelGroup { public: PanelGroup(std::string_view name) : m_Name(name) { } virtual ~PanelGroup() = default; void RenderWindows(); void RenderMenus(); template <class T = PanelGroup, class... Args> std::enable_if_t<std::is_base_of_v<PanelGroup, T>, T*> CreateGroup(Args&&... args) { m_PanelGroups.push_back(std::move(std::make_unique<T>(std::forward<Args>(args)...))); return reinterpret_cast<T*>(m_PanelGroups.back().get()); } template <class T, class... Args> std::enable_if_t<std::is_base_of_v<Panel, T>, T*> CreatePanel(Args&&... args) { m_Panels.push_back(std::move(std::make_unique<T>(std::forward<Args>(args)...))); return reinterpret_cast<T*>(m_Panels.back().get()); } const auto& GetPanels() const { return m_Panels; } const auto& GetGroups() const { return m_PanelGroups; } private: std::string m_Name; std::vector<std::unique_ptr<Panel>> m_Panels; std::vector<std::unique_ptr<PanelGroup>> m_PanelGroups; }; } // namespace Wraith
31.410256
97
0.587755
[ "vector" ]
2eed1567b228b03558887efcde246826b0515e33
25,514
h
C
Rendering/Annotation/vtkAxisActor.h
laurennlam/VTK
4958cf971ee13aadd2acf88339a887f4012594be
[ "BSD-3-Clause" ]
null
null
null
Rendering/Annotation/vtkAxisActor.h
laurennlam/VTK
4958cf971ee13aadd2acf88339a887f4012594be
[ "BSD-3-Clause" ]
null
null
null
Rendering/Annotation/vtkAxisActor.h
laurennlam/VTK
4958cf971ee13aadd2acf88339a887f4012594be
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkAxisActor.h Language: C++ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkAxisActor * @brief Create an axis with tick marks and labels * * vtkAxisActor creates an axis with tick marks, labels, and/or a title, * depending on the particular instance variable settings. It is assumed that * the axes is part of a bounding box and is orthoganal to one of the * coordinate axes. To use this class, you typically specify two points * defining the start and end points of the line (xyz definition using * vtkCoordinate class), the axis type (X, Y or Z), the axis location in * relation to the bounding box, the bounding box, the number of labels, and * the data range (min,max). You can also control what parts of the axis are * visible including the line, the tick marks, the labels, and the title. It * is also possible to control gridlines, and specifiy on which 'side' the * tickmarks are drawn (again with respect to the underlying assumed * bounding box). You can also specify the label format (a printf style format). * * This class decides how to locate the labels, and how to create reasonable * tick marks and labels. * * Labels follow the camera so as to be legible from any viewpoint. * * The instance variables Point1 and Point2 are instances of vtkCoordinate. * All calculations and references are in World Coordinates. * * @par Thanks: * This class was written by: * Hank Childs, Kathleen Bonnell, Amy Squillacote, Brad Whitlock, * Eric Brugger, Claire Guilbaud, Nicolas Dolegieviez, Will Schroeder, * Karthik Krishnan, Aashish Chaudhary, Philippe Pebay, David Gobbi, * David Partyka, Utkarsh Ayachit David Cole, Francois Bertel, and Mark Olesen * Part of this work was supported by CEA/DIF - Commissariat a l'Energie Atomique, * Centre DAM Ile-De-France, BP12, F-91297 Arpajon, France. * * @sa * vtkActor vtkVectorText vtkPolyDataMapper vtkAxisActor2D vtkCoordinate */ #ifndef vtkAxisActor_h #define vtkAxisActor_h #include "vtkActor.h" #include "vtkRenderingAnnotationModule.h" // For export macro class vtkAxisFollower; class vtkCamera; class vtkCoordinate; class vtkFollower; class vtkPoints; class vtkPolyData; class vtkPolyDataMapper; class vtkProp3DAxisFollower; class vtkProperty2D; class vtkStringArray; class vtkTextActor; class vtkTextActor3D; class vtkTextProperty; class vtkVectorText; class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor { public: vtkTypeMacro(vtkAxisActor, vtkActor); void PrintSelf(ostream& os, vtkIndent indent); /** * Instantiate object. */ static vtkAxisActor* New(); //@{ /** * Specify the position of the first point defining the axis. */ virtual vtkCoordinate* GetPoint1Coordinate(); virtual void SetPoint1(double x[3]) { this->SetPoint1(x[0], x[1], x[2]); } virtual void SetPoint1(double x, double y, double z); virtual double* GetPoint1(); //@} //@{ /** * Specify the position of the second point defining the axis. */ virtual vtkCoordinate* GetPoint2Coordinate(); virtual void SetPoint2(double x[3]) { this->SetPoint2(x[0], x[1], x[2]); } virtual void SetPoint2(double x, double y, double z); virtual double* GetPoint2(); //@} //@{ /** * Specify the (min,max) axis range. This will be used in the generation * of labels, if labels are visible. */ vtkSetVector2Macro(Range, double); vtkGetVectorMacro(Range, double, 2); //@} //@{ /** * Set or get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). */ void SetBounds(const double bounds[6]); void SetBounds(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax); double* GetBounds(void); void GetBounds(double bounds[6]); //@} //@{ /** * Set/Get the format with which to print the labels on the axis. */ vtkSetStringMacro(LabelFormat); vtkGetStringMacro(LabelFormat); //@} //@{ /** * Render text as polygons (vtkVectorText) or as sprites (vtkTextActor3D). * In 2D mode, the value is ignored and text is rendered as vtkTextActor. * False(0) by default. * See Also: * GetUse2DMode(), SetUse2DMode */ vtkSetMacro(UseTextActor3D, int); vtkGetMacro(UseTextActor3D, int); //@} //@{ /** * Set/Get the flag that controls whether the minor ticks are visible. */ vtkSetMacro(MinorTicksVisible, int); vtkGetMacro(MinorTicksVisible, int); vtkBooleanMacro(MinorTicksVisible, int); //@} //@{ /** * Set/Get the title of the axis actor, */ void SetTitle(const char* t); vtkGetStringMacro(Title); //@} //@{ /** * Set/Get the common exponent of the labels values */ void SetExponent(const char* t); vtkGetStringMacro(Exponent); //@} //@{ /** * Set/Get the size of the major tick marks */ vtkSetMacro(MajorTickSize, double); vtkGetMacro(MajorTickSize, double); //@} //@{ /** * Set/Get the size of the major tick marks */ vtkSetMacro(MinorTickSize, double); vtkGetMacro(MinorTickSize, double); //@} enum TickLocation { VTK_TICKS_INSIDE = 0, VTK_TICKS_OUTSIDE = 1, VTK_TICKS_BOTH = 2 }; //@{ /** * Set/Get the location of the ticks. * Inside: tick end toward positive direction of perpendicular axes. * Outside: tick end toward negative direction of perpendicular axes. */ vtkSetClampMacro(TickLocation, int, VTK_TICKS_INSIDE, VTK_TICKS_BOTH); vtkGetMacro(TickLocation, int); //@} void SetTickLocationToInside(void) { this->SetTickLocation(VTK_TICKS_INSIDE); }; void SetTickLocationToOutside(void) { this->SetTickLocation(VTK_TICKS_OUTSIDE); }; void SetTickLocationToBoth(void) { this->SetTickLocation(VTK_TICKS_BOTH); }; //@{ /** * Set/Get visibility of the axis line. */ vtkSetMacro(AxisVisibility, int); vtkGetMacro(AxisVisibility, int); vtkBooleanMacro(AxisVisibility, int); //@} //@{ /** * Set/Get visibility of the axis major tick marks. */ vtkSetMacro(TickVisibility, int); vtkGetMacro(TickVisibility, int); vtkBooleanMacro(TickVisibility, int); //@} //@{ /** * Set/Get visibility of the axis labels. */ vtkSetMacro(LabelVisibility, int); vtkGetMacro(LabelVisibility, int); vtkBooleanMacro(LabelVisibility, int); //@} //@{ /** * Set/Get visibility of the axis title. */ vtkSetMacro(TitleVisibility, int); vtkGetMacro(TitleVisibility, int); vtkBooleanMacro(TitleVisibility, int); //@} //@{ /** * Set/Get visibility of the axis detached exponent. */ vtkSetMacro(ExponentVisibility, bool); vtkGetMacro(ExponentVisibility, bool); vtkBooleanMacro(ExponentVisibility, bool); //@} //@{ /** * Set/Get visibility of the axis detached exponent. */ vtkSetMacro(LastMajorTickPointCorrection, bool); vtkGetMacro(LastMajorTickPointCorrection, bool); vtkBooleanMacro(LastMajorTickPointCorrection, bool); //@} enum AlignLocation { VTK_ALIGN_TOP = 0, VTK_ALIGN_BOTTOM = 1, VTK_ALIGN_POINT1 = 2, VTK_ALIGN_POINT2 = 3 }; //@{ /** * Get/Set the alignement of the title related to the axis. * Possible Alignment: VTK_ALIGN_TOP, VTK_ALIGN_BOTTOM, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2 */ virtual void SetTitleAlignLocation(int location); vtkGetMacro(TitleAlignLocation, int); //@} //@{ /** * Get/Set the location of the Detached Exponent related to the axis. * Possible Location: VTK_ALIGN_TOP, VTK_ALIGN_BOTTOM, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2 */ virtual void SetExponentLocation(int location); vtkGetMacro(ExponentLocation, int); //@} //@{ /** * Set/Get the axis title text property. */ virtual void SetTitleTextProperty(vtkTextProperty* p); vtkGetObjectMacro(TitleTextProperty, vtkTextProperty); //@} //@{ /** * Set/Get the axis labels text property. */ virtual void SetLabelTextProperty(vtkTextProperty* p); vtkGetObjectMacro(LabelTextProperty, vtkTextProperty); //@} //@{ /** * Get/Set axis actor property (axis and its ticks) (kept for compatibility) */ void SetAxisLinesProperty(vtkProperty*); vtkProperty* GetAxisLinesProperty(); //@} //@{ /** * Get/Set main line axis actor property */ void SetAxisMainLineProperty(vtkProperty*); vtkProperty* GetAxisMainLineProperty(); //@} //@{ /** * Get/Set axis actor property (axis and its ticks) */ void SetAxisMajorTicksProperty(vtkProperty*); vtkProperty* GetAxisMajorTicksProperty(); //@} //@{ /** * Get/Set axis actor property (axis and its ticks) */ void SetAxisMinorTicksProperty(vtkProperty*); vtkProperty* GetAxisMinorTicksProperty(); //@} //@{ /** * Get/Set gridlines actor property (outer grid lines) */ void SetGridlinesProperty(vtkProperty*); vtkProperty* GetGridlinesProperty(); //@} //@{ /** * Get/Set inner gridlines actor property */ void SetInnerGridlinesProperty(vtkProperty*); vtkProperty* GetInnerGridlinesProperty(); //@} //@{ /** * Get/Set gridPolys actor property (grid quads) */ void SetGridpolysProperty(vtkProperty*); vtkProperty* GetGridpolysProperty(); //@} //@{ /** * Set/Get whether gridlines should be drawn. */ vtkSetMacro(DrawGridlines, int); vtkGetMacro(DrawGridlines, int); vtkBooleanMacro(DrawGridlines, int); //@} //@{ /** * Set/Get whether ONLY the gridlines should be drawn. * This will only draw GridLines and will skip any other part of the rendering * such as Axis/Tick/Title/... */ vtkSetMacro(DrawGridlinesOnly, int); vtkGetMacro(DrawGridlinesOnly, int); vtkBooleanMacro(DrawGridlinesOnly, int); //@} vtkSetMacro(DrawGridlinesLocation, int); vtkGetMacro(DrawGridlinesLocation, int); //@{ /** * Set/Get whether inner gridlines should be drawn. */ vtkSetMacro(DrawInnerGridlines, int); vtkGetMacro(DrawInnerGridlines, int); vtkBooleanMacro(DrawInnerGridlines, int); //@} //@{ /** * Set/Get the length to use when drawing gridlines. */ vtkSetMacro(GridlineXLength, double); vtkGetMacro(GridlineXLength, double); vtkSetMacro(GridlineYLength, double); vtkGetMacro(GridlineYLength, double); vtkSetMacro(GridlineZLength, double); vtkGetMacro(GridlineZLength, double); //@} //@{ /** * Set/Get whether gridpolys should be drawn. */ vtkSetMacro(DrawGridpolys, int); vtkGetMacro(DrawGridpolys, int); vtkBooleanMacro(DrawGridpolys, int); //@} enum AxisType { VTK_AXIS_TYPE_X = 0, VTK_AXIS_TYPE_Y = 1, VTK_AXIS_TYPE_Z = 2 }; //@{ /** * Set/Get the type of this axis. */ vtkSetClampMacro(AxisType, int, VTK_AXIS_TYPE_X, VTK_AXIS_TYPE_Z); vtkGetMacro(AxisType, int); void SetAxisTypeToX(void) { this->SetAxisType(VTK_AXIS_TYPE_X); }; void SetAxisTypeToY(void) { this->SetAxisType(VTK_AXIS_TYPE_Y); }; void SetAxisTypeToZ(void) { this->SetAxisType(VTK_AXIS_TYPE_Z); }; //@} enum AxisPosition { VTK_AXIS_POS_MINMIN = 0, VTK_AXIS_POS_MINMAX = 1, VTK_AXIS_POS_MAXMAX = 2, VTK_AXIS_POS_MAXMIN = 3 }; //@{ /** * Set/Get The type of scale, enable logarithmic scale or linear by default */ vtkSetMacro(Log, bool); vtkGetMacro(Log, bool); vtkBooleanMacro(Log, bool); //@} //@{ /** * Set/Get the position of this axis (in relation to an an * assumed bounding box). For an x-type axis, MINMIN corresponds * to the x-edge in the bounding box where Y values are minimum and * Z values are minimum. For a y-type axis, MAXMIN corresponds to the * y-edge where X values are maximum and Z values are minimum. */ vtkSetClampMacro(AxisPosition, int, VTK_AXIS_POS_MINMIN, VTK_AXIS_POS_MAXMIN); vtkGetMacro(AxisPosition, int); //@} void SetAxisPositionToMinMin(void) { this->SetAxisPosition(VTK_AXIS_POS_MINMIN); }; void SetAxisPositionToMinMax(void) { this->SetAxisPosition(VTK_AXIS_POS_MINMAX); }; void SetAxisPositionToMaxMax(void) { this->SetAxisPosition(VTK_AXIS_POS_MAXMAX); }; void SetAxisPositionToMaxMin(void) { this->SetAxisPosition(VTK_AXIS_POS_MAXMIN); }; //@{ /** * Set/Get the camera for this axis. The camera is used by the * labels to 'follow' the camera and be legible from any viewpoint. */ virtual void SetCamera(vtkCamera*); vtkGetObjectMacro(Camera, vtkCamera); //@} //@{ /** * Draw the axis. */ virtual int RenderOpaqueGeometry(vtkViewport* viewport); virtual int RenderTranslucentGeometry(vtkViewport* viewport); virtual int RenderTranslucentPolygonalGeometry(vtkViewport* viewport); virtual int RenderOverlay(vtkViewport* viewport); int HasTranslucentPolygonalGeometry(); //@} /** * Release any graphics resources that are being consumed by this actor. * The parameter window could be used to determine which graphic * resources to release. */ void ReleaseGraphicsResources(vtkWindow*); double ComputeMaxLabelLength(const double[3]); double ComputeTitleLength(const double[3]); void SetLabelScale(const double scale); void SetLabelScale(int labelIndex, const double scale); void SetTitleScale(const double scale); //@{ /** * Set/Get the starting position for minor and major tick points, * and the delta values that determine their spacing. */ vtkSetMacro(MinorStart, double); vtkGetMacro(MinorStart, double); double GetMajorStart(int axis); void SetMajorStart(int axis, double value); // vtkSetMacro(MajorStart, double); // vtkGetMacro(MajorStart, double); vtkSetMacro(DeltaMinor, double); vtkGetMacro(DeltaMinor, double); double GetDeltaMajor(int axis); void SetDeltaMajor(int axis, double value); // vtkSetMacro(DeltaMajor, double); // vtkGetMacro(DeltaMajor, double); //@} //@{ /** * Set/Get the starting position for minor and major tick points on * the range and the delta values that determine their spacing. The * range and the position need not be identical. ie the displayed * values need not match the actual positions in 3D space. */ vtkSetMacro(MinorRangeStart, double); vtkGetMacro(MinorRangeStart, double); vtkSetMacro(MajorRangeStart, double); vtkGetMacro(MajorRangeStart, double); vtkSetMacro(DeltaRangeMinor, double); vtkGetMacro(DeltaRangeMinor, double); vtkSetMacro(DeltaRangeMajor, double); vtkGetMacro(DeltaRangeMajor, double); //@} void SetLabels(vtkStringArray* labels); void BuildAxis(vtkViewport* viewport, bool); //@{ /** * Get title actor and it is responsible for drawing * title text. */ vtkGetObjectMacro(TitleActor, vtkAxisFollower); //@} //@{ /** * Get exponent follower actor */ vtkGetObjectMacro(ExponentActor, vtkAxisFollower); //@} /** * Get label actors responsigle for drawing label text. */ inline vtkAxisFollower** GetLabelActors() { return this->LabelActors; } //@{ /** * Get title actor and it is responsible for drawing * title text. */ vtkGetObjectMacro(TitleProp3D, vtkProp3DAxisFollower); //@} /** * Get label actors responsigle for drawing label text. */ inline vtkProp3DAxisFollower** GetLabelProps3D() { return this->LabelProps3D; } //@{ /** * Get title actor and it is responsible for drawing * title text. */ vtkGetObjectMacro(ExponentProp3D, vtkProp3DAxisFollower); //@} //@{ /** * Get total number of labels built. Once built * this count does not change. */ vtkGetMacro(NumberOfLabelsBuilt, int); //@} //@{ /** * Set/Get flag whether to calculate title offset. * Default is true. */ vtkSetMacro(CalculateTitleOffset, int); vtkGetMacro(CalculateTitleOffset, int); vtkBooleanMacro(CalculateTitleOffset, int); //@} //@{ /** * Set/Get flag whether to calculate label offset. * Default is true. */ vtkSetMacro(CalculateLabelOffset, int); vtkGetMacro(CalculateLabelOffset, int); vtkBooleanMacro(CalculateLabelOffset, int); //@} //@{ /** * Set/Get the 2D mode */ vtkSetMacro(Use2DMode, int); vtkGetMacro(Use2DMode, int); //@} //@{ /** * Set/Get the 2D mode the vertical offset for X title in 2D mode */ vtkSetMacro(VerticalOffsetXTitle2D, double); vtkGetMacro(VerticalOffsetXTitle2D, double); //@} //@{ /** * Set/Get the 2D mode the horizontal offset for Y title in 2D mode */ vtkSetMacro(HorizontalOffsetYTitle2D, double); vtkGetMacro(HorizontalOffsetYTitle2D, double); //@} //@{ /** * Set/Get whether title position must be saved in 2D mode */ vtkSetMacro(SaveTitlePosition, int); vtkGetMacro(SaveTitlePosition, int); //@} //@{ /** * Provide real vector for non aligned axis */ vtkSetVector3Macro(AxisBaseForX, double); vtkGetVector3Macro(AxisBaseForX, double); //@} //@{ /** * Provide real vector for non aligned axis */ vtkSetVector3Macro(AxisBaseForY, double); vtkGetVector3Macro(AxisBaseForY, double); //@} //@{ /** * Provide real vector for non aligned axis */ vtkSetVector3Macro(AxisBaseForZ, double); vtkGetVector3Macro(AxisBaseForZ, double); //@} //@{ /** * Notify the axes that is not part of a cube anymore */ vtkSetMacro(AxisOnOrigin, int); vtkGetMacro(AxisOnOrigin, int); //@} //@{ /** * Set/Get the offsets used to position texts. */ vtkSetMacro(LabelOffset, double); vtkGetMacro(LabelOffset, double); vtkSetMacro(TitleOffset, double); vtkGetMacro(TitleOffset, double); vtkSetMacro(ExponentOffset, double); vtkGetMacro(ExponentOffset, double); vtkSetMacro(ScreenSize, double); vtkGetMacro(ScreenSize, double); //@} protected: vtkAxisActor(); ~vtkAxisActor(); char* Title; char* Exponent; double Range[2]; double LastRange[2]; char* LabelFormat; int UseTextActor3D; int NumberOfLabelsBuilt; int MinorTicksVisible; int LastMinorTicksVisible; /** * The location of the ticks. * Inside: tick end toward positive direction of perpendicular axes. * Outside: tick end toward negative direction of perpendicular axes. */ int TickLocation; /** * Hold the alignement property of the title related to the axis. * Possible Alignment: VTK_ALIGN_BOTTOM, VTK_ALIGN_TOP, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2. */ int TitleAlignLocation; /** * Hold the alignement property of the exponent coming from the label values. * Possible Alignment: VTK_ALIGN_BOTTOM, VTK_ALIGN_TOP, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2. */ int ExponentLocation; int DrawGridlines; int DrawGridlinesOnly; int LastDrawGridlines; int DrawGridlinesLocation; // 0: all | 1: closest | 2: farest int LastDrawGridlinesLocation; // 0: all | 1: closest | 2: farest double GridlineXLength; double GridlineYLength; double GridlineZLength; int DrawInnerGridlines; int LastDrawInnerGridlines; int DrawGridpolys; int LastDrawGridpolys; int AxisVisibility; int TickVisibility; int LastTickVisibility; int LabelVisibility; int TitleVisibility; bool ExponentVisibility; bool LastMajorTickPointCorrection; bool Log; int AxisType; int AxisPosition; double Bounds[6]; // coordinate system for axisAxtor, relative to world coordinates double AxisBaseForX[3]; double AxisBaseForY[3]; double AxisBaseForZ[3]; private: vtkAxisActor(const vtkAxisActor&) VTK_DELETE_FUNCTION; void operator=(const vtkAxisActor&) VTK_DELETE_FUNCTION; void TransformBounds(vtkViewport*, double bnds[6]); void BuildLabels(vtkViewport*, bool); void BuildLabels2D(vtkViewport*, bool); void SetLabelPositions(vtkViewport*, bool); void SetLabelPositions2D(vtkViewport*, bool); /** * Set orientation of the actor 2D (follower) to keep the axis orientation and stay on the right * size */ void RotateActor2DFromAxisProjection(vtkTextActor* pActor2D); /** * Init the geometry of the title. (no positioning or orientation) */ void InitTitle(); /** * Init the geometry of the common exponent of the labels values. (no positioning or orientation) */ void InitExponent(); /** * This methdod set the text and set the base position of the follower from the axis * The position will be modified in vtkAxisFollower::Render() sub-functions according to the * camera position * for convenience purpose. */ void BuildTitle(bool); /** * Build the actor to display the exponent in case it should appear next to the title or next to * p2 coordinate. */ void BuildExponent(bool force); void BuildExponent2D(vtkViewport* viewport, bool force); void BuildTitle2D(vtkViewport* viewport, bool); void SetAxisPointsAndLines(void); bool BuildTickPoints(double p1[3], double p2[3], bool force); // Build major ticks for linear scale. void BuildMajorTicks(double p1[3], double p2[3], double localCoordSys[3][3]); // Build major ticks for logarithmic scale. void BuildMajorTicksLog(double p1[3], double p2[3], double localCoordSys[3][3]); // Build minor ticks for linear scale. void BuildMinorTicks(double p1[3], double p2[3], double localCoordSys[3][3]); // Build minor ticks for logarithmic scale enabled void BuildMinorTicksLog(double p1[3], double p2[3], double localCoordSys[3][3]); void BuildAxisGridLines(double p1[3], double p2[3], double localCoordSys[3][3]); bool TickVisibilityChanged(void); vtkProperty* NewTitleProperty(); vtkProperty2D* NewTitleProperty2D(); vtkProperty* NewLabelProperty(); bool BoundsDisplayCoordinateChanged(vtkViewport* viewport); vtkCoordinate* Point1Coordinate; vtkCoordinate* Point2Coordinate; double MajorTickSize; double MinorTickSize; // For each axis (for the inner gridline generation) double MajorStart[3]; double DeltaMajor[3]; double MinorStart; double DeltaMinor; // For the ticks, w.r.t to the set range double MajorRangeStart; double MinorRangeStart; /** * step between 2 minor ticks, in range value (values displayed on the axis) */ double DeltaRangeMinor; /** * step between 2 major ticks, in range value (values displayed on the axis) */ double DeltaRangeMajor; int LastAxisPosition; int LastAxisType; int LastTickLocation; double LastLabelStart; vtkPoints* MinorTickPts; vtkPoints* MajorTickPts; vtkPoints* GridlinePts; vtkPoints* InnerGridlinePts; vtkPoints* GridpolyPts; vtkVectorText* TitleVector; vtkPolyDataMapper* TitleMapper; vtkAxisFollower* TitleActor; vtkTextActor* TitleActor2D; vtkProp3DAxisFollower* TitleProp3D; vtkTextActor3D* TitleActor3D; vtkTextProperty* TitleTextProperty; //@{ /** * Mapper/Actor used to display a common exponent of the label values */ vtkVectorText* ExponentVector; vtkPolyDataMapper* ExponentMapper; vtkAxisFollower* ExponentActor; vtkTextActor* ExponentActor2D; vtkProp3DAxisFollower* ExponentProp3D; vtkTextActor3D* ExponentActor3D; //@} vtkVectorText** LabelVectors; vtkPolyDataMapper** LabelMappers; vtkAxisFollower** LabelActors; vtkProp3DAxisFollower** LabelProps3D; vtkTextActor** LabelActors2D; vtkTextActor3D** LabelActors3D; vtkTextProperty* LabelTextProperty; // Main line axis vtkPolyData* AxisLines; vtkPolyDataMapper* AxisLinesMapper; vtkActor* AxisLinesActor; // Ticks of the axis vtkPolyData *AxisMajorTicks, *AxisMinorTicks; vtkPolyDataMapper *AxisMajorTicksMapper, *AxisMinorTicksMapper; vtkActor *AxisMajorTicksActor, *AxisMinorTicksActor; vtkPolyData* Gridlines; vtkPolyDataMapper* GridlinesMapper; vtkActor* GridlinesActor; vtkPolyData* InnerGridlines; vtkPolyDataMapper* InnerGridlinesMapper; vtkActor* InnerGridlinesActor; vtkPolyData* Gridpolys; vtkPolyDataMapper* GridpolysMapper; vtkActor* GridpolysActor; vtkCamera* Camera; vtkTimeStamp BuildTime; vtkTimeStamp BuildTickPointsTime; vtkTimeStamp BoundsTime; vtkTimeStamp LabelBuildTime; vtkTimeStamp TitleTextTime; vtkTimeStamp ExponentTextTime; int AxisOnOrigin; int AxisHasZeroLength; int CalculateTitleOffset; int CalculateLabelOffset; /** * Use xy-axis only when Use2DMode=1: */ int Use2DMode; /** * Vertical offset in display coordinates for X axis title (used in 2D mode only) * Default: -40 */ double VerticalOffsetXTitle2D; /** * Vertical offset in display coordinates for X axis title (used in 2D mode only) * Default: -50 */ double HorizontalOffsetYTitle2D; /** * Save title position (used in 2D mode only): * val = 0 : no need to save position (doesn't stick actors in a position) * val = 1 : positions have to be saved during the next render pass * val = 2 : positions are saved; use them */ int SaveTitlePosition; /** * Constant position for the title (used in 2D mode only) */ double TitleConstantPosition[2]; /** * True if the 2D title has to be built, false otherwise */ bool NeedBuild2D; double LastMinDisplayCoordinate[3]; double LastMaxDisplayCoordinate[3]; double TickVector[3]; //@{ /** * Offsets used to position text. */ double ScreenSize; double LabelOffset; double TitleOffset; double ExponentOffset; }; //@} #endif
26.357438
99
0.704594
[ "geometry", "render", "object", "vector", "3d" ]
2eeeb9d9e95100b8207e53625a05bcd5a7e307e4
4,463
h
C
LivingCity/bTraffic/bEdgeIntersectionData.h
pavyedav/manta
575d4395ad8a6000e8ca1de8c450fad2a541f19b
[ "BSD-3-Clause" ]
10
2020-08-12T12:45:35.000Z
2022-03-13T03:05:00.000Z
LivingCity/bTraffic/bEdgeIntersectionData.h
pavyedav/manta
575d4395ad8a6000e8ca1de8c450fad2a541f19b
[ "BSD-3-Clause" ]
24
2020-08-19T18:19:04.000Z
2022-03-12T00:55:34.000Z
LivingCity/bTraffic/bEdgeIntersectionData.h
pavyedav/manta
575d4395ad8a6000e8ca1de8c450fad2a541f19b
[ "BSD-3-Clause" ]
3
2020-06-05T03:40:38.000Z
2021-06-12T01:55:02.000Z
//--------------------------------------------------------------------------------------------------------------------- // Copyright 2017, 2018 Purdue University, Ignacio Garcia Dorado, Daniel Aliaga // // 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. //--------------------------------------------------------------------------------------------------------------------- /************************************************************************************************ * @desc Class that contains the structure of the lane maps * @author igaciad ************************************************************************************************/ #pragma once #include <vector> #define S_TOSTART 0x00 #define S_MOVE 0x01 #define S_PASSINT 0x02 #define S_END 0xFF #include "stdint.h" #define ushort uint16_t #define uint uint32_t #define uchar uint8_t namespace LC { struct BEdgesDataCUDA { uchar *numLinesB; ushort *nextInters; uchar *nextIntersType; ushort *lengthC;//length in cells float *maxSpeedCpSec;//speed in cells per delta time }; struct BEdgesData { std::vector<uchar> numLinesB; std::vector<ushort> nextInters; std::vector<uchar> nextIntersType; std::vector<ushort> lengthC;//length in cells std::vector<float> maxSpeedCpSec;//speed in cells per delta time void resize(int size) { numLinesB.resize(size); nextInters.resize(size); nextIntersType.resize(size); lengthC.resize(size); maxSpeedCpSec.resize(size); } void clear() { numLinesB.clear(); nextInters.clear(); nextIntersType.clear(); lengthC.clear(); maxSpeedCpSec.clear(); } }; ///////////////////////////////// // STOP struct BStopsData { std::vector<uchar> state; std::vector<ushort> intersNumber;//number of intersect void resize(int size) { state.resize(size); intersNumber.resize(size); } }; ///////////////////////////////// // TRAFFIC LIGHT struct BTrafficLightData { std::vector<ushort> intersNumber;//number of intersect std::vector<uchar> offSet;//time offset std::vector<ushort> phaseInd; std::vector<uchar> numPhases; std::vector<uchar> curPhase; std::vector<unsigned long> phases; std::vector<uchar> phaseTime;//note that it is *2 }; ///////////////////////////////// // INTERSECTION struct BIntersectionsData { std::vector<unsigned long> req; std::vector<unsigned long> trafficLight; // common std::vector<uchar> numIn; std::vector<uchar> type; std::vector<float> nextEvent; void resize(int size) { req.resize(size); trafficLight.resize(size); numIn.resize(size); type.resize(size); nextEvent.resize(size); }// void resetReq() { memset((uchar *)(&req[0]), 0, req.size()*sizeof(unsigned long)); }// void resetTraff() { memset((uchar *)(&trafficLight[0]), 0x00, trafficLight.size()*sizeof(unsigned long)); }// }; }
30.993056
120
0.61685
[ "vector" ]
2ef0ac95538bf7e0c4db1e8a012bc1b4653776cf
2,968
h
C
motioncorr_v2.1/src/SP++3/include/fftw.h
cianfrocco-lab/Motion-correction
c77ee034bba2ef184837e070dde43f75d8a4e1e7
[ "MIT" ]
11
2015-12-21T19:47:53.000Z
2021-01-21T02:58:43.000Z
src/SP++3/include/fftw.h
wjiang/motioncorr
14ed37d1cc72e55d1592e78e3dda758cd46a3698
[ "Naumen", "Condor-1.1", "MS-PL" ]
5
2016-05-24T10:55:18.000Z
2016-06-10T01:07:42.000Z
src/SP++3/include/fftw.h
wjiang/motioncorr
14ed37d1cc72e55d1592e78e3dda758cd46a3698
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2016-04-26T10:14:20.000Z
2020-10-14T07:34:59.000Z
/* * Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.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 or any later version. * * 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 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. A copy of the GNU General Public License is available at: * http://www.fsf.org/licensing/licenses */ /***************************************************************************** * fftw.h * * A simple C++ interface for FFTW. This file only provides the one dimension * DFT and IDFT for data type as "Vector<Type>" in SPLab, where "Type" can * be "double", "complex<double>, "float", "complex<float>, "long double", * "complex<long double>. * * If you need execute FFT many times in your program, it's not a good idear * for using this interface because of losing efficiency. * * Zhang Ming, 2010-01, Xi'an Jiaotong University. *****************************************************************************/ #ifndef FFTW_H #define FFTW_H #include <complex> #include <fftw3.h> #include <vector.h> namespace splab { void fftw( Vector<double>&, Vector< complex<double> >& ); void fftw( Vector<float>&, Vector< complex<float> >& ); void fftw( Vector<long double>&, Vector< complex<long double> >& ); void fftw( Vector< complex<double> >&, Vector< complex<double> >& ); void fftw( Vector< complex<float> >&, Vector< complex<float> >& ); void fftw( Vector< complex<long double> >&, Vector< complex<long double> >& ); void ifftw( Vector< complex<double> >&, Vector<double>& ); void ifftw( Vector< complex<float> >&, Vector<float>& ); void ifftw( Vector< complex<long double> >&, Vector<long double>& ); void ifftw( Vector< complex<double> >&, Vector< complex<double> >& ); void ifftw( Vector< complex<float> >&, Vector< complex<float> >& ); void ifftw( Vector< complex<long double> >&, Vector< complex<long double> >& ); #include <fftw-impl.h> } // namespace splab #endif // FFTW_H
37.1
80
0.626685
[ "vector" ]
2ef0adb23652ca411bf045677a95d32393b7f71c
16,786
h
C
EmldCore/CompactHashMap/VectorManager.h
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
3
2020-08-16T17:56:25.000Z
2021-02-25T21:55:39.000Z
EmldCore/CompactHashMap/VectorManager.h
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
EmldCore/CompactHashMap/VectorManager.h
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
//-***************************************************************************** // Copyright (c) 2001-2013, Christopher Jon Horvath. 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 Christopher Jon Horvath nor the names of his // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //-***************************************************************************** #ifndef _EmldCore_CompactHashMap_VectorManager_h_ #define _EmldCore_CompactHashMap_VectorManager_h_ #include "Foundation.h" namespace EmldCore { namespace CompactHashMap { //-***************************************************************************** template <typename T> class TypedManagedCvectorPtrHandle { public: typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef TypedManagedCvectorPtrHandle<T> this_type; typedef typename storage_traits<T>::storage_type storage_value_type; typedef BucketedConcurrentVector<storage_value_type> storage_vector_type; typedef storage_vector_type* storage_vector_ptr; private: storage_vector_ptr m_storageRawPtr; protected: void resetRaw() { m_storageRawPtr = NULL; } public: TypedManagedCvectorPtrHandle() : m_storageRawPtr( NULL ) {} explicit TypedManagedCvectorPtrHandle( storage_vector_ptr i_ptr ) : m_storageRawPtr( i_ptr ) { EMLD_ASSERT( sizeof( storage_value_type ) == sizeof( value_type ), "Incompatible storage & vector types." ); } pointer data() { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::data() " << "NULL storage pointer" ); if ( m_storageRawPtr->size() == 0 ) { return NULL; } else { return reinterpret_cast<T*>( &( m_storageRawPtr->front() ) ); } } const_pointer cdata() const { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::data() const " << "NULL storage pointer" ); if ( m_storageRawPtr->size() == 0 ) { return NULL; } else { return reinterpret_cast<const T*>( &( m_storageRawPtr->front() ) ); } } const_pointer data() const { return cdata(); } size_type size() const { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::size() " << "NULL storage pointer" ); return m_storageRawPtr->size(); } iterator begin() { return data(); } const_iterator begin() const { return data(); } const_iterator cbegin() const { return data(); } iterator end() { return data() + size(); } const_iterator end() const { return data() + size(); } const_iterator cend() const { return data() + size(); } reference operator[]( size_type i ) { return data()[i]; } const_reference operator[]( size_type i ) const { return data()[i]; } reference front() { return data()[0]; } const_reference front() const { return cdata()[0]; } reference back() { return data()[size()-1]; } const_reference back() const { return cdata()[size()-1]; } void reserve( size_type i_size ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::reserve() " << "NULL storage pointer" ); m_storageRawPtr->reserve( i_size ); } void resize( size_type i_size ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::resize() " << "NULL storage pointer" ); m_storageRawPtr->resize( i_size ); } void clear() { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::clear() " << "NULL storage pointer" ); m_storageRawPtr->clear(); } void push_back( const_reference i_value ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::push_back() " << "NULL storage pointer" ); m_storageRawPtr->push_back( reinterpret_cast<const storage_value_type&>( i_value ) ); } template <typename ITER> void append( ITER i_begin, ITER i_end ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::append( begin, end ) " << "NULL storage pointer" ); size_type n = i_end - i_begin; std::copy( i_begin, i_end, m_storageRawPtr->grow_by( n ) ); } template <typename VEC> void append( const VEC& i_vec ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::append( vec ) " << "NULL storage pointer" ); std::copy( i_vec.begin(), i_vec.end(), m_storageRawPtr->grow_by( i_vec.size() ) ); } // Swapping void swap( TypedManagedCvectorPtrHandle<T> i_other ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::swap() " << "NULL storage pointer" ); EMLD_ASSERT( i_other.m_storageRawPtr, "TypedManagedCvectorPtrHandle::swap() " << "NULL other shared storage pointer" ); m_storageRawPtr->swap( *( i_other.m_storageRawPtr ) ); } // Copying. template <typename VEC> void copy_from( const VEC& i_vec ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::copy_from() " << "NULL storage pointer" ); EmldCore::ParallelUtil::VectorCopy( i_vec, *this ); } // Zero-fill. void fill_with_zero() { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::fill_with_zero() " << "NULL storage pointer" ); EmldCore::ParallelUtil::VectorZeroBits( *this ); } // Value-fill. void fill_with_value( const_reference i_val ) { EMLD_ASSERT( m_storageRawPtr, "TypedManagedCvectorPtrHandle::fill_with_value() " << "NULL storage pointer" ); EmldCore::ParallelUtil::VectorFill( *this, i_val ); } // Validity of the handle. bool valid() const { return ( m_storageRawPtr != NULL ); } operator bool() const { return valid(); } bool operator!() const { return !valid(); } }; //-***************************************************************************** //-***************************************************************************** // MANAGER FOR A SINGLE STORAGE SINGLE TYPE //-***************************************************************************** //-***************************************************************************** //-***************************************************************************** template <typename STORAGE_TYPE> class SubVectorManager { public: typedef STORAGE_TYPE storage_value_type; typedef BucketedConcurrentVector<storage_value_type> container_type; typedef container_type* container_ptr; typedef EMLD_SHARED_PTR<container_type> container_sptr; typedef std::vector<container_sptr> container_sptr_vec; typedef typename container_type::size_type size_type; typedef typename container_type::difference_type difference_type; protected: // The used and unused containers container_sptr_vec m_used; container_sptr_vec m_unused; // The bucket size. size_type m_bucketSize; protected: SubVectorManager() { m_bucketSize = container_type::DEFAULT_BUCKET_SIZE(); } SubVectorManager( std::size_t i_bs ) { m_bucketSize = std::max( container_type::MIN_BUCKET_SIZE(), i_bs ); } public: size_type bucketSize() const { return m_bucketSize; } void setBucketSize( size_type i_bs ) { m_bucketSize = std::max( container_type::MIN_BUCKET_SIZE(), i_bs ); for ( typename container_sptr_vec::iterator iter = m_used.begin(); iter != m_used.end(); ++iter ) { (*iter)->set_bucket_size( m_bucketSize ); } for ( typename container_sptr_vec::iterator iter = m_unused.begin(); iter != m_unused.end(); ++iter ) { (*iter)->set_bucket_size( m_bucketSize ); } } void protectedGet( container_ptr& o_c ) { container_sptr c; if ( m_unused.size() > 0 ) { c = m_unused.back(); m_unused.pop_back(); #ifdef EMLD_TEST_MVEC_DEBUG_VERBOSE std::cout << "MVEC: UU.get popped " << c.get() << " off unused size[" << sizeof( storage_value_type ) << "]" << std::endl; #endif } else { c.reset( new container_type() ); #ifdef EMLD_TEST_MVEC_DEBUG_VERBOSE std::cout << "MVEC: UU.get created " << c.get() << " size[" << sizeof( storage_value_type ) << "]" << std::endl; #endif } m_used.push_back( c ); o_c = c.get(); } void protectedRelease( container_ptr i_c ) { size_type n = m_used.size(); for ( size_type i = 0; i < n; ++i ) { container_sptr c = m_used[i]; if ( c.get() == i_c ) { #ifdef EMLD_TEST_MVEC_DEBUG_VERBOSE std::cout << "MVEC: released " << c.get() << " off used[" << i << "] size[" << sizeof( storage_value_type ) << "]" << std::endl; #endif if ( i != n - 1 ) { m_used[i] = m_used[n - 1]; } m_used.pop_back(); m_unused.push_back( c ); return; } } EMLD_THROW( "Attempting to release a vector that's not in " "the used list." ); } }; //-***************************************************************************** template <typename DERIVED> class VectorManagerWrapper { public: typedef DERIVED derived_type; typedef VectorManagerWrapper<DERIVED> this_type; typedef std::size_t size_type; //-************************************************************************* VectorManagerWrapper() {} //-************************************************************************* template <typename CONTAINER> class StorageVectorDeleter { public: StorageVectorDeleter( VectorManagerWrapper<DERIVED>& i_manager ) : m_manager( i_manager ) {} void operator()( CONTAINER* i_ptr ) { m_manager.storageVectorDeleterRelease<CONTAINER>( i_ptr ); } protected: VectorManagerWrapper<DERIVED>& m_manager; }; //-************************************************************************* // A Handle around the Concurrent Vector which allows us to insert // a deleter. template <typename T> class TypedManagedCvectorHandle : public TypedManagedCvectorPtrHandle<T> { public: typedef TypedManagedCvectorPtrHandle<T> super_type; typedef super_type ptr_handle_type; typedef typename super_type::storage_vector_type storage_vector_type; typedef typename super_type::storage_vector_ptr storage_vector_ptr; typedef EMLD_SHARED_PTR<storage_vector_type> storage_vector_sptr; TypedManagedCvectorHandle() : TypedManagedCvectorPtrHandle<T>() {} // Parallel functors shouldn't have an object that has a shared ptr // in it, they may confuse the reference count and accidentally delete // something we need to keep. This function returns an internally // raw version of the handle for keeping in parallel functors. TypedManagedCvectorPtrHandle<T> ptrHandle() { return TypedManagedCvectorPtrHandle<T>( m_storageSharedPtr.get() ); } void reset() { this->resetRaw(); m_storageSharedPtr.reset(); } // Not actually a public constructor. TypedManagedCvectorHandle( storage_vector_ptr i_ptr, StorageVectorDeleter<storage_vector_type> i_svd ) : TypedManagedCvectorPtrHandle<T>( i_ptr ) , m_storageSharedPtr( i_ptr, i_svd ) {} protected: storage_vector_sptr m_storageSharedPtr; }; //-************************************************************************* template <typename T> TypedManagedCvectorHandle<T> get( size_type N ) { typedef TypedManagedCvectorHandle<T> handle_type; typedef T value_type; typedef typename handle_type::storage_value_type storage_value_type; typedef typename handle_type::storage_vector_type storage_vector_type; typedef typename handle_type::storage_vector_ptr storage_vector_ptr; typedef typename handle_type::storage_vector_sptr storage_vector_sptr; typedef StorageVectorDeleter<storage_vector_type> storage_vector_deleter; typedef SubVectorManager<storage_value_type> sub_type; storage_vector_ptr data = NULL; DERIVED* derivedThis = static_cast<DERIVED*>( this ); sub_type* subThis = static_cast<sub_type*>( derivedThis ); subThis->protectedGet( data ); handle_type handle( data, storage_vector_deleter( *this ) ); handle.resize( N ); return handle; } //-************************************************************************* // Don't call this directly. template <typename storage_vector_type> void storageVectorDeleterRelease( storage_vector_type* i_ptr ) { typedef typename storage_vector_type::value_type storage_value_type; typedef SubVectorManager<storage_value_type> sub_type; DERIVED* derivedThis = static_cast<DERIVED*>( this ); sub_type* subThis = static_cast<sub_type*>( derivedThis ); subThis->protectedRelease( i_ptr ); } }; //-***************************************************************************** // EXAMPLE // class MyVectorManager // : public VectorManagerWrapper<MyVectorManager> // , public SubVectorManager<storage_bytes_0> // , public SubVectorManager<storage_bytes_1> // {}; //-***************************************************************************** } // End namespace CompactHashMap } // End namespace EmldCore #endif
35.190776
80
0.551352
[ "object", "vector" ]
2efadea3e601fb3fa32b114554400d09a4d9a53f
3,190
h
C
TemplePlus/gamesystems/objects/arrayidxbitmaps.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
69
2015-05-05T14:09:25.000Z
2022-02-15T06:13:04.000Z
TemplePlus/gamesystems/objects/arrayidxbitmaps.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
457
2015-05-01T22:07:45.000Z
2022-03-31T02:19:10.000Z
TemplePlus/gamesystems/objects/arrayidxbitmaps.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
25
2016-02-04T21:19:53.000Z
2021-11-15T23:14:51.000Z
#pragma once #include <EASTL/vector.h> class OutputStream; struct TioFile; using ArrayIdxMapId = uint32_t; struct ArrayIndices { size_t firstIdx; // Index of first bitmap block used size_t count; // Number of bitmap blocks used }; /** * Manages storage for array index bitmaps, which are used to * more efficiently store sparse arrays. */ class ArrayIndexBitmaps { public: ArrayIndexBitmaps(); // Allocate an array index map ArrayIdxMapId Allocate(); // Free an array index map void Free(ArrayIdxMapId id); // Copies an array index map and returns the id of the created copy ArrayIdxMapId Clone(ArrayIdxMapId id); // Removes an index from an index map void RemoveIndex(ArrayIdxMapId id, size_t index); // Adds an index to an index map if it's not already in it void AddIndex(ArrayIdxMapId id, size_t index); // Checks if an index is present in the array index map bool HasIndex(ArrayIdxMapId id, size_t index) const; // Get the index mapped to a range with no gaps (for storage purposes) size_t GetPackedIndex(ArrayIdxMapId id, size_t index) const; // Returns the serialized size of an array index map in bytes size_t GetSerializedSize(ArrayIdxMapId id) const; // Deserializes an array index map from the given memory buffer and returns // the id of the newly allocated map ArrayIdxMapId DeserializeFromMemory(uint8_t **buffer); // Serializes an array index map to the given memory buffer void SerializeToMemory(ArrayIdxMapId id, uint8_t **buffer) const; // Serializes an array index map to the given stream void SerializeToStream(ArrayIdxMapId id, OutputStream &stream) const; // Deserializes an array index map from the given file and returns // the id of the newly allocated map or throws on failure. ArrayIdxMapId DeserializeFromFile(TioFile *file); // Calls a callback for all indices that are present in the index map. // Stops iterating when false is returned. Returns false if any call to // callback returned false, true otherwise. bool ForEachIndex(ArrayIdxMapId id, std::function<bool(size_t)> callback) const; // Count of set bits in given 32-bit integer up to and not including the given bit (0-31) uint8_t PopCntConstrained(uint32_t value, uint8_t upToExclusive) const; // Count of set bits in given 32-bit integer uint8_t PopCnt(uint32_t value) const; private: // The bitmap blocks that contain the actual index bitmaps eastl::vector<uint32_t> mBitmapBlocks; // State stored for each array eastl::vector<ArrayIndices> mArrays; // IDs of free entries in mArrays eastl::vector<ArrayIdxMapId> mFreeIds; // Bitmask lookup table that contains bitmasks that have the lower 0 - 31 // bits set. This is used in counting the bits up and until position i in // a DWORD std::array<uint32_t, 32> mPartialBitmasks; // A bit count lookup table for all values of a 16-bit integer std::array<uint8_t, UINT16_MAX + 1> mBitCountLut; // Shrinks an index map by the specified number of bitmap blocks void Shrink(ArrayIdxMapId id, size_t shrinkBy); // Extends an index map by the specified number of bitmap blocks void Extend(ArrayIdxMapId id, size_t extendBy); }; extern ArrayIndexBitmaps arrayIdxBitmaps;
32.222222
90
0.762382
[ "vector" ]
2efd4568e2b82efa724641475c123ac8237c5587
2,856
h
C
inetsrv/msmq/src/lib/inc/rwlock.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/msmq/src/lib/inc/rwlock.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/msmq/src/lib/inc/rwlock.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: rwlock.h Abstract: This file contains a Multi-reader, one-writer synchronization object and useful templates for auto lock/unlock Author: Uri Habusha (urih), 27-Dec-99 --*/ #pragma once #ifndef _MSMQ_RWLOCK_H_ #define _MSMQ_RWLOCK_H_ /*++ Class: CReadWriteLock Purpose: Shared/Exclusive access services Interface: LockRead - Grab shared access to resource LockWrite - Grab exclusive access to resource UnlockRead - Release shared access to resource UnlockWrite - Release exclusive access to resource Notes: This class guards a resource in such a way that it can have multiple readers XOR one writer at any one time. It's clever, and won't let writers be starved by a constant flow of readers. Another way of saying this is, it can guard a resource in a way that offers both shared and exclusive access to it. If any thread holds a lock of one sort on a CReadWriteLock, it had better not grab a second. That way could lay deadlock, matey! Har har har..... --*/ class CReadWriteLock { public: CReadWriteLock(unsigned long ulcSpinCount = 0); ~CReadWriteLock(void); void LockRead(void); void LockWrite(void); void UnlockRead(void); void UnlockWrite(void); private: HANDLE GetReadWaiterSemaphore(void); HANDLE GetWriteWaiterEvent (void); private: unsigned long m_ulcSpinCount; // spin counter volatile unsigned long m_dwFlag; // internal state, see implementation HANDLE m_hReadWaiterSemaphore; // semaphore for awakening read waiters HANDLE m_hWriteWaiterEvent; // event for awakening write waiters }; //--------------------------------------------------------- // // class CSR // //--------------------------------------------------------- class CSR { public: CSR(CReadWriteLock& lock) : m_lock(&lock) { m_lock->LockRead(); } ~CSR() {if(m_lock) m_lock->UnlockRead(); } CReadWriteLock* detach(){CReadWriteLock* lock = m_lock; m_lock = 0; return lock;} private: CReadWriteLock* m_lock; }; //--------------------------------------------------------- // // class CSW // //--------------------------------------------------------- class CSW { public: CSW(CReadWriteLock& lock) : m_lock(&lock) { m_lock->LockWrite(); } ~CSW() {if(m_lock) m_lock->UnlockWrite(); } CReadWriteLock* detach(){CReadWriteLock* lock = m_lock; m_lock = 0; return lock; } private: CReadWriteLock* m_lock; }; #endif // _MSMQ_RWLOCK_H_
26.691589
87
0.567577
[ "object" ]
2c01528b829478f3e0ca04900c7bc06eeff4f01c
6,717
h
C
aws-cpp-sdk-lambda/include/aws/lambda/model/AccountLimit.h
PaladinAI/aws-sdk-cpp
8f1ace035adf6117f59b535a81de72756e6203e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lambda/include/aws/lambda/model/AccountLimit.h
PaladinAI/aws-sdk-cpp
8f1ace035adf6117f59b535a81de72756e6203e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lambda/include/aws/lambda/model/AccountLimit.h
PaladinAI/aws-sdk-cpp
8f1ace035adf6117f59b535a81de72756e6203e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/lambda/Lambda_EXPORTS.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Lambda { namespace Model { /** * <p>Provides limits of code size and concurrency associated with the current * account and region.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/AccountLimit">AWS * API Reference</a></p> */ class AWS_LAMBDA_API AccountLimit { public: AccountLimit(); AccountLimit(Aws::Utils::Json::JsonView jsonValue); AccountLimit& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Maximum size, in bytes, of a code package you can upload per region. The * default size is 75 GB. </p> */ inline long long GetTotalCodeSize() const{ return m_totalCodeSize; } /** * <p>Maximum size, in bytes, of a code package you can upload per region. The * default size is 75 GB. </p> */ inline void SetTotalCodeSize(long long value) { m_totalCodeSizeHasBeenSet = true; m_totalCodeSize = value; } /** * <p>Maximum size, in bytes, of a code package you can upload per region. The * default size is 75 GB. </p> */ inline AccountLimit& WithTotalCodeSize(long long value) { SetTotalCodeSize(value); return *this;} /** * <p>Size, in bytes, of code/dependencies that you can zip into a deployment * package (uncompressed zip/jar size) for uploading. The default limit is 250 * MB.</p> */ inline long long GetCodeSizeUnzipped() const{ return m_codeSizeUnzipped; } /** * <p>Size, in bytes, of code/dependencies that you can zip into a deployment * package (uncompressed zip/jar size) for uploading. The default limit is 250 * MB.</p> */ inline void SetCodeSizeUnzipped(long long value) { m_codeSizeUnzippedHasBeenSet = true; m_codeSizeUnzipped = value; } /** * <p>Size, in bytes, of code/dependencies that you can zip into a deployment * package (uncompressed zip/jar size) for uploading. The default limit is 250 * MB.</p> */ inline AccountLimit& WithCodeSizeUnzipped(long long value) { SetCodeSizeUnzipped(value); return *this;} /** * <p>Size, in bytes, of a single zipped code/dependencies package you can upload * for your Lambda function(.zip/.jar file). Try using Amazon S3 for uploading * larger files. Default limit is 50 MB.</p> */ inline long long GetCodeSizeZipped() const{ return m_codeSizeZipped; } /** * <p>Size, in bytes, of a single zipped code/dependencies package you can upload * for your Lambda function(.zip/.jar file). Try using Amazon S3 for uploading * larger files. Default limit is 50 MB.</p> */ inline void SetCodeSizeZipped(long long value) { m_codeSizeZippedHasBeenSet = true; m_codeSizeZipped = value; } /** * <p>Size, in bytes, of a single zipped code/dependencies package you can upload * for your Lambda function(.zip/.jar file). Try using Amazon S3 for uploading * larger files. Default limit is 50 MB.</p> */ inline AccountLimit& WithCodeSizeZipped(long long value) { SetCodeSizeZipped(value); return *this;} /** * <p>Number of simultaneous executions of your function per region. For more * information or to request a limit increase for concurrent executions, see <a * href="http://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html">Lambda * Function Concurrent Executions</a>. The default limit is 1000.</p> */ inline int GetConcurrentExecutions() const{ return m_concurrentExecutions; } /** * <p>Number of simultaneous executions of your function per region. For more * information or to request a limit increase for concurrent executions, see <a * href="http://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html">Lambda * Function Concurrent Executions</a>. The default limit is 1000.</p> */ inline void SetConcurrentExecutions(int value) { m_concurrentExecutionsHasBeenSet = true; m_concurrentExecutions = value; } /** * <p>Number of simultaneous executions of your function per region. For more * information or to request a limit increase for concurrent executions, see <a * href="http://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html">Lambda * Function Concurrent Executions</a>. The default limit is 1000.</p> */ inline AccountLimit& WithConcurrentExecutions(int value) { SetConcurrentExecutions(value); return *this;} /** * <p>The number of concurrent executions available to functions that do not have * concurrency limits set. For more information, see * <a>concurrent-executions</a>.</p> */ inline int GetUnreservedConcurrentExecutions() const{ return m_unreservedConcurrentExecutions; } /** * <p>The number of concurrent executions available to functions that do not have * concurrency limits set. For more information, see * <a>concurrent-executions</a>.</p> */ inline void SetUnreservedConcurrentExecutions(int value) { m_unreservedConcurrentExecutionsHasBeenSet = true; m_unreservedConcurrentExecutions = value; } /** * <p>The number of concurrent executions available to functions that do not have * concurrency limits set. For more information, see * <a>concurrent-executions</a>.</p> */ inline AccountLimit& WithUnreservedConcurrentExecutions(int value) { SetUnreservedConcurrentExecutions(value); return *this;} private: long long m_totalCodeSize; bool m_totalCodeSizeHasBeenSet; long long m_codeSizeUnzipped; bool m_codeSizeUnzippedHasBeenSet; long long m_codeSizeZipped; bool m_codeSizeZippedHasBeenSet; int m_concurrentExecutions; bool m_concurrentExecutionsHasBeenSet; int m_unreservedConcurrentExecutions; bool m_unreservedConcurrentExecutionsHasBeenSet; }; } // namespace Model } // namespace Lambda } // namespace Aws
37.52514
157
0.704035
[ "model" ]
2c043861e4944a58e7dff3366274b9bfec633678
7,386
h
C
cdb/include/tencentcloud/cdb/v20170320/model/Address.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
cdb/include/tencentcloud/cdb/v20170320/model/Address.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
cdb/include/tencentcloud/cdb/v20170320/model/Address.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "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_CDB_V20170320_MODEL_ADDRESS_H_ #define TENCENTCLOUD_CDB_V20170320_MODEL_ADDRESS_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cdb { namespace V20170320 { namespace Model { /** * Address */ class Address : public AbstractModel { public: Address(); ~Address() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取Address Note: this field may return `null`, indicating that no valid value can be found. * @return Vip Address Note: this field may return `null`, indicating that no valid value can be found. */ std::string GetVip() const; /** * 设置Address Note: this field may return `null`, indicating that no valid value can be found. * @param Vip Address Note: this field may return `null`, indicating that no valid value can be found. */ void SetVip(const std::string& _vip); /** * 判断参数 Vip 是否已赋值 * @return Vip 是否已赋值 */ bool VipHasBeenSet() const; /** * 获取Port Note: this field may return `null`, indicating that no valid value can be found. * @return VPort Port Note: this field may return `null`, indicating that no valid value can be found. */ uint64_t GetVPort() const; /** * 设置Port Note: this field may return `null`, indicating that no valid value can be found. * @param VPort Port Note: this field may return `null`, indicating that no valid value can be found. */ void SetVPort(const uint64_t& _vPort); /** * 判断参数 VPort 是否已赋值 * @return VPort 是否已赋值 */ bool VPortHasBeenSet() const; /** * 获取VPC ID Note: this field may return `null`, indicating that no valid value can be found. * @return UniqVpcId VPC ID Note: this field may return `null`, indicating that no valid value can be found. */ std::string GetUniqVpcId() const; /** * 设置VPC ID Note: this field may return `null`, indicating that no valid value can be found. * @param UniqVpcId VPC ID Note: this field may return `null`, indicating that no valid value can be found. */ void SetUniqVpcId(const std::string& _uniqVpcId); /** * 判断参数 UniqVpcId 是否已赋值 * @return UniqVpcId 是否已赋值 */ bool UniqVpcIdHasBeenSet() const; /** * 获取VPC subnet ID Note: this field may return `null`, indicating that no valid value can be found. * @return UniqSubnet VPC subnet ID Note: this field may return `null`, indicating that no valid value can be found. */ std::string GetUniqSubnet() const; /** * 设置VPC subnet ID Note: this field may return `null`, indicating that no valid value can be found. * @param UniqSubnet VPC subnet ID Note: this field may return `null`, indicating that no valid value can be found. */ void SetUniqSubnet(const std::string& _uniqSubnet); /** * 判断参数 UniqSubnet 是否已赋值 * @return UniqSubnet 是否已赋值 */ bool UniqSubnetHasBeenSet() const; /** * 获取Description Note: this field may return `null`, indicating that no valid value can be found. * @return Desc Description Note: this field may return `null`, indicating that no valid value can be found. */ std::string GetDesc() const; /** * 设置Description Note: this field may return `null`, indicating that no valid value can be found. * @param Desc Description Note: this field may return `null`, indicating that no valid value can be found. */ void SetDesc(const std::string& _desc); /** * 判断参数 Desc 是否已赋值 * @return Desc 是否已赋值 */ bool DescHasBeenSet() const; private: /** * Address Note: this field may return `null`, indicating that no valid value can be found. */ std::string m_vip; bool m_vipHasBeenSet; /** * Port Note: this field may return `null`, indicating that no valid value can be found. */ uint64_t m_vPort; bool m_vPortHasBeenSet; /** * VPC ID Note: this field may return `null`, indicating that no valid value can be found. */ std::string m_uniqVpcId; bool m_uniqVpcIdHasBeenSet; /** * VPC subnet ID Note: this field may return `null`, indicating that no valid value can be found. */ std::string m_uniqSubnet; bool m_uniqSubnetHasBeenSet; /** * Description Note: this field may return `null`, indicating that no valid value can be found. */ std::string m_desc; bool m_descHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CDB_V20170320_MODEL_ADDRESS_H_
36.384236
116
0.508394
[ "vector", "model" ]
2c0a43b10dcb0bbe6e2baededc672dc3f04f745b
9,789
c
C
library/src/Nucleus/Object/Signals.c
michaelheilmann/nucleus-object
0bf644d31f0d81f4e4cc0761030f5ee0621c064b
[ "MIT" ]
null
null
null
library/src/Nucleus/Object/Signals.c
michaelheilmann/nucleus-object
0bf644d31f0d81f4e4cc0761030f5ee0621c064b
[ "MIT" ]
null
null
null
library/src/Nucleus/Object/Signals.c
michaelheilmann/nucleus-object
0bf644d31f0d81f4e4cc0761030f5ee0621c064b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Michael Heilmann #include "Nucleus/Object/Signals-private.c.i" #include "Nucleus/Object/ImmutableString.h" #if defined (Nucleus_WithSignals) && 1 == Nucleus_WithSignals DEFINE_MODULE(Nucleus_Signals) Nucleus_Object_Library_Export Nucleus_NonNull() Nucleus_Status Nucleus_Signals_addSignal ( const char *name, Nucleus_Type *type ) { Nucleus_Status status; Nucleus_ImmutableString *name1; // status = Nucleus_ImmutableString_create(&name1, name, strlen(name)); if (Nucleus_Unlikely(status)) return status; // status = addSignal(name1, type); Nucleus_ImmutableString_unlock(name1); // return status; } Nucleus_Object_Library_Export Nucleus_NonNull() Nucleus_Status Nucleus_Signals_removeAllSignals ( Nucleus_Type *type ) { Nucleus_Status status; Nucleus_Collections_PointerHashMap_Enumerator e; status = Nucleus_Collections_PointerHashMap_Enumerator_initialize(&e, &g_singleton->signals); if (Nucleus_Unlikely(status)) { return status; } while (Nucleus_Boolean_True) { Nucleus_Boolean hasValue; // status = Nucleus_Collections_PointerHashMap_Enumerator_hasValue(&e, &hasValue); if (Nucleus_Unlikely(status)) { Nucleus_Collections_PointerHashMap_Enumerator_uninitialize(&e); return status; } // if (!hasValue) { break; } // void *k, *v; status = Nucleus_Collections_PointerHashMap_Enumerator_getValue(&e, &k, &v); if (Nucleus_Unlikely(status)) { Nucleus_Collections_PointerHashMap_Enumerator_uninitialize(&e); return status; } // if (((Nucleus_Signal *)v)->type == type) { status = Nucleus_Collections_PointerHashMap_Enumerator_remove(&e); if (Nucleus_Unlikely(status)) { Nucleus_Collections_PointerHashMap_Enumerator_uninitialize(&e); return status; } } else { status = Nucleus_Collections_PointerHashMap_Enumerator_next(&e); if (Nucleus_Unlikely(status)) { Nucleus_Collections_PointerHashMap_Enumerator_uninitialize(&e); return status; } } } Nucleus_Collections_PointerHashMap_Enumerator_uninitialize(&e); return Nucleus_Status_Success; } // Nucleus_Status_NotExists if the signal does not exist. Nucleus_NonNull() Nucleus_Status lookupSignal ( Nucleus_Signal **signal, Nucleus_Object *source, const char *name ) { Nucleus_Status status; // Get the type of the source. Nucleus_Type *type = source->type; // Get the signal name as an immutable string. Nucleus_ImmutableString *nameImmutableString; status = Nucleus_ImmutableString_create(&nameImmutableString, name, strlen(name)); if (Nucleus_Unlikely(status)) return status; // Get the signal by its name. Nucleus_Signal *temporary; status = lookupInClasses(&temporary, nameImmutableString, type); Nucleus_ImmutableString_unlock(nameImmutableString); if (Nucleus_Unlikely(status)) { return status; } *signal = temporary; return Nucleus_Status_Success; } Nucleus_Object_Library_Export Nucleus_NonNull(1, 2, 4) Nucleus_Status Nucleus_Signals_connect ( Nucleus_Object *object, const char *name, Nucleus_Object *sink, Nucleus_Callback *callback ) { // Get the signal. Nucleus_Signal *signal; Nucleus_Status status = lookupSignal(&signal, object, name); if (Nucleus_Unlikely(status)) return status; // Get or create the connections for the object. Connections *connections = NULL; status = Nucleus_Collections_PointerHashMap_get(&g_singleton->connections, object, (void **)&connections); if (Nucleus_Unlikely(status)) { if (Nucleus_Status_NotExists == status) { status = Connections_create(&connections); if (Nucleus_Unlikely(status)) return status; status = Nucleus_Collections_PointerHashMap_set(&g_singleton->connections, object, connections, Nucleus_Boolean_False); if (Nucleus_Unlikely(status)) { Connections_destroy(connections); return status; } } else { return status; } } // Add the connection to the connections of the object. Connection *connection = NULL; status = Connection_create(&connection, signal, sink, callback); if (Nucleus_Unlikely(status)) { return status; } connection->next = connections->connections; connections->connections = connection; // Return success. return Nucleus_Status_Success; } Nucleus_Object_Library_Export Nucleus_NonNull(1, 2) Nucleus_Status Nucleus_Signals_getNumberOfConnections ( Nucleus_Object *source, Nucleus_Size *count ) { // Get the connections of the source. Connections *connections = NULL; Nucleus_Status status; status = Nucleus_Collections_PointerHashMap_get(&g_singleton->connections, source, (void **)&connections); // If there are not connections for the source, we are done. if (status == Nucleus_Status_NotExists) { *count = 0; return Nucleus_Status_Success; } // There are connections for the source. Count the connections. Nucleus_Size i = 0; Connection *current = connections->connections; while (current) { i++; current = current->next; } *count = i; return Nucleus_Status_Success; } Nucleus_Object_Library_Export Nucleus_NonNull(1, 2, 4) Nucleus_Status Nucleus_Signals_disconnect ( Nucleus_Object *source, const char *name, Nucleus_Object *sink, Nucleus_Callback *callback ) { // Get the connections of the source. Connections *connections = NULL; Nucleus_Status status; status = Nucleus_Collections_PointerHashMap_get(&g_singleton->connections, source, (void **)&connections); // If there are not connections for the source, we are done. if (status == Nucleus_Status_NotExists) return Nucleus_Status_Success; // Get the signal. Nucleus_Signal *signal; status = lookupSignal(&signal, source, name); if (Nucleus_Unlikely(status)) return status; // There are connections for the source: Search and remove the connection. Connection **previous = &(connections->connections), *current = connections->connections; while (current) { if (current->sink == sink && current->signal == signal && current->callback == callback) { *previous = current->next; current->next = NULL; Connection_destroy(current); break; } else { previous = &current->next; current = current->next; } } // Return success. return Nucleus_Status_Success; } Nucleus_Object_Library_Export Nucleus_NonNull(1) Nucleus_Status Nucleus_Signals_disconnectAll ( Nucleus_Object *source ) { // Get the connections of the source. Connections *connections = NULL; Nucleus_Status status; status = Nucleus_Collections_PointerHashMap_get(&g_singleton->connections, source, (void **)&connections); // If there are not connections for the source, we are done. if (status == Nucleus_Status_NotExists) return Nucleus_Status_Success; // If there are connections, remove them. // TODO: Add and utilize Connections_clear(). while (connections->connections) { Connection *connection = connections->connections; connections->connections = connection->next; Connection_destroy(connection); } Nucleus_Collections_PointerHashMap_remove(&g_singleton->connections, source); // Return success. return Nucleus_Status_Success; } #if !defined(Nucleus_Cast) #define Nucleus_Cast(T, E) ((T)(E)) #endif typedef Nucleus_Status (Nucleus_SignalFunction)(Nucleus_Object *self, Nucleus_Object *source, Nucleus_Object *arguments); Nucleus_Object_Library_Export Nucleus_NonNull(1, 2) Nucleus_Status Nucleus_Signal_invoke ( Nucleus_Object *source, const char *name, Nucleus_Object *arguments ) { // Get the connections of the source. Connections *connections = NULL; Nucleus_Status status; status = Nucleus_Collections_PointerHashMap_get(&g_singleton->connections, source, (void **)&connections); // If there are not connections for the source, we are done. if (status == Nucleus_Status_NotExists) return Nucleus_Status_Success; // Get the signal. Nucleus_Signal *signal; status = lookupSignal(&signal, source, name); if (Nucleus_Unlikely(status)) return status; // There are connections for the source: Search and remove the connection. Connection *current = connections->connections; while (current) { if (current->signal == signal && current->callback) { status = Nucleus_Cast(Nucleus_SignalFunction *, current->callback) (current->sink, source, arguments); if (Nucleus_Unlikely(status)) return status; } current = current->next; } return Nucleus_Status_Success; } #endif
32.200658
122
0.645623
[ "object" ]
2c0abff590800aefb759246fed291dac2a34c865
1,260
h
C
neurox/tools/linear/vector.h
BlueBrain/neurox
ff7089e5f1e86176280ff5fabc73cf52d7edcd02
[ "BSD-3-Clause" ]
2
2019-07-28T21:53:21.000Z
2019-07-30T21:30:13.000Z
neurox/tools/linear/vector.h
BlueBrain/neurox
ff7089e5f1e86176280ff5fabc73cf52d7edcd02
[ "BSD-3-Clause" ]
null
null
null
neurox/tools/linear/vector.h
BlueBrain/neurox
ff7089e5f1e86176280ff5fabc73cf52d7edcd02
[ "BSD-3-Clause" ]
2
2019-07-28T19:51:12.000Z
2021-07-28T05:09:10.000Z
/* # ============================================================================= # Copyright (c) 2015 - 2021 Blue Brain Project/EPFL # # See top-level LICENSE file for details. # =============================================================================. */ #pragma once #include <vector> namespace neurox { namespace tools { namespace linear { /** * @brief The Linear Vector class */ template <class Val> class Vector { public: Vector() = delete; Vector(std::vector<Val*> data, unsigned char* buffer) { // needs to be called with placement-new where buffer* // is the start of the data structure assert((void*)buffer == this); n_ = data.size(); size_t offset = sizeof(Vector<Val>); data_ = (Val*)&(buffer[offset]); for (int i = 0; i < data.size(); i++) memcpy(&data_[i], data[i], sizeof(Val)); assert(offset + n_ * sizeof(Val) == Size(n_)); } ~Vector() { delete[] data_; } static size_t Size(size_t n) { return sizeof(Vector<Val>) + sizeof(Val) * n; } inline Val* At(size_t i) { assert(i < n_); return &data_[i]; } inline size_t Count() { return n_; } private: size_t n_; Val* data_; }; // class Vector }; // namespace linear }; // namespace tools }; // namespace neurox
23.333333
80
0.539683
[ "vector" ]
2c0ba1988ddb22b6e4a4dd9a26497f005894f825
13,535
h
C
CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h
merdahl/avs-device-sdk
2cc16d8cc472afc9b7a736a8c1169f12b71dd229
[ "Apache-2.0" ]
1
2022-01-09T21:26:04.000Z
2022-01-09T21:26:04.000Z
CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h
justdoGIT/avs-device-sdk
2cc16d8cc472afc9b7a736a8c1169f12b71dd229
[ "Apache-2.0" ]
null
null
null
CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h
justdoGIT/avs-device-sdk
2cc16d8cc472afc9b7a736a8c1169f12b71dd229
[ "Apache-2.0" ]
1
2018-10-12T07:58:44.000Z
2018-10-12T07:58:44.000Z
/* * SpeakerManager.h * * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef ALEXACLIENTSDK_CAPABILITY_AGENTS_SPEAKER_MANAGER_INCLUDE_SPEAKER_MANAGER_SPEAKER_MANAGER_H_ #define ALEXACLIENTSDK_CAPABILITY_AGENTS_SPEAKER_MANAGER_INCLUDE_SPEAKER_MANAGER_SPEAKER_MANAGER_H_ #include <future> #include <map> #include <memory> #include <unordered_set> #include <vector> #include <AVSCommon/AVS/AVSDirective.h> #include <AVSCommon/AVS/CapabilityAgent.h> #include <AVSCommon/SDKInterfaces/ContextManagerInterface.h> #include <AVSCommon/SDKInterfaces/MessageSenderInterface.h> #include <AVSCommon/SDKInterfaces/SpeakerInterface.h> #include <AVSCommon/SDKInterfaces/SpeakerManagerInterface.h> #include <AVSCommon/SDKInterfaces/SpeakerManagerObserverInterface.h> #include <AVSCommon/Utils/RequiresShutdown.h> #include <AVSCommon/Utils/Threading/Executor.h> namespace alexaClientSDK { namespace capabilityAgents { namespace speakerManager { /** * This class implementes a @c CapabilityAgent that handles the AVS @c Speaker API. * * The @c SpeakerManager can handle multiple @c SpeakerInterface objects. @c SpeakerInterface * are grouped by their respective types, and the volume and mute state will be consistent * across each type. For example, to change the volume of all speakers of a specific type: * * @code{.cpp} * // Use local setVolume API. * std::future<bool> result = speakerManager->setVolume(type, AVS_SET_VOLUME_MAX); * // Optionally, wait for the operation to complete. * if (result.valid()) { * result.wait(); * } * @endcode * * AVS documentation specifies that Alerts volume should be handled separately. * Currently, the AVS API does not support differentiating between different speakers. * To provide clients an option to handle Alerts (and any other) volumes independently, * only @c SpeakerInterface::Type::AVS_SYNCED speakers will communicate with AVS. * * A default type, @c SpeakerInterface::Type::LOCAL, is provided. This type will not be modified by directives sent by * AVS, nor will they send events on volume/mute change. These @c SpeakerInterfaces can still be modified through the * APIs that @c SpeakerManagerInterface provides. Clients may extend the @c SpeakerInterface::Type enum if multiple * independent volume controls are needed. * * If clients wish directives and events to apply to the specific @c SpeakerInterface, it must * have a type of @c SpeakerInterface::Type::AVS_SYNCED. */ class SpeakerManager : public avsCommon::avs::CapabilityAgent , public avsCommon::sdkInterfaces::SpeakerManagerInterface , public avsCommon::utils::RequiresShutdown { public: /** * Create an instance of @c SpeakerManager, and register the @c SpeakerInterfaces that will be controlled * by it. SpeakerInterfaces will be grouped by @c SpeakerInterface::Type. * * @param speakers The @c Speakers to register. * @param contextManager A @c ContextManagerInterface to manage the context. * @param messageSender A @c MessageSenderInterface to send messages to AVS. * @param exceptionEncounteredSender An @c ExceptionEncounteredSenderInterface to send * directive processing exceptions to AVS. */ static std::shared_ptr<SpeakerManager> create( const std::vector<std::shared_ptr<avsCommon::sdkInterfaces::SpeakerInterface>>& speakers, std::shared_ptr<avsCommon::sdkInterfaces::ContextManagerInterface> contextManager, std::shared_ptr<avsCommon::sdkInterfaces::MessageSenderInterface> messageSender, std::shared_ptr<avsCommon::sdkInterfaces::ExceptionEncounteredSenderInterface> exceptionEncounteredSender); /// @name CapabilityAgent Functions /// @{ avsCommon::avs::DirectiveHandlerConfiguration getConfiguration() const override; void handleDirectiveImmediately(std::shared_ptr<avsCommon::avs::AVSDirective> directive) override; void preHandleDirective(std::shared_ptr<avsCommon::avs::CapabilityAgent::DirectiveInfo> info) override; void handleDirective(std::shared_ptr<avsCommon::avs::CapabilityAgent::DirectiveInfo> info) override; void cancelDirective(std::shared_ptr<avsCommon::avs::CapabilityAgent::DirectiveInfo> info) override; void provideState(const unsigned int stateRequestToken) override; /// @} // @name RequiresShutdown Functions /// @{ void doShutdown() override; /// @} // @name SpeakerManagerInterface Functions /// @{ std::future<bool> setVolume( avsCommon::sdkInterfaces::SpeakerInterface::Type type, int8_t volume, bool forceNoNotifications = false) override; std::future<bool> adjustVolume( avsCommon::sdkInterfaces::SpeakerInterface::Type type, int8_t delta, bool forceNoNotifications = false) override; std::future<bool> setMute( avsCommon::sdkInterfaces::SpeakerInterface::Type type, bool mute, bool forceNoNotifications = false) override; std::future<bool> getSpeakerSettings( avsCommon::sdkInterfaces::SpeakerInterface::Type type, avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* settings) override; void addSpeakerManagerObserver( std::shared_ptr<avsCommon::sdkInterfaces::SpeakerManagerObserverInterface> observer) override; void removeSpeakerManagerObserver( std::shared_ptr<avsCommon::sdkInterfaces::SpeakerManagerObserverInterface> observer) override; /// @} private: /** * Constructor. Called after validation has occurred on parameters. * * @param speakers The @c Speakers to register. * @param contextManager A @c ContextManagerInterface to manage the context. * @param messageSender A @c MessageSenderInterface to send messages to AVS. * @param exceptionEncounteredSender An @c ExceptionEncounteredSenderInterface to send * directive processing exceptions to AVS. */ SpeakerManager( const std::vector<std::shared_ptr<avsCommon::sdkInterfaces::SpeakerInterface>>& speakerInterfaces, std::shared_ptr<avsCommon::sdkInterfaces::ContextManagerInterface> contextManager, std::shared_ptr<avsCommon::sdkInterfaces::MessageSenderInterface> messageSender, std::shared_ptr<avsCommon::sdkInterfaces::ExceptionEncounteredSenderInterface> exceptionEncounteredSender); /** * Parses the payload from a string into a rapidjson document. * * @param payload The payload as a string. * @param document The document that will contain the payload. * @return A bool indicating the results of the operation. */ bool parseDirectivePayload(std::string payload, rapidjson::Document* document); /** * Performs clean-up after a successful handling of a directive. * * @param info The current directive being processed. */ void executeSetHandlingCompleted(std::shared_ptr<DirectiveInfo> info); /** * Removes the directive after it's been processed. * * @param info The current directive being processed. */ void removeDirective(std::shared_ptr<DirectiveInfo> info); /** * Sends an exception to AVS. * * @param info The current directive being processed. * @param message The exception message. * @param type The type of exception. */ void sendExceptionEncountered( std::shared_ptr<CapabilityAgent::DirectiveInfo> info, const std::string& message, avsCommon::avs::ExceptionErrorType type); /** * Internal function to provide the state (Context). This runs on a worker thread. * * @param stateRequestToken A token representing the request. */ void executeProvideState(unsigned int stateRequestToken); /** * Sends <Volume/Mute>Changed events to AVS. The events are identical except for the name. * * @param eventName The name of the event. * @param settings The current speaker settings. */ void executeSendSpeakerSettingsChangedEvent( const std::string& eventName, avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings settings); /** * Internal function to set the volume for a specific @c Type. This runs on a worker thread. * Upon success, a VolumeChanged event will be sent to AVS. * * @param type The type of speaker to modify volume for. * @param volume The volume to change. * @param source Whether the call is from AVS or locally. * @param forceNoNotifications This flag will ensure no event is sent and the observer is not notified. * @return A bool indicating success. */ bool executeSetVolume( avsCommon::sdkInterfaces::SpeakerInterface::Type type, int8_t volume, avsCommon::sdkInterfaces::SpeakerManagerObserverInterface::Source source, bool forceNoNotifications = false); /** * Internal function to adjust the volume for a specific @c Type. This runs on a worker thread. * Upon success, a VolumeChanged event will be sent to AVS. * * @param type The type of speaker to modify volume for. * @param delta The delta to change the volume by. * @param source Whether the call is from AVS or locally. * @param forceNoNotifications This flag will ensure no event is sent and the observer is not notified. * @return A bool indicating success. */ bool executeAdjustVolume( avsCommon::sdkInterfaces::SpeakerInterface::Type type, int8_t delta, avsCommon::sdkInterfaces::SpeakerManagerObserverInterface::Source source, bool forceNoNotifications = false); /** * Internal function to set the mute for a specific @c Type. This runs on a worker thread. * Upon success, a MuteChanged event will be sent to AVS. * * @param type The type of speaker to modify mute for. * @param mute Whether to mute/unmute. * @param source Whether the call is from AVS or locally. * @param forceNoNotifications This flag will ensure no event is sent and the observer is not notified. * @return A bool indicating success. */ bool executeSetMute( avsCommon::sdkInterfaces::SpeakerInterface::Type type, bool mute, avsCommon::sdkInterfaces::SpeakerManagerObserverInterface::Source source, bool forceNoNotifications = false); /** * Internal function to get the speaker settings for a specific @c Type. * This runs on a worker thread. * * @param type The type of speaker to modify mute for. * @param[out] settings The settings if successful. * @return A bool indicating success. */ bool executeGetSpeakerSettings( avsCommon::sdkInterfaces::SpeakerInterface::Type type, avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* settings); /** * Internal function to notify the observer when a @c SpeakerSettings change has occurred. * * @param source. This indicates the origin of the call. * @param type. This indicates the type of speaker that was modified. * @param settings. This indicates the current settings after the change. */ void executeNotifyObserver( const avsCommon::sdkInterfaces::SpeakerManagerObserverInterface::Source& source, const avsCommon::sdkInterfaces::SpeakerInterface::Type& type, const avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings& settings); /** * Validates that all speakers with the given @c Type have the same @c SpeakerSettings. * * @param type The type of speaker to validate. * @param[out] settings The settings that will be return if consistent. * @return A bool indicating success. */ bool validateSpeakerSettingsConsistency( avsCommon::sdkInterfaces::SpeakerInterface::Type type, avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* settings); /// The @c ContextManager used to generate system context for events. std::shared_ptr<avsCommon::sdkInterfaces::ContextManagerInterface> m_contextManager; /// The @c MessageSenderInterface used to send event messages. std::shared_ptr<avsCommon::sdkInterfaces::MessageSenderInterface> m_messageSender; /// A multimap contain speakers keyed by @c Type. std::multimap< avsCommon::sdkInterfaces::SpeakerInterface::Type, std::shared_ptr<avsCommon::sdkInterfaces::SpeakerInterface>> m_speakerMap; /// The observers to be notified whenever any of the @c SpeakerSetting changing APIs are called. std::unordered_set<std::shared_ptr<avsCommon::sdkInterfaces::SpeakerManagerObserverInterface>> m_observers; /// An executor to perform operations on a worker thread. avsCommon::utils::threading::Executor m_executor; }; } // namespace speakerManager } // namespace capabilityAgents } // namespace alexaClientSDK #endif // ALEXACLIENTSDK_CAPABILITY_AGENTS_SPEAKER_MANAGER_INCLUDE_SPEAKER_MANAGER_SPEAKER_MANAGER_H_
44.669967
118
0.727152
[ "vector" ]
2c10780744eaa7e15559678a0b954837b24d57f7
388
h
C
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter10_classrelationships/ch10_trackcoach/ch10time.h
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter10_classrelationships/ch10_trackcoach/ch10time.h
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/johnstonc_programmingtoday_sourcecode/chapter10_classrelationships/ch10_trackcoach/ch10time.h
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
// Program 10-5 TrackCoach has a stopwatch, which uses a masterclock //File: Ch10Time.h #ifndef _TIME_H #define _TIME_H class Time { private: int hr, min, sec; public: Time(); //sets the time object to 0:0:1 void Reset(int h, int m, int s); // resets time to h:m:s void ShowTime(); Time operator -(Time N); // need to be able to subtract times }; #endif
19.4
70
0.641753
[ "object" ]
2c145414d62fc172c129d3e7a6f2b0d1e241502e
549
h
C
day23/puzzle.h
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
20
2021-12-04T04:53:22.000Z
2022-02-24T23:37:31.000Z
day23/puzzle.h
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
null
null
null
day23/puzzle.h
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
1
2022-01-04T22:12:05.000Z
2022-01-04T22:12:05.000Z
#ifndef PUZZLE_H_ #define PUZZLE_H_ #include "room.h" #include <iosfwd> #include <limits> #include <optional> #include <vector> struct Puzzle { std::vector<char> hallway; std::vector<Room> rooms; size_t greedy_move_to_room(); size_t greedy_room_to_room(); std::optional<size_t> hallway_move(size_t home, size_t pos); size_t occupied_spaces_between(size_t from, size_t to) const; bool solved() const; friend std::ostream &operator<<(std::ostream &, const Puzzle &); }; std::optional<size_t> find_shortest(Puzzle puzzle); #endif
21.115385
66
0.734062
[ "vector" ]
2c1592b4e62f7f459b5ef038ea8f391cb50ea192
1,200
h
C
all/native/renderers/drawdatas/PointDrawData.h
mostafa-j13/mobile-sdk
60d51e4d37c7fb9558b1310345083c7f7d6b79e7
[ "BSD-3-Clause" ]
null
null
null
all/native/renderers/drawdatas/PointDrawData.h
mostafa-j13/mobile-sdk
60d51e4d37c7fb9558b1310345083c7f7d6b79e7
[ "BSD-3-Clause" ]
null
null
null
all/native/renderers/drawdatas/PointDrawData.h
mostafa-j13/mobile-sdk
60d51e4d37c7fb9558b1310345083c7f7d6b79e7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_POINTDRAWDATA_H_ #define _CARTO_POINTDRAWDATA_H_ #include "renderers/drawdatas/VectorElementDrawData.h" #include <memory> #include <cglib/vec.h> namespace carto { class Bitmap; class PointGeometry; class PointStyle; class Projection; class PointDrawData : public VectorElementDrawData { public: PointDrawData(const PointGeometry& geometry, const PointStyle& style, const Projection& projection); virtual ~PointDrawData(); const std::shared_ptr<Bitmap> getBitmap() const; float getClickScale() const; const cglib::vec3<double>& getPos() const; float getSize() const; virtual void offsetHorizontally(double offset); private: static const int IDEAL_CLICK_SIZE = 64; static const float CLICK_SIZE_COEF; std::shared_ptr<Bitmap> _bitmap; float _clickScale; cglib::vec3<double> _pos; float _size; }; } #endif
22.222222
108
0.653333
[ "geometry" ]
2c175646947079020dc921a3078ba09b79a73ea7
54,385
c
C
core/connection/ble/src/softbus_ble_connection.c
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
2
2021-11-22T15:58:06.000Z
2021-12-03T13:57:01.000Z
core/connection/ble/src/softbus_ble_connection.c
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
null
null
null
core/connection/ble/src/softbus_ble_connection.c
openharmony-gitee-mirror/communication_dsoftbus
afae96a6c8674d6ac7de307fccfa2dd205e5bcf6
[ "Apache-2.0" ]
4
2021-09-13T11:17:56.000Z
2022-03-31T01:28:33.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. */ #include <pthread.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include <sys/prctl.h> #include <time.h> #include "bus_center_manager.h" #include "cJSON.h" #include "common_list.h" #include "message_handler.h" #include "securec.h" #include "softbus_adapter_ble_gatt_server.h" #include "softbus_adapter_mem.h" #include "softbus_ble_trans_manager.h" #include "softbus_conn_manager.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_json_utils.h" #include "softbus_log.h" #include "softbus_queue.h" #include "softbus_type_def.h" #include "softbus_utils.h" #define SEND_QUEUE_UNIT_NUM 128 #define CONNECT_REF_INCRESE 1 #define CONNECT_REF_DECRESE (-1) #define METHOD_NOTIFY_REQUEST 1 #define METHOD_NOTIFY_RESPONSE 2 #define METHOD_SHUT_DOWN 3 #define CONN_MAGIC_NUMBER 0xBABEFACE #define KEY_METHOD "KEY_METHOD" #define KEY_DELTA "KEY_DELTA" #define KEY_REFERENCE_NUM "KEY_REFERENCE_NUM" #define TYPE_HEADER_SIZE 4 #define SOFTBUS_SERVICE_UUID "11C8B310-80E4-4276-AFC0-F81590B2177F" #define SOFTBUS_CHARA_BLENET_UUID "00002B00-0000-1000-8000-00805F9B34FB" #define SOFTBUS_CHARA_BLECONN_UUID "00002B01-0000-1000-8000-00805F9B34FB" #define SOFTBUS_DESCRIPTOR_CONFIGURE_UUID "00002902-0000-1000-8000-00805F9B34FB" typedef enum { BLE_GATT_SERVICE_INITIAL = 0, BLE_GATT_SERVICE_ADDING, BLE_GATT_SERVICE_ADDED, BLE_GATT_SERVICE_STARTING, BLE_GATT_SERVICE_STARTED, BLE_GATT_SERVICE_STOPPING, BLE_GATT_SERVICE_DELETING, BLE_GATT_SERVICE_INVALID } GattServiceState; typedef struct { GattServiceState state; int32_t svcId; int32_t bleConnCharaId; int32_t bleConnDesId; int32_t bleNetCharaId; int32_t bleNetDesId; } SoftBusGattService; typedef enum { BLE_CONNECTION_STATE_CONNECTING = 0, BLE_CONNECTION_STATE_CONNECTED, BLE_CONNECTION_STATE_BASIC_INFO_EXCHANGED, BLE_CONNECTION_STATE_CLOSING, BLE_CONNECTION_STATE_CLOSED } BleConnectionState; typedef enum { ADD_SERVICE_MSG, ADD_CHARA_MSG, ADD_DESCRIPTOR_MSG, } BleConnLoopMsg; typedef struct { pthread_mutex_t lock; pthread_cond_t cond; LockFreeQueue *queue; } BleQueue; typedef struct { uint32_t halConnId; uint32_t connectionId; int32_t pid; int32_t flag; int32_t isServer; int32_t isInner; int32_t module; int32_t seq; int32_t len; const char *data; } SendQueueNode; typedef enum { TYPE_UNKNOW = -1, TYPE_AUTH = 0, TYPE_BASIC_INFO = 1, TYPE_DEV_INFO = 2, } BleNetMsgType; typedef struct { int32_t type; } BleBasicInfo; static const int MAX_SERVICE_CHAR_NUM = 8; static const int BLE_GATT_ATT_MTU_DEFAULT = 23; static const int BLE_GATT_ATT_MTU_DEFAULT_PAYLOAD = 21; static const int MTU_HEADER_SIZE = 3; static const int BLE_GATT_ATT_MTU_MAX = 512; static const int BLE_ROLE_CLIENT = 1; static const int BLE_ROLE_SERVER = 2; static LIST_HEAD(g_conection_list); static ConnectCallback *g_connectCallback = NULL; static SoftBusHandler g_bleAsyncHandler = { .name ="g_bleAsyncHandler" }; static ConnectFuncInterface g_bleInterface = { 0 }; static SoftBusGattsCallback g_bleGattsCallback = { 0 }; static pthread_mutex_t g_connectionLock; static SoftBusGattService g_gattService = { .state = BLE_GATT_SERVICE_INITIAL, .svcId = -1, .bleConnCharaId = -1, .bleConnDesId = -1, .bleNetCharaId = -1, .bleNetDesId = -1 }; static BleQueue g_sendQueue; static SoftBusMessage *BleConnCreateLoopMsg(int32_t what, uint64_t arg1, uint64_t arg2, const char *data) { SoftBusMessage *msg = NULL; msg = SoftBusCalloc(sizeof(SoftBusMessage)); if (msg == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnCreateLoopMsg SoftBusCalloc failed"); return NULL; } msg->what = what; msg->arg1 = arg1; msg->arg2 = arg2; msg->handler = &g_bleAsyncHandler; msg->FreeMessage = NULL; msg->obj = (void *)data; return msg; } static int32_t AllocBleConnectionIdLocked() { static int16_t nextConnectionId = 0; uint32_t tempId; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return 0; } nextConnectionId++; while (1) { tempId = (CONNECT_BLE << CONNECT_TYPE_SHIFT) + nextConnectionId; ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == tempId) { nextConnectionId++; continue; } } break; } (void)pthread_mutex_unlock(&g_connectionLock); return tempId; } static BleConnectionInfo* CreateBleConnectionNode(void) { BleConnectionInfo *newConnectionInfo = SoftBusCalloc(sizeof(BleConnectionInfo)); if (newConnectionInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnectDeviceFristTime malloc fail.]"); return NULL; } ListInit(&newConnectionInfo->node); newConnectionInfo->connId = AllocBleConnectionIdLocked(); newConnectionInfo->mtu = BLE_GATT_ATT_MTU_DEFAULT_PAYLOAD; newConnectionInfo->refCount = 1; newConnectionInfo->info.isAvailable = 1; newConnectionInfo->info.type = CONNECT_BLE; return newConnectionInfo; } void DeleteBleConnectionNode(BleConnectionInfo* node) { if (node == NULL) { return; } node->state = BLE_CONNECTION_STATE_CLOSED; for (int i = 0; i < MAX_CACHE_NUM_PER_CONN; i++) { if (node->recvCache[i].cache != NULL) { SoftBusFree(node->recvCache[i].cache); } } SoftBusFree(node); } static BleConnectionInfo* GetBleConnInfoByConnId(uint32_t connectionId) { ListNode *item = NULL; BleConnectionInfo *itemNode = NULL; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return NULL; } LIST_FOR_EACH(item, &g_conection_list) { itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == connectionId) { break; } } (void)pthread_mutex_unlock(&g_connectionLock); return itemNode; } BleConnectionInfo* GetBleConnInfoByHalConnId(int32_t halConnectionId) { ListNode *item = NULL; BleConnectionInfo *itemNode = NULL; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return NULL; } LIST_FOR_EACH(item, &g_conection_list) { itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->halConnId == halConnectionId) { break; } } (void)pthread_mutex_unlock(&g_connectionLock); return itemNode; } static int32_t GetBleConnInfoByAddr(const char *strAddr, BleConnectionInfo **server, BleConnectionInfo **client) { ListNode *item = NULL; BleConnectionInfo *itemNode = NULL; bool findServer = false; bool findClient = false; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; } LIST_FOR_EACH(item, &g_conection_list) { itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (memcmp(itemNode->info.info.bleInfo.bleMac, strAddr, BT_MAC_LEN) == 0) { if (itemNode->info.isServer) { *server = itemNode; findServer = true; } else { *client = itemNode; findClient = true; } if (findServer && findClient) { break; } } } (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_OK; } int32_t GetBleAttrHandle(int32_t module) { return (module == MODULE_BLE_NET) ? g_gattService.bleNetCharaId : g_gattService.bleConnCharaId; } static int32_t BleConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ConnectDevice failed, reason:gatt client is not currently supported"); return SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT; } static int BleEnqueueNonBlock(const void *msg) { if (msg == NULL) { return SOFTBUS_ERR; } return QueueMultiProducerEnqueue(g_sendQueue.queue, msg); } static int BleDequeueBlock(void **msg) { if (msg == NULL) { return SOFTBUS_ERR; } (void)pthread_mutex_lock(&g_sendQueue.lock); if (QueueIsEmpty(g_sendQueue.queue) == 0) { pthread_cond_wait(&g_sendQueue.cond, &g_sendQueue.lock); (void)pthread_mutex_unlock(&g_sendQueue.lock); } return QueueSingleConsumerDequeue(g_sendQueue.queue, msg); } static int32_t BlePostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BlePostBytes connectionId=%u,pid=%d,len=%d flag=%d", connectionId, pid, len, flag); if (data == NULL) { return SOFTBUS_ERR; } BleConnectionInfo *connInfo = GetBleConnInfoByConnId(connectionId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes GetBleConnInfo failed"); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } SendQueueNode *node = SoftBusCalloc(sizeof(SendQueueNode)); if (node == NULL) { return SOFTBUS_MALLOC_ERR; } node->halConnId = connInfo->halConnId; node->connectionId = connectionId; node->isServer = connInfo->info.isServer; node->pid = pid; node->flag = flag; node->len = len; node->data = data; int ret = BleEnqueueNonBlock((const void *)node); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes enqueue failed"); return ret; } (void)pthread_mutex_lock(&g_sendQueue.lock); pthread_cond_signal(&g_sendQueue.cond); (void)pthread_mutex_unlock(&g_sendQueue.lock); return SOFTBUS_OK; } static int32_t BlePostBytesInner(uint32_t connectionId, ConnPostData *data) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BlePostBytesInner connectionId=%u", connectionId); if (data == NULL) { return SOFTBUS_ERR; } BleConnectionInfo *connInfo = GetBleConnInfoByConnId(connectionId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes GetBleConnInfo failed"); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } SendQueueNode *node = SoftBusCalloc(sizeof(SendQueueNode)); if (node == NULL) { return SOFTBUS_MALLOC_ERR; } node->halConnId = connInfo->halConnId; node->connectionId = connectionId; node->isServer = connInfo->info.isServer; node->len = data->len; node->data = data->buf; node->isInner = 1; node->module = data->module; node->isInner = data->seq; int ret = BleEnqueueNonBlock((const void *)node); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes enqueue failed"); return ret; } (void)pthread_mutex_lock(&g_sendQueue.lock); pthread_cond_signal(&g_sendQueue.cond); (void)pthread_mutex_unlock(&g_sendQueue.lock); return SOFTBUS_OK; } static int AddNumToJson(cJSON *json, int32_t requestOrResponse, int32_t delta, int32_t count) { if (requestOrResponse == METHOD_NOTIFY_REQUEST) { if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_REQUEST) || !AddNumberToJsonObject(json, KEY_DELTA, delta) || !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; } } else { if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_RESPONSE) || !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; } } return SOFTBUS_OK; } static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, int32_t requestOrResponse) { cJSON *json = cJSON_CreateObject(); if (json == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); return; } if (AddNumToJson(json, requestOrResponse, delta, count) != SOFTBUS_OK) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot AddNumToJson"); return; } char *data = cJSON_PrintUnformatted(json); cJSON_Delete(json); if (data == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "cJSON_PrintUnformatted failed"); return; } int32_t headSize = sizeof(ConnPktHead); int32_t dataLen = strlen(data) + 1 + headSize; char *buf = (char *)SoftBusCalloc(dataLen); if (buf == NULL) { cJSON_free(data); return; } ConnPktHead head; head.magic = CONN_MAGIC_NUMBER; head.module = MODULE_CONNECTION; head.seq = 1; head.flag = 0; head.len = strlen(data) + 1; if (memcpy_s(buf, dataLen, (void *)&head, headSize)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s head error"); cJSON_free(data); SoftBusFree(buf); return; } if (memcpy_s(buf + headSize, dataLen - headSize, data, strlen(data) + 1)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s data error"); cJSON_free(data); SoftBusFree(buf); return; } cJSON_free(data); (void)BlePostBytes(connectionId, buf, dataLen, 0, 0); return; } static void PackRequest(int32_t delta, uint32_t connectionId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onNotifyRequest: delta=%d, connectionIds=%u", delta, connectionId); ListNode *item = NULL; BleConnectionInfo *targetNode = NULL; int refCount; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == connectionId) { itemNode->refCount += delta; refCount = itemNode->refCount; targetNode = itemNode; break; } } (void)pthread_mutex_unlock(&g_connectionLock); if (targetNode == NULL) { return; } SendRefMessage(delta, connectionId, refCount, METHOD_NOTIFY_REQUEST); } static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onNotifyRequest: delta=%d, RemoteRef=%d, connectionIds=%u", delta, peerRef, connectionId); ListNode *item = NULL; BleConnectionInfo *targetNode = NULL; int myRefCount; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == connectionId) { targetNode = itemNode; targetNode->refCount += delta; myRefCount = targetNode->refCount; break; } } if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Not find OnPackResponse device"); (void)pthread_mutex_unlock(&g_connectionLock); return; } (void)pthread_mutex_unlock(&g_connectionLock); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onPackRequest: myRefCount=%d]", myRefCount); if (peerRef > 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[remote device Ref is > 0, do not reply]"); return; } if (myRefCount <= 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[local device Ref <= 0, close connection now]"); SoftBusGattsDisconnect(targetNode->btBinaryAddr, targetNode->halConnId); return; } SendRefMessage(delta, connectionId, myRefCount, METHOD_NOTIFY_RESPONSE); } static void RecvConnectedComd(uint32_t connectionId, const cJSON *data) { int32_t keyMethod = 0; int32_t keyDelta = 0; int32_t keyRefernceNum = 0; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RecvConnectedComd ID=%u", connectionId); if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod)) { return; } if (keyMethod == METHOD_NOTIFY_REQUEST) { if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || !GetJsonObjectNumberItem(data, KEY_DELTA, &keyDelta) || !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "REQUEST fail"); return; } OnPackResponse(keyDelta, keyRefernceNum, connectionId); } if (keyMethod == METHOD_NOTIFY_RESPONSE) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_RESPONSE"); if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RESPONSE fail"); return; } (void)pthread_mutex_lock(&g_connectionLock); ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == connectionId) { if (itemNode->state == BLE_CONNECTION_STATE_CLOSING) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_CHANGE"); itemNode->state = BLE_CONNECTION_STATE_CONNECTED; } break; } } (void)pthread_mutex_unlock(&g_connectionLock); } } static int32_t BleDisconnectDevice(uint32_t connectionId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice]"); BleConnectionInfo *connInfo = GetBleConnInfoByConnId(connectionId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectDevice GetBleConnInfo failed"); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } (void)PackRequest(CONNECT_REF_DECRESE, connectionId); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice over]"); return SOFTBUS_OK; } static int32_t BleDisconnectDeviceNow(const ConnectOption *option) { int32_t ret; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDeviceByOption]"); BleConnectionInfo *server = NULL; BleConnectionInfo *client = NULL; ret = GetBleConnInfoByAddr(option->info.bleOption.bleMac, &server, &client); if ((ret != SOFTBUS_OK) || ((server == NULL) && (client == NULL))) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectDevice GetBleConnInfo failed"); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } SoftBusBtAddr btAddr; if (server != NULL) { ret = ConvertBtMacToBinary((const char *)server->info.info.bleInfo.bleMac, BT_MAC_LEN, btAddr.addr, BT_ADDR_LEN); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr to binary failed:%d", ret); return ret; } ret = SoftBusGattsDisconnect(btAddr, server->halConnId); } else { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectDeviceNow failed, reason:gatt client not support"); return SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT; } return ret; } static int32_t BleGetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) { int32_t result = SOFTBUS_ERR; if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_ERR; } ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->connId == connectionId) { if (memcpy_s(info, sizeof(ConnectionInfo), &(itemNode->info), sizeof(ConnectionInfo)) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGetConnInfo scpy error"); (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } result = SOFTBUS_OK; break; } } (void)pthread_mutex_unlock(&g_connectionLock); return result; } static int32_t BleStartLocalListening(const LocalListenerInfo *info) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattsStartService enter"); if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; } if ((g_gattService.state == BLE_GATT_SERVICE_STARTED) || (g_gattService.state == BLE_GATT_SERVICE_STARTING)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleStartLocalListening service already started or is starting"); (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_OK; } if (g_gattService.state == BLE_GATT_SERVICE_ADDED) { g_gattService.state = BLE_GATT_SERVICE_STARTING; int ret = SoftBusGattsStartService(g_gattService.svcId); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattsStartService failed"); g_gattService.state = BLE_GATT_SERVICE_ADDED; } (void)pthread_mutex_unlock(&g_connectionLock); return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; } (void)pthread_mutex_unlock(&g_connectionLock); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleStartLocalListening wrong service state:%d", g_gattService.state); return SOFTBUS_ERR; } static int32_t BleStopLocalListening(const LocalListenerInfo *info) { if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; } if ((g_gattService.state == BLE_GATT_SERVICE_ADDED) || (g_gattService.state == BLE_GATT_SERVICE_STOPPING)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleStopLocalListening service already stopped or is stopping"); (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_OK; } if (g_gattService.state == BLE_GATT_SERVICE_STARTED) { g_gattService.state = BLE_GATT_SERVICE_STOPPING; int ret = SoftBusGattsStopService(g_gattService.svcId); if (ret != SOFTBUS_OK) { g_gattService.state = BLE_GATT_SERVICE_STARTED; } (void)pthread_mutex_unlock(&g_connectionLock); return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; } (void)pthread_mutex_unlock(&g_connectionLock); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleStopLocalListening wrong service state:%d", g_gattService.state); return SOFTBUS_ERR; } static void UpdateGattService(SoftBusGattService *service, int status) { if (service == NULL) { return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } switch (service->state) { case BLE_GATT_SERVICE_ADDING: if ((service->svcId != -1) && (service->bleConnCharaId != -1) && (service->bleNetCharaId != -1) && (service->bleConnDesId != -1) && (service->bleNetDesId != -1)) { service->state = BLE_GATT_SERVICE_ADDED; if (BleStartLocalListening(NULL) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleStartLocalListening failed"); } break; } if (service->svcId != -1) { service->state = BLE_GATT_SERVICE_DELETING; int ret = SoftBusGattsDeleteService(service->svcId); if (ret != SOFTBUS_OK) { service->state = BLE_GATT_SERVICE_INVALID; } } else { service->state = BLE_GATT_SERVICE_INITIAL; } break; case BLE_GATT_SERVICE_STARTING: service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_STARTED : BLE_GATT_SERVICE_ADDED; break; case BLE_GATT_SERVICE_STOPPING: service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_ADDED : BLE_GATT_SERVICE_STARTED; break; case BLE_GATT_SERVICE_DELETING: service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_INITIAL : BLE_GATT_SERVICE_INVALID; break; default: break; } (void)pthread_mutex_unlock(&g_connectionLock); } static void ResetGattService(SoftBusGattService *service) { if (service == NULL) { return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } if (service->svcId != -1) { service->state = BLE_GATT_SERVICE_DELETING; int ret = SoftBusGattsDeleteService(service->svcId); if (ret != SOFTBUS_OK) { service->state = BLE_GATT_SERVICE_INVALID; } } else { service->state = BLE_GATT_SERVICE_INITIAL; } service->svcId = -1; service->bleConnCharaId = -1; service->bleConnDesId = -1; service->bleNetCharaId = -1; service->bleNetDesId = -1; (void)pthread_mutex_unlock(&g_connectionLock); } static void BleServiceAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceAddCallback srvcHandle=%d\n", srvcHandle); if ((uuid == NULL) || (uuid->uuid == NULL)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); return; } if (memcmp(uuid->uuid, SOFTBUS_SERVICE_UUID, uuid->uuidLen) == 0) { if (status != SOFTBUS_OK) { ResetGattService(&g_gattService); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); (void)pthread_mutex_unlock(&g_connectionLock); return; } g_gattService.svcId = srvcHandle; (void)pthread_mutex_unlock(&g_connectionLock); SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLENET_UUID); if (msg == NULL) { return; } g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); if (msg == NULL) { return; } g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLECONN_UUID); if (msg == NULL) { return; } g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); } else { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback unknown uuid"); } } static void BleCharacteristicAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle, int characteristicHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "CharacteristicAddCallback srvcHandle=%d,charHandle=%d\n", srvcHandle, characteristicHandle); if ((uuid == NULL) || (uuid->uuid == NULL)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); return; } if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLENET_UUID, uuid->uuidLen) == 0)) { if (status != SOFTBUS_OK) { ResetGattService(&g_gattService); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { return; } if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_gattService state not equal BLE_GATT_SERVICE_ADDING"); (void)pthread_mutex_unlock(&g_connectionLock); return; } g_gattService.bleNetCharaId = characteristicHandle; (void)pthread_mutex_unlock(&g_connectionLock); return; } if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLECONN_UUID, uuid->uuidLen) == 0)) { if (status != SOFTBUS_OK) { ResetGattService(&g_gattService); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { return; } if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { (void)pthread_mutex_unlock(&g_connectionLock); return; } g_gattService.bleConnCharaId = characteristicHandle; (void)pthread_mutex_unlock(&g_connectionLock); SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); if (msg == NULL) { return; } g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); } } static void BleDescriptorAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle, int descriptorHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DescriptorAddCallback srvcHandle=%d,descriptorHandle=%d\n", srvcHandle, descriptorHandle); if ((uuid == NULL) || (uuid->uuid == NULL)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); return; } if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID, uuid->uuidLen) == 0)) { if (status != SOFTBUS_OK) { ResetGattService(&g_gattService); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); (void)pthread_mutex_unlock(&g_connectionLock); return; } if (g_gattService.bleNetDesId == -1) { g_gattService.bleNetDesId = descriptorHandle; } else { g_gattService.bleConnDesId = descriptorHandle; UpdateGattService(&g_gattService, 0); } (void)pthread_mutex_unlock(&g_connectionLock); } else { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDescriptorAddCallback unknown srvcHandle or uuid"); } } static void BleServiceStartCallback(int status, int srvcHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ServiceStartCallback srvcHandle=%d\n", srvcHandle); if (srvcHandle != g_gattService.svcId) { return; } if (status != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start failed"); } UpdateGattService(&g_gattService, status); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start success"); } static void BleServiceStopCallback(int status, int srvcHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceStopCallback srvcHandle=%d\n", srvcHandle); if (srvcHandle != g_gattService.svcId) { return; } if (status != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); } UpdateGattService(&g_gattService, status); } static void BleServiceDeleteCallback(int status, int srvcHandle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceDeleteCallback srvcHandle=%d\n", srvcHandle); if (srvcHandle != g_gattService.svcId) { return; } if (status != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); } UpdateGattService(&g_gattService, status); } static void BleConnectServerCallback(int connId, const SoftBusBtAddr *btAddr) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnectServerCallback is coming, halConnId=%d\n", connId); char bleMac[BT_MAC_LEN]; int ret = ConvertBtMacToStr(bleMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->halConnId == connId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback exist same connId, exit"); (void)pthread_mutex_unlock(&g_connectionLock); return; } } BleConnectionInfo *newNode = CreateBleConnectionNode(); newNode->halConnId = connId; if (memcpy_s(newNode->btBinaryAddr.addr, BT_ADDR_LEN, btAddr->addr, BT_ADDR_LEN) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback memcpy_s error"); SoftBusFree(newNode); (void)pthread_mutex_unlock(&g_connectionLock); return; } if (memcpy_s(newNode->info.info.bleInfo.bleMac, BT_MAC_LEN, bleMac, BT_MAC_LEN) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback memcpy_s error"); SoftBusFree(newNode); (void)pthread_mutex_unlock(&g_connectionLock); return; } newNode->info.isServer = 1; newNode->state = BLE_CONNECTION_STATE_CONNECTED; ListTailInsert(&g_conection_list, &(newNode->node)); (void)pthread_mutex_unlock(&g_connectionLock); g_connectCallback->OnConnected(newNode->connId, &(newNode->info)); } static void BleDisconnectServerCallback(int connId, const SoftBusBtAddr *btAddr) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DisconnectServerCallback is coming, halconnId=%d", connId); char bleMac[BT_MAC_LEN]; int ret = ConvertBtMacToStr(bleMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } ListNode *item = NULL; ListNode *nextItem = NULL; BleConnectionInfo *targetNode = NULL; LIST_FOR_EACH_SAFE(item, nextItem, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); if (itemNode->halConnId == connId) { targetNode = itemNode; itemNode->state = BLE_CONNECTION_STATE_CLOSED; ListDelete(&(itemNode->node)); DeleteBleConnectionNode(itemNode); break; } } (void)pthread_mutex_unlock(&g_connectionLock); if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectServerCallback unknown halconnId:%d", connId); return; } g_connectCallback->OnDisconnected(targetNode->connId, &(targetNode->info)); } static cJSON *GetLocalInfoJson(void) { cJSON *json = cJSON_CreateObject(); if (json == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); return NULL; } char devId[UUID_BUF_LEN] = {0}; if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, devId, UDID_BUF_LEN) != SOFTBUS_OK) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Get local dev Id failed."); return NULL; } if (!AddStringToJsonObject(json, "devid", devId)) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Cannot add devid to jsonobj"); return NULL; } if (!AddNumberToJsonObject(json, "type", BLE_ROLE_SERVER)) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Cannot add type to jsonobj"); return NULL; } return json; } int SendSelfBasicInfo(uint32_t connId) { cJSON *json = GetLocalInfoJson(); if (json == NULL) { return SOFTBUS_ERR; } char *data = cJSON_PrintUnformatted(json); cJSON_Delete(json); if (data == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "cJSON_PrintUnformatted failed"); return SOFTBUS_ERR; } int32_t dataLen = strlen(data) + 1 + TYPE_HEADER_SIZE; int32_t *buf = (int32_t *)SoftBusCalloc(dataLen); if (buf == NULL) { cJSON_free(data); return SOFTBUS_ERR; } buf[0] = TYPE_BASIC_INFO; if (memcpy_s((char*)buf + TYPE_HEADER_SIZE, dataLen - TYPE_HEADER_SIZE, data, strlen(data) + 1)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s data error"); cJSON_free(data); SoftBusFree(buf); return SOFTBUS_ERR; } cJSON_free(data); static int i = 0; ConnPostData postData = { .module = MODULE_BLE_NET, .seq = i++, .flag = 0, .pid = 0, .len = dataLen, .buf = (char*)buf }; BlePostBytesInner(connId, &postData); return SOFTBUS_OK; } int PeerBasicInfoParse(BleConnectionInfo *connInfo, const char *value, int32_t len) { cJSON *data = NULL; data = cJSON_Parse(value + TYPE_HEADER_SIZE); if (!GetJsonObjectStringItem(data, "devid", connInfo->peerDevId, UUID_BUF_LEN) || !GetJsonObjectNumberItem(data, "type", &connInfo->peerType)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PeerBasicInfoParse failed"); return SOFTBUS_ERR; } return SOFTBUS_OK; } static void BleOnDataReceived(int32_t handle, int32_t halConnId, uint32_t len, const char *value) { if (value == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived invalid data"); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } BleConnectionInfo *targetNode = GetBleConnInfoByHalConnId(halConnId); if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived unknown device"); (void)pthread_mutex_unlock(&g_connectionLock); return; } if (handle == g_gattService.bleConnCharaId) { ConnPktHead *head = (ConnPktHead *)value; if (head->module == MODULE_CONNECTION) { cJSON *data = NULL; data = cJSON_Parse(value + sizeof(ConnPktHead)); if (data == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[receive data invalid]"); (void)pthread_mutex_unlock(&g_connectionLock); return; } RecvConnectedComd(targetNode->connId, (const cJSON*)data); cJSON_Delete(data); } else { if (head->len + sizeof(ConnPktHead) > len) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BLEINFOPRTINT: recv a big data:%d, not support", head->len + sizeof(ConnPktHead)); } if (g_connectCallback != NULL) { g_connectCallback->OnDataReceived(targetNode->connId, (ConnModule)head->module, head->seq, (char *)value, head->len + sizeof(ConnPktHead)); } } } else { if (targetNode->state == BLE_CONNECTION_STATE_BASIC_INFO_EXCHANGED) { g_connectCallback->OnDataReceived(targetNode->connId, MODULE_BLE_NET, 0, (char *)value, len); } else { if (PeerBasicInfoParse(targetNode, value, len) != SOFTBUS_OK) { (void)pthread_mutex_unlock(&g_connectionLock); return; } targetNode->state = BLE_CONNECTION_STATE_BASIC_INFO_EXCHANGED; SendSelfBasicInfo(targetNode->connId); } } (void)pthread_mutex_unlock(&g_connectionLock); } static void BleRequestReadCallback(SoftBusGattReadRequest readCbPara) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestReadCallback transId=%d, attrHandle=%d\n", readCbPara.transId, readCbPara.attrHandle); SoftBusGattsResponse response = { .connectId = readCbPara.connId, .status = SOFTBUS_BT_STATUS_SUCCESS, .attrHandle = readCbPara.transId, .valueLen = strlen("not support!") + 1, .value = "not support!" }; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestReadCallback sendresponse"); SoftBusGattsSendResponse(&response); } static void BleRequestWriteCallback(SoftBusGattWriteRequest writeCbPara) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestWriteCallback halconnId=%d, transId=%d, attrHandle=%d\n", writeCbPara.connId, writeCbPara.transId, writeCbPara.attrHandle); if (writeCbPara.attrHandle != g_gattService.bleConnCharaId && writeCbPara.attrHandle != g_gattService.bleNetCharaId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived not support handle :%d expect:%d", writeCbPara.attrHandle, g_gattService.bleConnCharaId); return; } if (writeCbPara.needRsp) { SoftBusGattsResponse response = { .connectId = writeCbPara.connId, .status = SOFTBUS_BT_STATUS_SUCCESS, .attrHandle = writeCbPara.transId, .valueLen = writeCbPara.length, .value = (char *)writeCbPara.value }; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestWriteCallback sendresponse"); SoftBusGattsSendResponse(&response); } SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BLEINFOPRTINT:BleRequestWriteCallback valuelen:%d value:)", writeCbPara.length); uint32_t len; int32_t index = -1; char *value = BleTransRecv(writeCbPara.connId, (char *)writeCbPara.value, (uint32_t)writeCbPara.length, &len, &index); if (value == NULL) { return; } BleOnDataReceived(writeCbPara.attrHandle, writeCbPara.connId, len, (const char *)value); if (index != -1) { BleTransCacheFree(writeCbPara.connId, index); } } static void BleResponseConfirmationCallback(int status, int handle) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ResponseConfirmationCallback status=%d, handle=%d\n", status, handle); } static void BleNotifySentCallback(int connId, int status) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "IndicationSentCallback status=%d, connId=%d\n", status, connId); } static void BleMtuChangeCallback(int connId, int mtu) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "MtuChangeCallback connId=%d, mtu=%d\n", connId, mtu); BleConnectionInfo *connInfo = GetBleConnInfoByConnId(connId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleMtuChangeCallback GetBleConnInfo failed"); return; } connInfo->mtu = mtu; } static int32_t SendBleData(SendQueueNode *node) { if (node->len > MAX_DATA_LEN) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendBleData big msg, len:%d\n", node->len); } if (node->isServer == 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendBleData ble gatt client not support"); return SOFTBUS_ERR; } BleConnectionInfo *connInfo = GetBleConnInfoByConnId(node->connectionId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleMtuChangeCallback GetBleConnInfo failed"); return SOFTBUS_ERR; } if (node->isInner) { return BleTransSend(connInfo, node->data, node->len, node->seq, node->module); } ConnPktHead *head = (ConnPktHead *)node->data; return BleTransSend(connInfo, node->data, node->len, head->seq, head->module); } static void FreeSendNode(SendQueueNode *node) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "FreeSendNode"); if (node == NULL) { return; } if (node->data != NULL) { SoftBusFree((void *)node->data); } SoftBusFree((void *)node); } void *BleSendTask(void *arg) { while (1) { SendQueueNode *node = NULL; BleDequeueBlock((void **)(&node)); if (node == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get sendItem failed"); continue; } if (SendBleData(node) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendItem fail"); } FreeSendNode(node); } } static int GattsRegisterCallback(void) { g_bleGattsCallback.ServiceAddCallback = BleServiceAddCallback; g_bleGattsCallback.CharacteristicAddCallback = BleCharacteristicAddCallback; g_bleGattsCallback.DescriptorAddCallback = BleDescriptorAddCallback; g_bleGattsCallback.ServiceStartCallback = BleServiceStartCallback; g_bleGattsCallback.ServiceStopCallback = BleServiceStopCallback; g_bleGattsCallback.ServiceDeleteCallback = BleServiceDeleteCallback; g_bleGattsCallback.ConnectServerCallback = BleConnectServerCallback; g_bleGattsCallback.DisconnectServerCallback = BleDisconnectServerCallback; g_bleGattsCallback.RequestReadCallback = BleRequestReadCallback; g_bleGattsCallback.RequestWriteCallback = BleRequestWriteCallback; g_bleGattsCallback.ResponseConfirmationCallback = BleResponseConfirmationCallback; g_bleGattsCallback.NotifySentCallback = BleNotifySentCallback; g_bleGattsCallback.MtuChangeCallback = BleMtuChangeCallback; return SoftBusRegisterGattsCallbacks(&g_bleGattsCallback); } static void InitBleInterface(void) { g_bleInterface.ConnectDevice = BleConnectDevice; g_bleInterface.PostBytes = BlePostBytes; g_bleInterface.DisconnectDevice = BleDisconnectDevice; g_bleInterface.DisconnectDeviceNow = BleDisconnectDeviceNow; g_bleInterface.GetConnectionInfo = BleGetConnectionInfo; g_bleInterface.StartLocalListening = BleStartLocalListening; g_bleInterface.StopLocalListening = BleStopLocalListening; } static void BleConnAddSerMsgHandler(const SoftBusMessage *msg) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call GattsRegisterCallback"); int32_t ret = GattsRegisterCallback(); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GattsRegisterCallbacks failed:%d", ret); return; } if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } g_gattService.state = BLE_GATT_SERVICE_ADDING; (void)pthread_mutex_unlock(&g_connectionLock); SoftBusBtUuid uuid; uuid.uuid = (char *)msg->obj; uuid.uuidLen = BT_UUID_LEN; ret = SoftBusGattsAddService(uuid, true, MAX_SERVICE_CHAR_NUM); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddService failed:%d", ret); return; } } static void BleConnMsgHandler(SoftBusMessage *msg) { SoftBusBtUuid uuid; int properties, permissions; if (msg == NULL) { return; } SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ble conn loop process msg type %d", msg->what); switch (msg->what) { case ADD_SERVICE_MSG: BleConnAddSerMsgHandler(msg); break; case ADD_CHARA_MSG: uuid.uuid = (char *)msg->obj; uuid.uuidLen = BT_UUID_LEN; properties = (int32_t)msg->arg1; permissions = (int32_t)msg->arg2; int32_t ret = SoftBusGattsAddCharacteristic(g_gattService.svcId, uuid, properties, permissions); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddCharacteristic failed:%d", ret); return; } break; case ADD_DESCRIPTOR_MSG: uuid.uuid = (char *)msg->obj; uuid.uuidLen = BT_UUID_LEN; permissions = (int32_t)msg->arg2; ret = SoftBusGattsAddDescriptor(g_gattService.svcId, uuid, permissions); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddDescriptor failed:%d", ret); return; } break; default: break; } } static int BleConnLooperInit(void) { g_bleAsyncHandler.looper = CreateNewLooper("ble_looper"); if (g_bleAsyncHandler.looper == NULL) { return SOFTBUS_ERR; } g_bleAsyncHandler.HandleMessage = BleConnMsgHandler; return SOFTBUS_OK; } static int BleQueueInit(void) { uint32_t sendQueueSize; int ret = QueueSizeCalc(SEND_QUEUE_UNIT_NUM, &sendQueueSize); if (ret != SOFTBUS_OK) { return SOFTBUS_ERR; } g_sendQueue.queue = (LockFreeQueue *)SoftBusCalloc(sendQueueSize); if (g_sendQueue.queue == NULL) { return SOFTBUS_ERR; } ret = QueueInit(g_sendQueue.queue, SEND_QUEUE_UNIT_NUM); if (ret != SOFTBUS_OK) { SoftBusFree(g_sendQueue.queue); g_sendQueue.queue = NULL; return SOFTBUS_ERR; } pthread_mutex_init(&g_sendQueue.lock, NULL); pthread_cond_init(&g_sendQueue.cond, NULL); pthread_t tid; if (pthread_create(&tid, NULL, BleSendTask, NULL) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create BleSendTask failed"); SoftBusFree(g_sendQueue.queue); g_sendQueue.queue = NULL; return SOFTBUS_ERR; } return SOFTBUS_OK; } void BleConnOnBtStateChanged(int listenerId, int state) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BleOnBtStateChanged] id:%d, state:%d", listenerId, state); if (state == SOFTBUS_BT_STATE_TURN_ON) { SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_SERVICE_MSG, 0, 0, SOFTBUS_SERVICE_UUID); if (msg == NULL) { return; } g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); } } static SoftBusBtStateListener g_bleConnStateListener = { .OnBtStateChanged = BleConnOnBtStateChanged }; ConnectFuncInterface *ConnInitBle(const ConnectCallback *callback) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[InitBle]"); int32_t ret; ret = BleConnLooperInit(); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnLoopInit failed:%d", ret); return NULL; } pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&g_connectionLock, &attr); ret = BleQueueInit(); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleQueueInit failed:%d", ret); return NULL; } ret = SoftBusAddBtStateListener(&g_bleConnStateListener); if (ret < 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusAddBtStateListener failed:%d", ret); return NULL; } ret = SoftBusEnableBt(); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusAddBtStateListener failed:%d", ret); return NULL; } g_connectCallback = (ConnectCallback*)callback; InitBleInterface(); return &g_bleInterface; }
37.532781
118
0.67925
[ "object" ]
2c1ee4c233260d5ec0abaa979d706f59d5862ae0
2,033
h
C
src/Node.h
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
2
2019-04-13T23:31:06.000Z
2020-12-21T15:33:55.000Z
src/Node.h
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
null
null
null
src/Node.h
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
null
null
null
/*! * \class Node * \author Daniel Sundfeld * \copyright MIT License * * \brief Class that hold all Nodes atributes, like the cost from the * origin, heuristic estimative, parent */ #ifndef _NODE_H #define _NODE_H #include <vector> #include "Coord.h" template < int N > class Node; template < int N > std::ostream& operator<< (std::ostream &lhs, const Node<N> &rhs); template < int N > struct change_node; template < int N > class Node { friend struct change_node< N >; public: Coord<N> pos; //!< Multidimensional coordinate of the node int m_f; //!< priority Node(); Node(const int g, const Coord<N> &pos, const int &parenti); friend std::ostream &operator<< <>(std::ostream &lhs, const Node &rhs); bool operator!=(const Node &rhs) const; void set_max(); int getNeigh(std::vector<Node> a[], int vec_size = 1); int get_g() const { return m_g; }; int get_f() const { return m_f; }; int get_h() const { return m_f - m_g; }; //!< heuristc estimated cost to the goal int get_parenti() const { return parenti; }; inline Coord<N> get_parent() const { return pos.parent(parenti); }; private: int m_g; //!< exact cost of the path from the start int parenti; //!< Integer representing the parent bool borderCheck(const Coord<N> &c) const; inline int pairCost(const int &neigh_num, const int &mm_cost, const int &s1, const int &s2) const; }; /*! * While using libboost implementation, it is possible to use a function * on an "update" operation. Coord always have the same value and must * not be updated. */ template < int N > struct change_node { change_node(int new_f, int new_g, int new_parenti):new_f(new_f), new_g(new_g), new_parenti(new_parenti){} void operator()(Node<N> &n) { n.m_f = new_f; n.m_g = new_g; n.parenti = new_parenti; } private: int new_f; int new_g; int new_parenti; }; #endif //_NODE_H
31.276923
109
0.628136
[ "vector" ]
2c1f7c6ef8cf9c762d1d97f240d8c360b1d61318
3,474
h
C
src/functions.h
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
src/functions.h
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
src/functions.h
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License * * Copyright (c) 2020, Fs2a, Simon de Hartog <simon@fs2a.pro> * 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. * * vim:set ts=4 sw=4 noet tw=120: */ /** @file Miscellaneous convenience functions */ #pragma once #include <unordered_map> #include <string> namespace Fs2a { /** Unordered map with HTML Character Entity Reference Codes to ASCII characters. */ extern const std::unordered_map<std::string, const char> hcerc2asc; /** Convert HTML character entity reference codes to plain ASCII. * @param str_i Input string with HTML character entity reference codes * @returns String with HTML character entity reference codes replaced by their ascii counterparts. */ std::string htmlCharEntRefCodes2ascii(const std::string & str_i); /** Join all items from something iterable into a string, separated by a * given separator string. * @param iterable_i Object to iterate over * @param separator_i Separation string to use, default is ", " * @param extrfunc_i Extraction function to convert item to string, * default is &std::to_string * @param lastsep_i Last separator to use. Facilitates "X", "Y" or "Z". * Default is "", meaning @p separator_i (so last separator can't * actually be the empty string) * @returns All items from @p iterable_i concatenated with @p * separator_i as separator string. */ template <typename IterableObjType> std::string join( const IterableObjType & iterable_i, const std::string & separator_i = ", ", std::string (*extrfunc_i)(const typename IterableObjType::value_type) = &std::to_string, const std::string & lastsep_i = "" ) { std::string rv = ""; // Return Value if (iterable_i.empty()) return rv; auto i = iterable_i.begin(); rv = extrfunc_i(*i); for (i++; i != iterable_i.end(); i++) { auto j = i; j++; if (j == iterable_i.end() && lastsep_i != "") rv += lastsep_i; else rv += separator_i; rv += extrfunc_i(*i); } return rv; } } // Fs2a namespace
41.855422
103
0.729706
[ "object" ]
2c2640fc9ab5c0f26e9e03ad291ae922a15192a6
1,439
h
C
src/AssemblerLib/assembler.h
faouellet/CHIP-16
f85aed30d849052ac057092b124321953de80db6
[ "BSD-3-Clause" ]
null
null
null
src/AssemblerLib/assembler.h
faouellet/CHIP-16
f85aed30d849052ac057092b124321953de80db6
[ "BSD-3-Clause" ]
null
null
null
src/AssemblerLib/assembler.h
faouellet/CHIP-16
f85aed30d849052ac057092b124321953de80db6
[ "BSD-3-Clause" ]
null
null
null
#ifndef ASSEMBLER_H #define ASSEMBLER_H #include <map> #include <regex> #include <set> #include <string> #include <vector> #include "emitter.h" /** * \class Assembler * \brief Produce a binary file from a Chip16 assembly file */ class Assembler { private: std::regex m_CommentRegex; std::regex m_LabelRegex; std::regex m_InstructionRegex; std::regex m_DataRegex; std::regex m_MacroRegex; std::map<std::string, UInt16> m_SymbolTable; std::set<std::string> m_ValidInstructions; public: /* * \fn Assembler * \brief Default constructor */ Assembler(); /* * \fn ~Assembler * \brief Destructor */ ~Assembler() = default; /* * \fn Assemble * \brief Assemble a binary file from a Chip16 file * \param in_Filename Name of the Chip16 assembly file * \return Assembly successful? */ bool Assemble(const std::string & in_Filename); private: // TODO: maybe add a ref to asm book /* * \fn FirstPass * \brief Read the file to populate the symbols table and check for syntax errors * \param in_FileContents The assembly contained in a file * \return Pass completed without error? */ bool FirstPass(const std::vector<std::string> & in_FileContents); /* * \fn SecondPass * \brief Read the file to assemble a binary file * \param in_FileContents The assembly contained in a file */ void SecondPass(const std::vector<std::string> & in_FileContents) const; }; #endif // ASSEMBLER_H
20.855072
82
0.703266
[ "vector" ]
2c27fc0695bc217e804636814b7888b5f99bab18
37,152
c
C
MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
3,012
2015-01-01T19:58:18.000Z
2022-03-31T22:07:14.000Z
MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
1,199
2015-01-12T08:00:01.000Z
2022-03-29T18:14:42.000Z
MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
1,850
2015-01-01T11:28:12.000Z
2022-03-31T18:10:59.000Z
/** @file DXE Core Main Entry Point Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "DxeMain.h" // // DXE Core Global Variables for Protocols from PEI // EFI_HANDLE mDecompressHandle = NULL; // // DXE Core globals for Architecture Protocols // EFI_SECURITY_ARCH_PROTOCOL *gSecurity = NULL; EFI_SECURITY2_ARCH_PROTOCOL *gSecurity2 = NULL; EFI_CPU_ARCH_PROTOCOL *gCpu = NULL; EFI_METRONOME_ARCH_PROTOCOL *gMetronome = NULL; EFI_TIMER_ARCH_PROTOCOL *gTimer = NULL; EFI_BDS_ARCH_PROTOCOL *gBds = NULL; EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *gWatchdogTimer = NULL; // // DXE Core globals for optional protocol dependencies // EFI_SMM_BASE2_PROTOCOL *gSmmBase2 = NULL; // // DXE Core Global used to update core loaded image protocol handle // EFI_GUID *gDxeCoreFileName; EFI_LOADED_IMAGE_PROTOCOL *gDxeCoreLoadedImage; // // DXE Core Module Variables // EFI_BOOT_SERVICES mBootServices = { { EFI_BOOT_SERVICES_SIGNATURE, // Signature EFI_BOOT_SERVICES_REVISION, // Revision sizeof (EFI_BOOT_SERVICES), // HeaderSize 0, // CRC32 0 // Reserved }, (EFI_RAISE_TPL)CoreRaiseTpl, // RaiseTPL (EFI_RESTORE_TPL)CoreRestoreTpl, // RestoreTPL (EFI_ALLOCATE_PAGES)CoreAllocatePages, // AllocatePages (EFI_FREE_PAGES)CoreFreePages, // FreePages (EFI_GET_MEMORY_MAP)CoreGetMemoryMap, // GetMemoryMap (EFI_ALLOCATE_POOL)CoreAllocatePool, // AllocatePool (EFI_FREE_POOL)CoreFreePool, // FreePool (EFI_CREATE_EVENT)CoreCreateEvent, // CreateEvent (EFI_SET_TIMER)CoreSetTimer, // SetTimer (EFI_WAIT_FOR_EVENT)CoreWaitForEvent, // WaitForEvent (EFI_SIGNAL_EVENT)CoreSignalEvent, // SignalEvent (EFI_CLOSE_EVENT)CoreCloseEvent, // CloseEvent (EFI_CHECK_EVENT)CoreCheckEvent, // CheckEvent (EFI_INSTALL_PROTOCOL_INTERFACE)CoreInstallProtocolInterface, // InstallProtocolInterface (EFI_REINSTALL_PROTOCOL_INTERFACE)CoreReinstallProtocolInterface, // ReinstallProtocolInterface (EFI_UNINSTALL_PROTOCOL_INTERFACE)CoreUninstallProtocolInterface, // UninstallProtocolInterface (EFI_HANDLE_PROTOCOL)CoreHandleProtocol, // HandleProtocol (VOID *)NULL, // Reserved (EFI_REGISTER_PROTOCOL_NOTIFY)CoreRegisterProtocolNotify, // RegisterProtocolNotify (EFI_LOCATE_HANDLE)CoreLocateHandle, // LocateHandle (EFI_LOCATE_DEVICE_PATH)CoreLocateDevicePath, // LocateDevicePath (EFI_INSTALL_CONFIGURATION_TABLE)CoreInstallConfigurationTable, // InstallConfigurationTable (EFI_IMAGE_LOAD)CoreLoadImage, // LoadImage (EFI_IMAGE_START)CoreStartImage, // StartImage (EFI_EXIT)CoreExit, // Exit (EFI_IMAGE_UNLOAD)CoreUnloadImage, // UnloadImage (EFI_EXIT_BOOT_SERVICES)CoreExitBootServices, // ExitBootServices (EFI_GET_NEXT_MONOTONIC_COUNT)CoreEfiNotAvailableYetArg1, // GetNextMonotonicCount (EFI_STALL)CoreStall, // Stall (EFI_SET_WATCHDOG_TIMER)CoreSetWatchdogTimer, // SetWatchdogTimer (EFI_CONNECT_CONTROLLER)CoreConnectController, // ConnectController (EFI_DISCONNECT_CONTROLLER)CoreDisconnectController, // DisconnectController (EFI_OPEN_PROTOCOL)CoreOpenProtocol, // OpenProtocol (EFI_CLOSE_PROTOCOL)CoreCloseProtocol, // CloseProtocol (EFI_OPEN_PROTOCOL_INFORMATION)CoreOpenProtocolInformation, // OpenProtocolInformation (EFI_PROTOCOLS_PER_HANDLE)CoreProtocolsPerHandle, // ProtocolsPerHandle (EFI_LOCATE_HANDLE_BUFFER)CoreLocateHandleBuffer, // LocateHandleBuffer (EFI_LOCATE_PROTOCOL)CoreLocateProtocol, // LocateProtocol (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES)CoreInstallMultipleProtocolInterfaces, // InstallMultipleProtocolInterfaces (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES)CoreUninstallMultipleProtocolInterfaces, // UninstallMultipleProtocolInterfaces (EFI_CALCULATE_CRC32)CoreEfiNotAvailableYetArg3, // CalculateCrc32 (EFI_COPY_MEM)CopyMem, // CopyMem (EFI_SET_MEM)SetMem, // SetMem (EFI_CREATE_EVENT_EX)CoreCreateEventEx // CreateEventEx }; EFI_DXE_SERVICES mDxeServices = { { DXE_SERVICES_SIGNATURE, // Signature DXE_SERVICES_REVISION, // Revision sizeof (DXE_SERVICES), // HeaderSize 0, // CRC32 0 // Reserved }, (EFI_ADD_MEMORY_SPACE)CoreAddMemorySpace, // AddMemorySpace (EFI_ALLOCATE_MEMORY_SPACE)CoreAllocateMemorySpace, // AllocateMemorySpace (EFI_FREE_MEMORY_SPACE)CoreFreeMemorySpace, // FreeMemorySpace (EFI_REMOVE_MEMORY_SPACE)CoreRemoveMemorySpace, // RemoveMemorySpace (EFI_GET_MEMORY_SPACE_DESCRIPTOR)CoreGetMemorySpaceDescriptor, // GetMemorySpaceDescriptor (EFI_SET_MEMORY_SPACE_ATTRIBUTES)CoreSetMemorySpaceAttributes, // SetMemorySpaceAttributes (EFI_GET_MEMORY_SPACE_MAP)CoreGetMemorySpaceMap, // GetMemorySpaceMap (EFI_ADD_IO_SPACE)CoreAddIoSpace, // AddIoSpace (EFI_ALLOCATE_IO_SPACE)CoreAllocateIoSpace, // AllocateIoSpace (EFI_FREE_IO_SPACE)CoreFreeIoSpace, // FreeIoSpace (EFI_REMOVE_IO_SPACE)CoreRemoveIoSpace, // RemoveIoSpace (EFI_GET_IO_SPACE_DESCRIPTOR)CoreGetIoSpaceDescriptor, // GetIoSpaceDescriptor (EFI_GET_IO_SPACE_MAP)CoreGetIoSpaceMap, // GetIoSpaceMap (EFI_DISPATCH)CoreDispatcher, // Dispatch (EFI_SCHEDULE)CoreSchedule, // Schedule (EFI_TRUST)CoreTrust, // Trust (EFI_PROCESS_FIRMWARE_VOLUME)CoreProcessFirmwareVolume, // ProcessFirmwareVolume (EFI_SET_MEMORY_SPACE_CAPABILITIES)CoreSetMemorySpaceCapabilities, // SetMemorySpaceCapabilities }; EFI_SYSTEM_TABLE mEfiSystemTableTemplate = { { EFI_SYSTEM_TABLE_SIGNATURE, // Signature EFI_SYSTEM_TABLE_REVISION, // Revision sizeof (EFI_SYSTEM_TABLE), // HeaderSize 0, // CRC32 0 // Reserved }, NULL, // FirmwareVendor 0, // FirmwareRevision NULL, // ConsoleInHandle NULL, // ConIn NULL, // ConsoleOutHandle NULL, // ConOut NULL, // StandardErrorHandle NULL, // StdErr NULL, // RuntimeServices &mBootServices, // BootServices 0, // NumberOfConfigurationTableEntries NULL // ConfigurationTable }; EFI_RUNTIME_SERVICES mEfiRuntimeServicesTableTemplate = { { EFI_RUNTIME_SERVICES_SIGNATURE, // Signature EFI_RUNTIME_SERVICES_REVISION, // Revision sizeof (EFI_RUNTIME_SERVICES), // HeaderSize 0, // CRC32 0 // Reserved }, (EFI_GET_TIME)CoreEfiNotAvailableYetArg2, // GetTime (EFI_SET_TIME)CoreEfiNotAvailableYetArg1, // SetTime (EFI_GET_WAKEUP_TIME)CoreEfiNotAvailableYetArg3, // GetWakeupTime (EFI_SET_WAKEUP_TIME)CoreEfiNotAvailableYetArg2, // SetWakeupTime (EFI_SET_VIRTUAL_ADDRESS_MAP)CoreEfiNotAvailableYetArg4, // SetVirtualAddressMap (EFI_CONVERT_POINTER)CoreEfiNotAvailableYetArg2, // ConvertPointer (EFI_GET_VARIABLE)CoreEfiNotAvailableYetArg5, // GetVariable (EFI_GET_NEXT_VARIABLE_NAME)CoreEfiNotAvailableYetArg3, // GetNextVariableName (EFI_SET_VARIABLE)CoreEfiNotAvailableYetArg5, // SetVariable (EFI_GET_NEXT_HIGH_MONO_COUNT)CoreEfiNotAvailableYetArg1, // GetNextHighMonotonicCount (EFI_RESET_SYSTEM)CoreEfiNotAvailableYetArg4, // ResetSystem (EFI_UPDATE_CAPSULE)CoreEfiNotAvailableYetArg3, // UpdateCapsule (EFI_QUERY_CAPSULE_CAPABILITIES)CoreEfiNotAvailableYetArg4, // QueryCapsuleCapabilities (EFI_QUERY_VARIABLE_INFO)CoreEfiNotAvailableYetArg4 // QueryVariableInfo }; EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate = { INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.ImageHead), INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.EventHead), // // Make sure Size != sizeof (EFI_MEMORY_DESCRIPTOR). This will // prevent people from having pointer math bugs in their code. // now you have to use *DescriptorSize to make things work. // sizeof (EFI_MEMORY_DESCRIPTOR) + sizeof (UINT64) - (sizeof (EFI_MEMORY_DESCRIPTOR) % sizeof (UINT64)), EFI_MEMORY_DESCRIPTOR_VERSION, 0, NULL, NULL, FALSE, FALSE }; EFI_RUNTIME_ARCH_PROTOCOL *gRuntime = &gRuntimeTemplate; // // DXE Core Global Variables for the EFI System Table, Boot Services Table, // DXE Services Table, and Runtime Services Table // EFI_DXE_SERVICES *gDxeCoreDS = &mDxeServices; EFI_SYSTEM_TABLE *gDxeCoreST = NULL; // // For debug initialize gDxeCoreRT to template. gDxeCoreRT must be allocated from RT memory // but gDxeCoreRT is used for ASSERT () and DEBUG () type macros so lets give it // a value that will not cause debug infrastructure to crash early on. // EFI_RUNTIME_SERVICES *gDxeCoreRT = &mEfiRuntimeServicesTableTemplate; EFI_HANDLE gDxeCoreImageHandle = NULL; BOOLEAN gMemoryMapTerminated = FALSE; // // EFI Decompress Protocol // EFI_DECOMPRESS_PROTOCOL gEfiDecompress = { DxeMainUefiDecompressGetInfo, DxeMainUefiDecompress }; // // For Loading modules at fixed address feature, the configuration table is to cache the top address below which to load // Runtime code&boot time code // GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable = { 0, 0 }; // Main entry point to the DXE Core // /** Main entry point to DXE Core. @param HobStart Pointer to the beginning of the HOB List from PEI. @return This function should never return. **/ VOID EFIAPI DxeMain ( IN VOID *HobStart ) { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS MemoryBaseAddress; UINT64 MemoryLength; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; UINTN Index; EFI_HOB_GUID_TYPE *GuidHob; EFI_VECTOR_HANDOFF_INFO *VectorInfoList; EFI_VECTOR_HANDOFF_INFO *VectorInfo; VOID *EntryPoint; // // Setup the default exception handlers // VectorInfoList = NULL; GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *)(GET_GUID_HOB_DATA (GuidHob)); } Status = InitializeCpuExceptionHandlersEx (VectorInfoList, NULL); ASSERT_EFI_ERROR (Status); // // Initialize Debug Agent to support source level debug in DXE phase // InitializeDebugAgent (DEBUG_AGENT_INIT_DXE_CORE, HobStart, NULL); // // Initialize Memory Services // CoreInitializeMemoryServices (&HobStart, &MemoryBaseAddress, &MemoryLength); MemoryProfileInit (HobStart); // // Allocate the EFI System Table and EFI Runtime Service Table from EfiRuntimeServicesData // Use the templates to initialize the contents of the EFI System Table and EFI Runtime Services Table // gDxeCoreST = AllocateRuntimeCopyPool (sizeof (EFI_SYSTEM_TABLE), &mEfiSystemTableTemplate); ASSERT (gDxeCoreST != NULL); gDxeCoreRT = AllocateRuntimeCopyPool (sizeof (EFI_RUNTIME_SERVICES), &mEfiRuntimeServicesTableTemplate); ASSERT (gDxeCoreRT != NULL); gDxeCoreST->RuntimeServices = gDxeCoreRT; // // Start the Image Services. // Status = CoreInitializeImageServices (HobStart); ASSERT_EFI_ERROR (Status); // // Initialize the Global Coherency Domain Services // Status = CoreInitializeGcdServices (&HobStart, MemoryBaseAddress, MemoryLength); ASSERT_EFI_ERROR (Status); // // Call constructor for all libraries // ProcessLibraryConstructorList (gDxeCoreImageHandle, gDxeCoreST); PERF_CROSSMODULE_END ("PEI"); PERF_CROSSMODULE_BEGIN ("DXE"); // // Log MemoryBaseAddress and MemoryLength again (from // CoreInitializeMemoryServices()), now that library constructors have // executed. // DEBUG (( DEBUG_INFO, "%a: MemoryBaseAddress=0x%Lx MemoryLength=0x%Lx\n", __FUNCTION__, MemoryBaseAddress, MemoryLength )); // // Report DXE Core image information to the PE/COFF Extra Action Library // ZeroMem (&ImageContext, sizeof (ImageContext)); ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)gDxeCoreLoadedImage->ImageBase; ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageContext.ImageAddress); ImageContext.SizeOfHeaders = PeCoffGetSizeOfHeaders ((VOID *)(UINTN)ImageContext.ImageAddress); Status = PeCoffLoaderGetEntryPoint ((VOID *)(UINTN)ImageContext.ImageAddress, &EntryPoint); if (Status == EFI_SUCCESS) { ImageContext.EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)EntryPoint; } ImageContext.Handle = (VOID *)(UINTN)gDxeCoreLoadedImage->ImageBase; ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; PeCoffLoaderRelocateImageExtraAction (&ImageContext); // // Install the DXE Services Table into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiDxeServicesTableGuid, gDxeCoreDS); ASSERT_EFI_ERROR (Status); // // Install the HOB List into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiHobListGuid, HobStart); ASSERT_EFI_ERROR (Status); // // Install Memory Type Information Table into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiMemoryTypeInformationGuid, &gMemoryTypeInformation); ASSERT_EFI_ERROR (Status); // // If Loading modules At fixed address feature is enabled, install Load moduels at fixed address // Configuration Table so that user could easily to retrieve the top address to load Dxe and PEI // Code and Tseg base to load SMM driver. // if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { Status = CoreInstallConfigurationTable (&gLoadFixedAddressConfigurationTableGuid, &gLoadModuleAtFixAddressConfigurationTable); ASSERT_EFI_ERROR (Status); } // // Report Status Code here for DXE_ENTRY_POINT once it is available // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_ENTRY_POINT) ); // // Create the aligned system table pointer structure that is used by external // debuggers to locate the system table... Also, install debug image info // configuration table. // CoreInitializeDebugImageInfoTable (); CoreNewDebugImageInfoEntry ( EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, gDxeCoreLoadedImage, gDxeCoreImageHandle ); DEBUG ((DEBUG_INFO | DEBUG_LOAD, "HOBLIST address in DXE = 0x%p\n", HobStart)); DEBUG_CODE_BEGIN (); EFI_PEI_HOB_POINTERS Hob; for (Hob.Raw = HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1 )); } } for (Hob.Raw = HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, "FV Hob 0x%0lx - 0x%0lx\n", Hob.FirmwareVolume->BaseAddress, Hob.FirmwareVolume->BaseAddress + Hob.FirmwareVolume->Length - 1 )); } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, "FV2 Hob 0x%0lx - 0x%0lx\n", Hob.FirmwareVolume2->BaseAddress, Hob.FirmwareVolume2->BaseAddress + Hob.FirmwareVolume2->Length - 1 )); DEBUG (( DEBUG_INFO | DEBUG_LOAD, " %g - %g\n", &Hob.FirmwareVolume2->FvName, &Hob.FirmwareVolume2->FileName )); } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, "FV3 Hob 0x%0lx - 0x%0lx - 0x%x - 0x%x\n", Hob.FirmwareVolume3->BaseAddress, Hob.FirmwareVolume3->BaseAddress + Hob.FirmwareVolume3->Length - 1, Hob.FirmwareVolume3->AuthenticationStatus, Hob.FirmwareVolume3->ExtractedFv )); if (Hob.FirmwareVolume3->ExtractedFv) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, " %g - %g\n", &Hob.FirmwareVolume3->FvName, &Hob.FirmwareVolume3->FileName )); } } } DEBUG_CODE_END (); // // Initialize the Event Services // Status = CoreInitializeEventServices (); ASSERT_EFI_ERROR (Status); MemoryProfileInstallProtocol (); CoreInitializeMemoryAttributesTable (); CoreInitializeMemoryProtection (); // // Get persisted vector hand-off info from GUIDeed HOB again due to HobStart may be updated, // and install configuration table // GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *)(GET_GUID_HOB_DATA (GuidHob)); VectorInfo = VectorInfoList; Index = 1; while (VectorInfo->Attribute != EFI_VECTOR_HANDOFF_LAST_ENTRY) { VectorInfo++; Index++; } VectorInfo = AllocateCopyPool (sizeof (EFI_VECTOR_HANDOFF_INFO) * Index, (VOID *)VectorInfoList); ASSERT (VectorInfo != NULL); Status = CoreInstallConfigurationTable (&gEfiVectorHandoffTableGuid, (VOID *)VectorInfo); ASSERT_EFI_ERROR (Status); } // // Get the Protocols that were passed in from PEI to DXE through GUIDed HOBs // // These Protocols are not architectural. This implementation is sharing code between // PEI and DXE in order to save FLASH space. These Protocols could also be implemented // as part of the DXE Core. However, that would also require the DXE Core to be ported // each time a different CPU is used, a different Decompression algorithm is used, or a // different Image type is used. By placing these Protocols in PEI, the DXE Core remains // generic, and only PEI and the Arch Protocols need to be ported from Platform to Platform, // and from CPU to CPU. // // // Publish the EFI, Tiano, and Custom Decompress protocols for use by other DXE components // Status = CoreInstallMultipleProtocolInterfaces ( &mDecompressHandle, &gEfiDecompressProtocolGuid, &gEfiDecompress, NULL ); ASSERT_EFI_ERROR (Status); // // Register for the GUIDs of the Architectural Protocols, so the rest of the // EFI Boot Services and EFI Runtime Services tables can be filled in. // Also register for the GUIDs of optional protocols. // CoreNotifyOnProtocolInstallation (); // // Produce Firmware Volume Protocols, one for each FV in the HOB list. // Status = FwVolBlockDriverInit (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); Status = FwVolDriverInit (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); // // Produce the Section Extraction Protocol // Status = InitializeSectionExtraction (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); // // Initialize the DXE Dispatcher // CoreInitializeDispatcher (); // // Invoke the DXE Dispatcher // CoreDispatcher (); // // Display Architectural protocols that were not loaded if this is DEBUG build // DEBUG_CODE_BEGIN (); CoreDisplayMissingArchProtocols (); DEBUG_CODE_END (); // // Display any drivers that were not dispatched because dependency expression // evaluated to false if this is a debug build // DEBUG_CODE_BEGIN (); CoreDisplayDiscoveredNotDispatched (); DEBUG_CODE_END (); // // Assert if the Architectural Protocols are not present. // Status = CoreAllEfiServicesAvailable (); if (EFI_ERROR (Status)) { // // Report Status code that some Architectural Protocols are not present. // REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MAJOR, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_EC_NO_ARCH) ); } ASSERT_EFI_ERROR (Status); // // Report Status code before transfer control to BDS // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_HANDOFF_TO_NEXT) ); // // Transfer control to the BDS Architectural Protocol // gBds->Entry (gBds); // // BDS should never return // ASSERT (FALSE); CpuDeadLoop (); UNREACHABLE (); } /** Place holder function until all the Boot Services and Runtime Services are available. @param Arg1 Undefined @return EFI_NOT_AVAILABLE_YET **/ EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg1 ( UINTN Arg1 ) { // // This function should never be executed. If it does, then the architectural protocols // have not been designed correctly. The CpuBreakpoint () is commented out for now until the // DXE Core and all the Architectural Protocols are complete. // return EFI_NOT_AVAILABLE_YET; } /** Place holder function until all the Boot Services and Runtime Services are available. @param Arg1 Undefined @param Arg2 Undefined @return EFI_NOT_AVAILABLE_YET **/ EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg2 ( UINTN Arg1, UINTN Arg2 ) { // // This function should never be executed. If it does, then the architectural protocols // have not been designed correctly. The CpuBreakpoint () is commented out for now until the // DXE Core and all the Architectural Protocols are complete. // return EFI_NOT_AVAILABLE_YET; } /** Place holder function until all the Boot Services and Runtime Services are available. @param Arg1 Undefined @param Arg2 Undefined @param Arg3 Undefined @return EFI_NOT_AVAILABLE_YET **/ EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg3 ( UINTN Arg1, UINTN Arg2, UINTN Arg3 ) { // // This function should never be executed. If it does, then the architectural protocols // have not been designed correctly. The CpuBreakpoint () is commented out for now until the // DXE Core and all the Architectural Protocols are complete. // return EFI_NOT_AVAILABLE_YET; } /** Place holder function until all the Boot Services and Runtime Services are available. @param Arg1 Undefined @param Arg2 Undefined @param Arg3 Undefined @param Arg4 Undefined @return EFI_NOT_AVAILABLE_YET **/ EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg4 ( UINTN Arg1, UINTN Arg2, UINTN Arg3, UINTN Arg4 ) { // // This function should never be executed. If it does, then the architectural protocols // have not been designed correctly. The CpuBreakpoint () is commented out for now until the // DXE Core and all the Architectural Protocols are complete. // return EFI_NOT_AVAILABLE_YET; } /** Place holder function until all the Boot Services and Runtime Services are available. @param Arg1 Undefined @param Arg2 Undefined @param Arg3 Undefined @param Arg4 Undefined @param Arg5 Undefined @return EFI_NOT_AVAILABLE_YET **/ EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg5 ( UINTN Arg1, UINTN Arg2, UINTN Arg3, UINTN Arg4, UINTN Arg5 ) { // // This function should never be executed. If it does, then the architectural protocols // have not been designed correctly. The CpuBreakpoint () is commented out for now until the // DXE Core and all the Architectural Protocols are complete. // return EFI_NOT_AVAILABLE_YET; } /** Calcualte the 32-bit CRC in a EFI table using the service provided by the gRuntime service. @param Hdr Pointer to an EFI standard header **/ VOID CalculateEfiHdrCrc ( IN OUT EFI_TABLE_HEADER *Hdr ) { UINT32 Crc; Hdr->CRC32 = 0; // // If gBS->CalculateCrce32 () == CoreEfiNotAvailableYet () then // Crc will come back as zero if we set it to zero here // Crc = 0; gBS->CalculateCrc32 ((UINT8 *)Hdr, Hdr->HeaderSize, &Crc); Hdr->CRC32 = Crc; } /** Terminates all boot services. @param ImageHandle Handle that identifies the exiting image. @param MapKey Key to the latest memory map. @retval EFI_SUCCESS Boot Services terminated @retval EFI_INVALID_PARAMETER MapKey is incorrect. **/ EFI_STATUS EFIAPI CoreExitBootServices ( IN EFI_HANDLE ImageHandle, IN UINTN MapKey ) { EFI_STATUS Status; // // Disable Timer // gTimer->SetTimerPeriod (gTimer, 0); // // Terminate memory services if the MapKey matches // Status = CoreTerminateMemoryMap (MapKey); if (EFI_ERROR (Status)) { // // Notify other drivers that ExitBootServices fail // CoreNotifySignalList (&gEventExitBootServicesFailedGuid); return Status; } gMemoryMapTerminated = TRUE; // // Notify other drivers that we are exiting boot services. // CoreNotifySignalList (&gEfiEventExitBootServicesGuid); // // Report that ExitBootServices() has been called // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_EFI_BOOT_SERVICE | EFI_SW_BS_PC_EXIT_BOOT_SERVICES) ); MemoryProtectionExitBootServicesCallback (); // // Disable interrupt of Debug timer. // SaveAndSetDebugTimerInterrupt (FALSE); // // Disable CPU Interrupts // gCpu->DisableInterrupt (gCpu); // // Clear the non-runtime values of the EFI System Table // gDxeCoreST->BootServices = NULL; gDxeCoreST->ConIn = NULL; gDxeCoreST->ConsoleInHandle = NULL; gDxeCoreST->ConOut = NULL; gDxeCoreST->ConsoleOutHandle = NULL; gDxeCoreST->StdErr = NULL; gDxeCoreST->StandardErrorHandle = NULL; // // Recompute the 32-bit CRC of the EFI System Table // CalculateEfiHdrCrc (&gDxeCoreST->Hdr); // // Zero out the Boot Service Table // ZeroMem (gBS, sizeof (EFI_BOOT_SERVICES)); gBS = NULL; // // Update the AtRuntime field in Runtiem AP. // gRuntime->AtRuntime = TRUE; return Status; } /** Given a compressed source buffer, this function retrieves the size of the uncompressed buffer and the size of the scratch buffer required to decompress the compressed source buffer. The GetInfo() function retrieves the size of the uncompressed buffer and the temporary scratch buffer required to decompress the buffer specified by Source and SourceSize. If the size of the uncompressed buffer or the size of the scratch buffer cannot be determined from the compressed data specified by Source and SourceData, then EFI_INVALID_PARAMETER is returned. Otherwise, the size of the uncompressed buffer is returned in DestinationSize, the size of the scratch buffer is returned in ScratchSize, and EFI_SUCCESS is returned. The GetInfo() function does not have scratch buffer available to perform a thorough checking of the validity of the source data. It just retrieves the "Original Size" field from the beginning bytes of the source data and output it as DestinationSize. And ScratchSize is specific to the decompression implementation. @param This A pointer to the EFI_DECOMPRESS_PROTOCOL instance. @param Source The source buffer containing the compressed data. @param SourceSize The size, in bytes, of the source buffer. @param DestinationSize A pointer to the size, in bytes, of the uncompressed buffer that will be generated when the compressed buffer specified by Source and SourceSize is decompressed. @param ScratchSize A pointer to the size, in bytes, of the scratch buffer that is required to decompress the compressed buffer specified by Source and SourceSize. @retval EFI_SUCCESS The size of the uncompressed data was returned in DestinationSize and the size of the scratch buffer was returned in ScratchSize. @retval EFI_INVALID_PARAMETER The size of the uncompressed data or the size of the scratch buffer cannot be determined from the compressed data specified by Source and SourceSize. **/ EFI_STATUS EFIAPI DxeMainUefiDecompressGetInfo ( IN EFI_DECOMPRESS_PROTOCOL *This, IN VOID *Source, IN UINT32 SourceSize, OUT UINT32 *DestinationSize, OUT UINT32 *ScratchSize ) { if ((Source == NULL) || (DestinationSize == NULL) || (ScratchSize == NULL)) { return EFI_INVALID_PARAMETER; } return UefiDecompressGetInfo (Source, SourceSize, DestinationSize, ScratchSize); } /** Decompresses a compressed source buffer. The Decompress() function extracts decompressed data to its original form. This protocol is designed so that the decompression algorithm can be implemented without using any memory services. As a result, the Decompress() Function is not allowed to call AllocatePool() or AllocatePages() in its implementation. It is the caller's responsibility to allocate and free the Destination and Scratch buffers. If the compressed source data specified by Source and SourceSize is successfully decompressed into Destination, then EFI_SUCCESS is returned. If the compressed source data specified by Source and SourceSize is not in a valid compressed data format, then EFI_INVALID_PARAMETER is returned. @param This A pointer to the EFI_DECOMPRESS_PROTOCOL instance. @param Source The source buffer containing the compressed data. @param SourceSize SourceSizeThe size of source data. @param Destination On output, the destination buffer that contains the uncompressed data. @param DestinationSize The size of the destination buffer. The size of the destination buffer needed is obtained from EFI_DECOMPRESS_PROTOCOL.GetInfo(). @param Scratch A temporary scratch buffer that is used to perform the decompression. @param ScratchSize The size of scratch buffer. The size of the scratch buffer needed is obtained from GetInfo(). @retval EFI_SUCCESS Decompression completed successfully, and the uncompressed buffer is returned in Destination. @retval EFI_INVALID_PARAMETER The source buffer specified by Source and SourceSize is corrupted (not in a valid compressed format). **/ EFI_STATUS EFIAPI DxeMainUefiDecompress ( IN EFI_DECOMPRESS_PROTOCOL *This, IN VOID *Source, IN UINT32 SourceSize, IN OUT VOID *Destination, IN UINT32 DestinationSize, IN OUT VOID *Scratch, IN UINT32 ScratchSize ) { EFI_STATUS Status; UINT32 TestDestinationSize; UINT32 TestScratchSize; if ((Source == NULL) || (Destination == NULL) || (Scratch == NULL)) { return EFI_INVALID_PARAMETER; } Status = UefiDecompressGetInfo (Source, SourceSize, &TestDestinationSize, &TestScratchSize); if (EFI_ERROR (Status)) { return Status; } if ((ScratchSize < TestScratchSize) || (DestinationSize < TestDestinationSize)) { return RETURN_INVALID_PARAMETER; } return UefiDecompress (Source, Destination, Scratch); }
38.98426
131
0.603009
[ "vector" ]
2c2fea950180c37a7ea79945bad6b1d3d3c1efa9
44,920
c
C
src/backend/access/remote/remote_xact.c
zettadb/kunlun
c6e24d6605f2551a2bc6f114bb37d39e4cdbfb47
[ "PostgreSQL", "Apache-2.0" ]
99
2021-03-09T06:52:05.000Z
2022-03-23T03:26:59.000Z
src/backend/access/remote/remote_xact.c
zettadb/kunlun
c6e24d6605f2551a2bc6f114bb37d39e4cdbfb47
[ "PostgreSQL", "Apache-2.0" ]
4
2021-07-30T02:37:14.000Z
2022-02-27T19:20:39.000Z
src/backend/access/remote/remote_xact.c
zettadb/kunlun
c6e24d6605f2551a2bc6f114bb37d39e4cdbfb47
[ "PostgreSQL", "Apache-2.0" ]
15
2021-04-12T02:40:26.000Z
2022-02-27T14:50:49.000Z
/*------------------------------------------------------------------------- * * remote_xact.c * send transaction commands to remote storage nodes. * * Copyright (c) 2019-2021 ZettaDB inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * combined with Common Clause Condition 1.0, as detailed in the NOTICE file. * * * IDENTIFICATION * src/backend/access/remote/remote_xact.c * * * INTERFACE ROUTINES * NOTES * This file contains the routines which implement * the POSTGRES remote access method used for remotely stored POSTGRES * relations. * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/remote_xact.h" #include "nodes/nodes.h" #include "nodes/pg_list.h" #include "utils/memutils.h" #include "sharding/sharding.h" #include "sharding/sharding_conn.h" #include "utils/builtins.h" #include "sharding/cluster_meta.h" #include "utils/snapmgr.h" #include "storage/shmem.h" #include "utils/catcache.h" #include "utils/guc.h" #include "miscadmin.h" #include "executor/spi.h" #include "storage/lwlock.h" #include "storage/bufmgr.h" #include "storage/smgr.h" #include "tcop/tcopprot.h" #include <unistd.h> #include <limits.h> #include <time.h> static char*get_storage_node_version(AsyncStmtInfo *asi); static bool check_gdd_supported(AsyncStmtInfo *asi); static void send_txn_cmd(enum enum_sql_command sqlcom, bool written_only, const char *fmt,...); static void init_txn_cmd(void); void downgrade_error(void); // send 'savepoint xxx' to all accessed shards in current transaction. char *g_txn_cmd = 0; size_t g_txn_cmd_buflen = 256; // GUI variables bool trace_global_deadlock_detection = false; int start_global_deadlock_detection_wait_timeout = 100; bool enable_global_deadlock_detection = true; inline static int gdd_log_level() { #ifdef ENABLE_DEBUG return trace_global_deadlock_detection ? LOG : DEBUG1; #else return DEBUG2; #endif } static void init_txn_cmd() { if (!g_txn_cmd) g_txn_cmd = MemoryContextAlloc(TopMemoryContext, g_txn_cmd_buflen); } void StartSubTxnRemote(const char *name) { Assert(name); send_txn_cmd(SQLCOM_SAVEPOINT, false, "SAVEPOINT %s", name); } void SendReleaseSavepointToRemote(const char *name) { send_txn_cmd(SQLCOM_RELEASE_SAVEPOINT, false, "RELEASE SAVEPOINT %s", name); } void SendRollbackRemote(const char *txnid, bool xa_end, bool written_only) { /* * If top txn's name isn't set, no XA txn is started at any storage nodes, * thus no need to execute an XA ROLLBACK. * */ if (!txnid) return; /* Txn memcxt is already released, should not free stmts in case they are allocated in txn memcxt, and they should be. Otherwise there would be memory leaks here! */ CancelAllRemoteStmtsInQueue(false); int ihoc = InterruptHoldoffCount; PG_TRY(); { if (xa_end) send_txn_cmd(SQLCOM_XA_ROLLBACK, written_only, "XA END '%s';XA ROLLBACK '%s'", txnid, txnid); else send_txn_cmd(SQLCOM_XA_ROLLBACK, written_only, "XA ROLLBACK '%s'", txnid); } PG_CATCH(); { PG_TRY(); { disconnect_storage_shards(); request_topo_checks_used_shards(); } PG_CATCH(); { } PG_END_TRY(); } PG_END_TRY(); InterruptHoldoffCount = ihoc; } void SendRollbackSubToRemote(const char *name) { send_txn_cmd(SQLCOM_ROLLBACK_TO_SAVEPOINT, false, "ROLLBACK TO %s", name); } static void send_txn_cmd(enum enum_sql_command esc, bool written_only, const char *fmt,...) { init_txn_cmd(); int len; va_list args; again: va_start(args, fmt); len = vsnprintf(g_txn_cmd, g_txn_cmd_buflen, fmt, args); va_end(args); if (len >= g_txn_cmd_buflen) { g_txn_cmd = repalloc(g_txn_cmd, g_txn_cmd_buflen *= 2); goto again; } send_stmt_to_all_inuse(g_txn_cmd, len, CMD_TXN_MGMT, false, esc, written_only); } /* * Send 1st phase stmts to remote shards, return true if there is 2nd phase, * false if no 2nd phase needed. * */ bool Send1stPhaseRemote(const char *txnid) { int num = GetAsyncStmtInfoUsed(); int nr = 0, nw = 0, nddls = 0; if (num <= 0 || txnid == NULL) return false; static size_t slen = 0; static char *stmt = NULL; static char *stmt1 = NULL; static char *stmt2 = NULL; if (!stmt) { slen = 3 * (txnid ? strlen(txnid) : 0) + 64; stmt = MemoryContextAlloc(TopMemoryContext, slen); stmt1 = MemoryContextAlloc(TopMemoryContext, slen); stmt2 = MemoryContextAlloc(TopMemoryContext, slen); } else { // We need no more than this actually. Assert(slen >= 2*strlen(txnid) + 34); } /* * This is a flag to let the allocated string belong to only one StmtElem, * other StmtElem simply refer to it but don't own it. The stmts sent to * all shards are the same so we don't want to alloc&fill it for every shard. * */ bool filled = false; int len = 0; bool abort_txn = false; for (int i = 0; i < num; i++) { AsyncStmtInfo *asi = GetAsyncStmtInfoByIndex(i); if (!ASIConnected(asi) || IsConnReset(asi)) { abort_txn = true; continue; } if (asi->did_write && asi->txn_wrows > 0) { elog(DEBUG2, "Found written shard in transaction %s shard node (%u,%u) at %s:%u, %d rows written.", txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port, asi->txn_wrows); nw++; } if (asi->did_ddl) nddls++; if (ASIReadOnly(asi) || (ASIAccessed(asi) && asi->txn_wrows == 0)) { if (!filled) { len = snprintf(stmt, slen, "XA END '%s';XA COMMIT '%s' ONE PHASE", txnid, txnid); Assert(len < slen); filled = true; } /* If we send an update to a shard but no maching rows updated, it's marked written but txn_wrows is 0. */ elog(DEBUG2, "Found in transaction %s shard node (%u,%u) at %s:%u read only branch, doing 1pc to it.", txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port); // In MySQL, XA COMMIT ... ONE PHASE is also a SQLCOM_XA_COMMIT. append_async_stmt(asi, stmt, len, CMD_TXN_MGMT, false, SQLCOM_XA_COMMIT); Assert(asi->result_pending == false); nr++; } if (ASIConnected(asi) && !ASIAccessed(asi)) { /* This happens when asi connection was found broken when stmts was sent through the connection and it's not an error, we can simply ignore the situation. */ ereport(LOG, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("A shard (%u) node (%u)'s connection not read or written in transaction %s is seen as used, probably because the connection was broken already.", asi->shard_id, asi->node_id, txnid))); } } if (nddls > 0) { if (nw > 0 || nr > 0 /*|| nddls > 1 it's possible that one DDL stmt takes actions on >1 tablets. MySQL XA doesn't support DDLs, for ACID properties of such a DDL stmt, we'd have to utilize the metadata DDL log.*/) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("State error for transaction %s: As required by MySQL, a DDL statement must be a single autocommit transaction, it should never be in an explicit transaction(nDDLs: %d, nWrittenShards: %d, nReadShards: %d).", txnid, nddls, nw, nr))); } return false; } Assert(nw >= 0); enum enum_sql_command sqlcom; bool filled1 = false; bool filled2 = false; // store 2nd type of stmts into stmt2. for (int i = 0; i < num; i++) { AsyncStmtInfo *asi = GetAsyncStmtInfoByIndex(i); // skip broken channels here, nothing to do for them here. if (!ASIConnected(asi) || IsConnReset(asi)) continue; if (asi->did_write) { if (abort_txn) { if (!filled) { len = snprintf(stmt2, slen, "XA END '%s';XA ROLLBACK '%s'", txnid, txnid); filled = true; } sqlcom = SQLCOM_XA_ROLLBACK; elog(DEBUG2, "Aborting transaction %s 's branch in shard node (%u,%u) at %s:%u", txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port); append_async_stmt(asi, stmt2, len, CMD_TXN_MGMT, false, sqlcom); } else if (nw == 1 && ASIAccessed(asi) && asi->txn_wrows > 0) { if (filled1 == false) { len = snprintf(stmt1, slen, "XA END '%s';XA COMMIT '%s' ONE PHASE", txnid, txnid); filled1 = true; } sqlcom = SQLCOM_XA_COMMIT; elog(DEBUG2, "Only 1 written shard found for transaction %s in shard node (%u,%u) at %s:%u, doing 1pc to it.", txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port); append_async_stmt(asi, stmt1, len, CMD_TXN_MGMT, false, sqlcom); } else if (nw > 1 && asi->txn_wrows > 0) { if (filled2 == false) { len = snprintf(stmt2, slen, "XA END '%s';XA PREPARE '%s'", txnid, txnid); filled2 = true; } sqlcom = SQLCOM_XA_PREPARE; elog(DEBUG2, "Found %d written shards for transaction %s, preparing in shard node (%u,%u) at %s:%u", nw, txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port); append_async_stmt(asi, stmt2, len, CMD_TXN_MGMT, false, sqlcom); } Assert(len < slen); Assert(asi->result_pending == false); } } send_multi_stmts_to_multi(); return nw > 1 && !abort_txn; } void Send2ndPhaseRemote(const char *txnid) { int num = GetAsyncStmtInfoUsed(); static size_t slen = 0; static char *stmt = NULL; int len = 0; bool filled = false; Assert(txnid && num > 1); if (!stmt) { slen = 2*strlen(txnid) + 32; stmt = MemoryContextAlloc(TopMemoryContext, slen); } else { // txnid strings are of similar lengths, make sure we allocated enough Assert(slen > strlen(txnid) + 14); } for (int i = 0; i < num; i++) { AsyncStmtInfo *asi = GetAsyncStmtInfoByIndex(i); /* If any conn broken before this call, the txn is aborted. So when we arrive here we definitely have all conns valid. */ Assert(ASIConnected(asi)); if (asi->did_write && asi->txn_wrows > 0) { if (!filled) { len = snprintf(stmt, slen, "XA COMMIT '%s'", txnid); Assert(len < slen); filled = true; } elog(DEBUG2, "For transaction %s doing 2pc commit in shard node (%u,%u) at %s:%u", txnid, asi->shard_id, asi->node_id, asi->conn->host, asi->conn->port); append_async_stmt(asi, stmt, len, CMD_TXN_MGMT, false, SQLCOM_XA_COMMIT); } } send_multi_stmts_to_multi(); } /* insert debug sync point to accessed storage shards certain debug_sync setting. where: so far always 1(before_execute_sql_command); what: so far always 1(wait) which: 1: all accessed shards; 2: all written shards */ void insert_debug_sync(int where, int what, int which) { #ifdef ENABLE_DEBUG_SYNC Assert(where == 1 && what == 1); Assert(which == 1 || which == 2); int num = GetAsyncStmtInfoUsed(); char stmt[] = "set session debug_sync = 'before_execute_sql_command wait_for resume'"; for (int i = 0; i < num; i++) { AsyncStmtInfo *asi = GetAsyncStmtInfoByIndex(i); if (asi->did_write || which == 1) { append_async_stmt(asi, stmt, sizeof(stmt) - 1, CMD_UTILITY, false, SQLCOM_SET_OPTION); } } #endif } char *MakeTopTxnName(TransactionId txnid, time_t now) { int idlen = 128, ret = 0; char *ptxnid = MemoryContextAlloc(TopTransactionContext, idlen); again: ret = snprintf(ptxnid, idlen, "%u-%ld-%u", comp_node_id, now, txnid); if (ret >= idlen) { ptxnid = repalloc(ptxnid, idlen *= 2); goto again; } return ptxnid; } /****************************************************************************/ /* * Global deadlock detector. * Periodically perform deadlock detection, and can be activated by waits for * remote DML result. * Fetch each shard master's local txn wait-for relationships, to build a * global one. * */ int g_glob_txnmgr_deadlock_detector_victim_policy = KILL_MOST_ROWS_LOCKED; static MemoryContext gdd_memcxt = NULL; static MemoryContext gdd_stmts_memcxt = NULL; /* * Let each backend request a round of global dd by sending gdd SIGUSR2. * they can do so if insert/update/delete stmts takes some time (N millisecs) * and not returned. N should be set less than lockwait timeout. * gdd can already respond to SIGUSR2 to start a round of gdd. */ typedef struct GDDState { volatile sig_atomic_t num_reqs; pid_t gdd_pid; time_t when_last_gdd; } GDDState; static GDDState *g_gdd_state = NULL; Size GDDShmemSize() { return sizeof(GDDState); } void CreateGDDShmem() { bool found = false; Size size = GDDShmemSize(); g_gdd_state = (GDDState*)ShmemInitStruct("Global deadlock detector state.", size, &found); if (!found) { /* * We're the first - initialize. */ MemSet(g_gdd_state, 0, size); } } /* To be called only by the gdd process, the pid will be used by backend processes to notify the gdd to start a round of deadlock detection. */ void set_gdd_pid() { g_gdd_state->gdd_pid = getpid(); } void kick_start_gdd() { #ifdef ENABLE_DEBUG /* This is called in SIGALRM handler, don't do IO or anything complex in production build. */ elog(gdd_log_level(), "Waking up gdd after waiting %d ms for write results from shards.", start_global_deadlock_detection_wait_timeout); #endif if (g_gdd_state->gdd_pid != 0) kill(g_gdd_state->gdd_pid, SIGUSR2); } size_t increment_gdd_reqs() { return ++g_gdd_state->num_reqs; } /* * This is only used to identify a global txn in deadlock detector code. * */ typedef struct GTxnId { time_t ts; Oid compnodeid; TransactionId txnid; } GTxnId; typedef struct TxnBranchId { GTxnId gtxnid; Shard_id_t shardid; } TxnBranchId; typedef struct GlobalTxn GlobalTxn; typedef struct TxnBranch { TxnBranchId tbid; // This global txn's txn branch is currently waiting in this shard for lock. Shard_id_t waiting_shardid; // The target txn branch's connection id. uint32_t mysql_connid; GlobalTxn *owner; // whether this txn branch's query is chosen as victim by deadlock detector. bool killed_dd; } TxnBranch; typedef struct TxnBranchRef { TxnBranchId txnid; TxnBranch *ptr; } TxnBranchRef; /* * Global txn wait-for graph node. Note that any global txn can be waiting * for at most one other global txn at any time. * */ typedef struct GlobalTxn { GTxnId gtxnid; // min of all txn branches time_t start_ts; // In each round of sub-graph traverse, each visited graph node is given // this unique id to identify this round of traverse. uint64_t visit_id; // sum of all txn branches uint32_t nrows_changed; uint32_t nrows_locked; // NO. of txn branches killed by deadlock detector. if in a cycle there is such a // global txn whose txn branches killed most by DD when they were found in other cycles, // it's always chosen as the victim for this cycle, to minimize the NO. of // global txns killed. uint32_t nbranches_killed; /* NO. of txn branches blocked by txn branches of this global txn. */ uint32_t num_blocked; // The txn branches this global txn waits for, i.e. its branches wait for. // Given a TxnBranch tb1 in 'blockers' array, the TxnBranch object in 'branches' // array with the same shardid is the txn branch that's waiting for tb1. TxnBranch **blockers; uint32_t nblocker_slots; uint32_t nblockers; /* This global txn's waiting txn branches in all shards accessed by the global txn. */ TxnBranch **branches; uint32_t nbranch_slots; uint32_t nbranches; } GlobalTxn; typedef struct GlobalTxnRef { GTxnId gtxnid; GlobalTxn *ptr; } GlobalTxnRef; typedef struct GTxnBest { GTxnDD_Victim_Policy policy; /* * this is always the top priority. * */ uint32_t nbranches_killed; TxnBranch *most_branches_killed_gtxn; time_t min_start_ts; TxnBranch *min_start_gtxn; time_t max_start_ts; TxnBranch *max_start_gtxn; uint32_t min_nrows_changed; TxnBranch *min_nrows_chg_gtxn; uint32_t max_nrows_changed; TxnBranch *max_nrows_chg_gtxn; uint32_t max_nrows_locked; TxnBranch *max_nrows_locked_gtxn; /* Kill the txn branch whose global txn has most waiting(blocked) txn branches. Such a global can possibly be a bottleneck since it easy can be blocked by other txns, if it is killed, many txns won't be blocked by it. */ uint32_t max_waiting_branches; TxnBranch *most_waiting_branches_gtxn; /* Kill the txn branch whose global txn has most blocking txn branches, i.e. it's blocking most NO. of other txns. */ uint32_t max_blocking_branches; TxnBranch *most_blocking_branches_gtxn; } GTxnBest; /* * Stack element. the stack stores alternative graph nodes to do DFS traverse * later. each batch of pushed PathNode share a best candidate found so far. * When the PathNode is poped, the best_so_far is used as best candidate in the traverse. * */ typedef struct PathNode { TxnBranch *blocker; GTxnBest *best_so_far; bool single_shard_cycle; Oid cur_shardid; }PathNode; typedef struct Stack { PathNode *base; int top; // stack top element's index int capacity; } Stack; static void stack_push(Stack *stk, PathNode*pn) { Assert(stk && pn); if (stk->base == NULL) { stk->top = 0; stk->capacity = 32; stk->base = (PathNode*)MemoryContextAllocZero(gdd_stmts_memcxt, sizeof(PathNode) * stk->capacity); } if (stk->top == stk->capacity) { Size stkspc = sizeof(PathNode) * stk->capacity; stk->base = repalloc(stk->base, stkspc * 2); memset(((char*)stk->base) + stkspc, 0, stkspc); stk->capacity *= 2; } stk->base[stk->top++] = *pn; } /* * pop top element to 'top'. * @retval true if there is top element, false if stack is empty. * */ static bool stack_pop(Stack *stk, PathNode *top) { if (stk->top <= 0 || stk->base == NULL) return false; *top = stk->base[--stk->top]; return true; } inline static void print_gtxnid(StringInfo buf, const GTxnId*gt) { appendStringInfo(buf, "%u-%ld-%u", gt->compnodeid, gt->ts, gt->txnid); } static void InitBestCandidate(GTxnBest *best, GTxnDD_Victim_Policy policy) { best->policy = policy; best->min_start_ts = 0xffffffff; best->max_start_ts = 0; best->min_nrows_changed = 0xffffffff; best->max_nrows_changed = 0; best->max_nrows_locked = 0; best->nbranches_killed = 0; best->most_branches_killed_gtxn = NULL; best->min_start_gtxn = best->max_start_gtxn = NULL; best->min_nrows_chg_gtxn = best->max_nrows_chg_gtxn = NULL; best->max_nrows_locked_gtxn = NULL; } // See if gn is a better choice than 'best' by 'vp' policy, if so note down gn. static void UpdateCandidate(GTxnBest *best, TxnBranch *gn) { if (best->nbranches_killed < gn->owner->nbranches_killed) { best->nbranches_killed = gn->owner->nbranches_killed; best->most_branches_killed_gtxn = gn; } switch (best->policy) { case KILL_OLDEST: if (best->min_start_ts > gn->owner->start_ts) { best->min_start_ts = gn->owner->start_ts; best->min_start_gtxn = gn; } break; case KILL_YOUNGEST: if (best->max_start_ts < gn->owner->start_ts) { best->max_start_ts = gn->owner->start_ts; best->max_start_gtxn = gn; } break; case KILL_MOST_ROWS_CHANGED: if (best->min_nrows_changed > gn->owner->nrows_changed) { best->min_nrows_changed = gn->owner->nrows_changed; best->min_nrows_chg_gtxn = gn; } break; case KILL_LEAST_ROWS_CHANGED: if (best->max_nrows_changed < gn->owner->nrows_changed) { best->max_nrows_changed = gn->owner->nrows_changed; best->max_nrows_chg_gtxn = gn; } break; case KILL_MOST_ROWS_LOCKED: if (best->max_nrows_changed < gn->owner->nrows_changed) { best->max_nrows_locked = gn->owner->nrows_locked; best->max_nrows_locked_gtxn = gn; } break; case KILL_MOST_WAITING_BRANCHES: if (best->max_waiting_branches < gn->owner->nblockers) { best->max_waiting_branches = gn->owner->nblockers; best->most_waiting_branches_gtxn = gn; } break; case KILL_MOST_BLOCKING_BRANCHES: if (best->max_blocking_branches < gn->owner->num_blocked) { best->max_blocking_branches = gn->owner->num_blocked; best->most_blocking_branches_gtxn = gn; } break; default: // If g_gtxn_dd_victim_policy is modified (by client) while assigning // to 'vp' parameter, control could come here. We simply skip 'gn' for // candidate. best->policy = g_glob_txnmgr_deadlock_detector_victim_policy; break; } } static TxnBranch *GetGTDDVictim(GTxnBest *best) { TxnBranch *gn = NULL; switch (best->policy) { case KILL_OLDEST: gn = best->min_start_gtxn; break; case KILL_YOUNGEST: gn = best->max_start_gtxn; break; case KILL_MOST_ROWS_CHANGED: gn = best->min_nrows_chg_gtxn; break; case KILL_LEAST_ROWS_CHANGED: gn = best->max_nrows_chg_gtxn; break; case KILL_MOST_ROWS_LOCKED: gn = best->max_nrows_locked_gtxn; break; case KILL_MOST_WAITING_BRANCHES: gn = best->most_waiting_branches_gtxn; break; case KILL_MOST_BLOCKING_BRANCHES: gn = best->most_blocking_branches_gtxn; break; default: gn = NULL; break; } /* * Always kill the global txn whose most branches are killed, override any policy. * */ if (gn && gn->owner->nbranches_killed < best->nbranches_killed) { gn = best->most_branches_killed_gtxn; } return gn; } static HTAB *gtxn_waitgnodes = 0; static HTAB *g_txn_branch_hashtbl = 0; #define MAX_TXN_WAIT_GNODES 256 /* * if a global txn is used as victim, it should be used as victim in other cycles found. * */ typedef struct GlobalTxnSection { struct GlobalTxnSection *next; int end; GlobalTxn nodes[MAX_TXN_WAIT_GNODES]; } GlobalTxnSection; static GlobalTxnSection g_all_gnodes; static GlobalTxn *Alloc_gtxn() { GlobalTxn *ret = NULL; GlobalTxnSection *last_sect = NULL; for (GlobalTxnSection *sect = &g_all_gnodes; sect; sect = sect->next) { if (sect->end < MAX_TXN_WAIT_GNODES) { ret = sect->nodes + sect->end++; /* * ret may hold alloced arrays, they can be reused. * */ GlobalTxn tmp = *ret; memset(ret, 0, sizeof(*ret)); ret->blockers = tmp.blockers; ret->nblocker_slots = tmp.nblocker_slots; ret->branches = tmp.branches; ret->nbranch_slots = tmp.nbranch_slots; goto end; } last_sect = sect; } last_sect->next = MemoryContextAllocZero(gdd_memcxt, sizeof(GlobalTxnSection)); last_sect = last_sect->next; ret = last_sect->nodes + last_sect->end++; end: return ret; } #define MAX_TXN_BRANCHES 1024 typedef struct TxnBranchSection { struct TxnBranchSection *next; int end; TxnBranch nodes[MAX_TXN_BRANCHES]; } TxnBranchSection; static TxnBranchSection g_all_txn_branches; /* * At start of each round of deadlock detect, we should first call this to * clear the data collected in previous round. * */ static void ResetDeadlockDetectorState() { MemoryContextReset(gdd_stmts_memcxt); for (GlobalTxnSection *s = &g_all_gnodes; s; s = s->next) { s->end = 0; } hash_destroy(gtxn_waitgnodes); /* * create hashtable that indexes the gtxnid-> */ HASHCTL ctl; MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(GTxnId); ctl.entrysize = sizeof(GlobalTxnRef); gtxn_waitgnodes = hash_create("Global transaction wait-for graph node by global txn-id", 256, &ctl, HASH_ELEM | HASH_BLOBS); for (TxnBranchSection *s = &g_all_txn_branches; s; s = s->next) { s->end = 0; } MemSet(&ctl, 0, sizeof(ctl)); hash_destroy(g_txn_branch_hashtbl); ctl.keysize = sizeof(TxnBranchId); ctl.entrysize = sizeof(TxnBranchRef); g_txn_branch_hashtbl = hash_create("Global transaction wait-for graph txn branch nodes by txn-id", 1024, &ctl, HASH_ELEM | HASH_BLOBS); } static TxnBranch *Alloc_txn_branch() { TxnBranch *ret = NULL; TxnBranchSection *last_sect = NULL; for (TxnBranchSection *sect = &g_all_txn_branches; sect; sect = sect->next) { if (sect->end < MAX_TXN_BRANCHES) { ret = sect->nodes + sect->end++; memset(ret, 0, sizeof(*ret)); goto end; } last_sect = sect; } last_sect->next = MemoryContextAllocZero(gdd_memcxt, sizeof(TxnBranchSection)); last_sect = last_sect->next; ret = last_sect->nodes + last_sect->end++; end: return ret; } static TxnBranch *FindTxnBranch(TxnBranchId *txnid) { bool found = false; TxnBranchRef *tbref = hash_search(g_txn_branch_hashtbl, txnid, HASH_FIND, &found); if (!tbref) { Assert(!found); return NULL; } Assert(found && tbref->ptr); return tbref->ptr; } static GlobalTxn *FindGtxn(GTxnId *gtxnid) { bool found = false; if (!gtxnid) return NULL; GlobalTxnRef *gnref = hash_search(gtxn_waitgnodes, gtxnid, HASH_FIND, &found); if (!gnref) { Assert(!found); return NULL; } Assert(found && gnref->ptr); return gnref->ptr; } /* * Add txn branch to its global txn owner. * If the global txn doesn't exist yet, add it first. * */ static TxnBranch * add_global_txn_branch(GTxnId *gtxnid, Shard_id_t shardid, uint32_t mysql_connid, time_t start_ts, uint32_t nrows_changed, uint32_t nrows_locked) { GlobalTxn *gn = NULL; TxnBranchId txnid; Assert(gtxnid && shardid != 0 && mysql_connid != 0 && start_ts > 0 && nrows_changed > 0); gn = FindGtxn(gtxnid); if (gn) goto add_branch; gn = Alloc_gtxn(); gn->gtxnid = *gtxnid; gn->nblockers = 0; gn->visit_id = 0; gn->start_ts = start_ts; gn->nrows_changed = 0; // will add nrows_changed below. gn->nrows_locked = 0; gn->nbranches_killed = 0; if (gn->blockers == NULL) { Assert(gn->nblocker_slots == 0 && gn->nblockers == 0); gn->nblocker_slots = 8; gn->blockers = MemoryContextAllocZero(gdd_memcxt, gn->nblocker_slots * sizeof(void*)); } if (gn->branches == NULL) { Assert(gn->nbranch_slots == 0 && gn->nbranches == 0); gn->nbranch_slots = 8; gn->branches = MemoryContextAllocZero(gdd_memcxt, gn->nbranch_slots * sizeof(void*)); } bool found = false; GlobalTxnRef *gnref = hash_search(gtxn_waitgnodes, gtxnid, HASH_ENTER, &found); Assert(!found && gnref); gnref->ptr = gn; elog(gdd_log_level(), "On shard(%u) found global txn (%u-%lu-%u)", shardid, gtxnid->compnodeid, gtxnid->ts, gtxnid->txnid); add_branch: memset(&txnid, 0, sizeof(txnid)); txnid.gtxnid = *gtxnid; txnid.shardid = shardid; TxnBranch *tb = FindTxnBranch(&txnid); if (tb) return tb; if (gn->start_ts > start_ts) gn->start_ts = start_ts; gn->nrows_changed += nrows_changed; gn->nrows_locked += nrows_locked; tb = Alloc_txn_branch(); tb->owner = gn; tb->waiting_shardid = shardid; tb->mysql_connid = mysql_connid; tb->killed_dd = false; TxnBranchRef *tbref = hash_search(g_txn_branch_hashtbl, &txnid, HASH_ENTER, &found); Assert(!found && tbref); tbref->ptr = tb; tb->tbid = txnid; /* * Add new branch 'tb' into gn->branches array, expand the array if no enough space. * */ if (gn->nbranches == gn->nbranch_slots) { gn->branches = repalloc(gn->branches, gn->nbranch_slots * 2 * sizeof(void*)); memset(gn->branches + gn->nbranch_slots, 0, gn->nbranch_slots * sizeof(void*)); gn->nbranch_slots *= 2; } gn->branches[gn->nbranches++] = tb; elog(gdd_log_level(), "On shard(%u) found txn branch(%d) of global txn (%u-%lu-%u)", shardid, gn->nbranches, gtxnid->compnodeid, gtxnid->ts, gtxnid->txnid); return tb; } static void MakeWaitFor(GlobalTxn *waiter, TxnBranch *blocker) { if (waiter->nblockers == waiter->nblocker_slots) { waiter->blockers = repalloc(waiter->blockers, waiter->nblocker_slots * 2 * sizeof(void*)); memset(waiter->blockers + waiter->nblocker_slots, 0, waiter->nblocker_slots * sizeof(void*)); waiter->nblocker_slots *= 2; } blocker->owner->num_blocked++; waiter->blockers[waiter->nblockers++] = blocker; } static inline void set_gtxnid(const char *gtxnid_str, GTxnId *gtxnid) { sscanf(gtxnid_str, "'%u-%lu-%u'", &gtxnid->compnodeid, &gtxnid->ts, &gtxnid->txnid); } void gdd_init() { /* * Initialization of needed modules and objects. * * make sure cache memory context exists */ if (!CacheMemoryContext) CreateCacheMemoryContext(); if (!gdd_memcxt) gdd_memcxt = AllocSetContextCreate(TopMemoryContext, "Global Deadlock Detector Memory Context", ALLOCSET_DEFAULT_SIZES); if (!gdd_stmts_memcxt) gdd_stmts_memcxt = AllocSetContextCreate(gdd_memcxt, "Global Deadlock Detector Memory Context for SQL Statements", ALLOCSET_DEFAULT_SIZES); ShardCacheInit(); InitShardingSession(); } /* * @retval true if need to traverse the wait-for graph for deadlocks and resolve them if any; * false if no such need because there is only one shard used. * */ static bool build_wait_for_graph() { static const char *query_wait = "SELECT waiter.trx_xid as waiter_xa_id, waiter.trx_mysql_thread_id as waiter_conn_id," "unix_timestamp(waiter.trx_started) as waiter_start_ts," "waiter.trx_rows_modified as waiter_nrows_changed, waiter.trx_rows_locked as waiter_nrows_locked," "blocker.trx_xid as blocker_xa_id, blocker.trx_mysql_thread_id as blocker_conn_id," "unix_timestamp(blocker.trx_started) as blocker_start_ts," "blocker.trx_rows_modified as blocker_nrows_changed, blocker.trx_rows_locked as blocker_nrows_locked " "FROM performance_schema.data_lock_waits as lock_info JOIN " " information_schema.innodb_trx as waiter JOIN " " information_schema.innodb_trx as blocker " "ON lock_info.REQUESTING_ENGINE_TRANSACTION_ID = waiter.trx_id AND " " lock_info.BLOCKING_ENGINE_TRANSACTION_ID = blocker.trx_id AND " " waiter.trx_xa_type = 'external' and blocker.trx_xa_type = 'external' AND " " waiter.trx_state='LOCK WAIT' AND (blocker.trx_state='RUNNING' OR blocker.trx_state='LOCK WAIT')"; static int qlen_wait = 0; if (qlen_wait == 0) qlen_wait = strlen(query_wait); Shard_ref_t *ptr; HASH_SEQ_STATUS seqstat; ResetCommunicationHub(); size_t nshards = startShardCacheSeq(&seqstat); if (nshards == 1) { hash_seq_term(&seqstat); return false; } /* * build the wait-for graph. * */ int shardidx = 0; bool gdd_supported = true; while ((ptr = hash_seq_search(&seqstat)) != NULL) { AsyncStmtInfo *asi = NULL; PG_TRY(); { asi = GetAsyncStmtInfo(ptr->id); if (shardidx == 0 && !(gdd_supported = check_gdd_supported(asi))) break; shardidx++; } PG_CATCH(); { /* Get rid of the exception, log it to server log only to free error stack space. Do not abort the current pg txn, keep running in it. it's not pg error that the mysql node can't be reached. */ HOLD_INTERRUPTS(); //EmitErrorReport(); //AbortOutOfAnyTransaction(); downgrade_error(); errfinish(0); FlushErrorState(); RESUME_INTERRUPTS(); elog(DEBUG1, "GDD: Skipping shard (%s, %u) when building wait-for graph because its master %u isn't available for now.", ptr->ptr->name.data, ptr->id, ptr->ptr->master_node_id); } PG_END_TRY(); if (asi) append_async_stmt(asi, query_wait, qlen_wait, CMD_SELECT, false, SQLCOM_SELECT); else // This shard has no known master node, so it can't be written // anyway and it's safe to skip it for now. nshards--; } if (!gdd_supported) return false; enable_remote_timeout(); send_multi_stmts_to_multi(); size_t num_asis = GetAsyncStmtInfoUsed(); //Assert(num_asis == nshards); this could fail if a shard suddenly has no master. /* * Receive results and build graph nodes. * */ for (size_t i = 0; i < num_asis; i++) { CHECK_FOR_INTERRUPTS(); AsyncStmtInfo *asi = GetAsyncStmtInfoByIndex(i); // If shard master unavailable, handle this shard in next round. if (!ASIConnected(asi)) continue; MYSQL_RES *mres = asi->mysql_res; GTxnId gtxnid; TxnBranchId txnid_blocker; memset(&txnid_blocker, 0, sizeof(txnid_blocker)); if (mres == NULL) { elog(DEBUG1, "GDD: NULL results of wait-for relationship from shard.node(%u.%u).", asi->shard_id, asi->node_id); free_mysql_result(asi); continue; } do { MYSQL_ROW row = mysql_fetch_row(mres); if (row == NULL) { check_mysql_fetch_row_status(asi); free_mysql_result(asi); break; } if (row[0] == NULL || row[1] == NULL || row[2] == NULL || row[3] == NULL || row[4] == NULL || row[5] == NULL || row[6] == NULL || row[7] == NULL || row[8] == NULL || row[9] == NULL) { elog(WARNING, "GDD: Invalid rows fetched from i_s.innodb_trx of shard.node(%u.%u): NULL field(s) in NOT NULL column(s).", asi->shard_id, asi->node_id); free_mysql_result(asi); break; } // store waiter info set_gtxnid(row[0], &gtxnid); char *endptr = NULL; /* * Although the i_s.innodb_trx defines its connection_id column * as bigint unsigned, in MySQL the my_thread_id type is uint32_t, * so conn_id is in (0, UINT_MAX) for sure. * */ uint64_t conn_id = strtoull(row[1], &endptr, 10); uint64_t start_ts = strtoull(row[2], &endptr, 10); uint64_t nrows_locked = strtoull(row[3], &endptr, 10); uint64_t nrows_changed = strtoull(row[4], &endptr, 10); Assert(conn_id <= UINT_MAX && start_ts <= UINT_MAX && nrows_locked <= UINT_MAX && nrows_changed <= UINT_MAX); add_global_txn_branch(&gtxnid, asi->shard_id, conn_id, start_ts, nrows_changed, nrows_locked); // store blocker info set_gtxnid(row[5], &txnid_blocker.gtxnid); /* * Although the i_s.innodb_trx defines its connection_id column * as bigint unsigned, in MySQL the my_thread_id type is uint32_t, * so conn_id is in (0, UINT_MAX) for sure. * */ conn_id = strtoull(row[6], &endptr, 10); start_ts = strtoull(row[7], &endptr, 10); nrows_locked = strtoull(row[8], &endptr, 10); nrows_changed = strtoull(row[9], &endptr, 10); Assert(conn_id <= UINT_MAX && start_ts <= UINT_MAX && nrows_locked <= UINT_MAX && nrows_changed <= UINT_MAX); add_global_txn_branch(&txnid_blocker.gtxnid, asi->shard_id, conn_id, start_ts, nrows_changed, nrows_locked); txnid_blocker.shardid = asi->shard_id; /* * We have to fetch active xa txns before fetching wait-for relationship, * otherwise we don't have global txns to set up the wait-for relationship. * */ GlobalTxn *gt_waiter = FindGtxn(&gtxnid); TxnBranch *tb_blocker = FindTxnBranch(&txnid_blocker); /* * local txn branch wait-for can only happen on the same shard. * */ if (gt_waiter && tb_blocker) { elog(gdd_log_level(), "On shard(%u) found (%u-%lu-%u) waiting for (%u-%lu-%u)", txnid_blocker.shardid, gtxnid.compnodeid, gtxnid.ts, gtxnid.txnid, txnid_blocker.gtxnid.compnodeid, txnid_blocker.gtxnid.ts, txnid_blocker.gtxnid.txnid); MakeWaitFor(gt_waiter, tb_blocker); } } while (true); } disable_remote_timeout(); return true/*GDD supported*/; } /* * kill 'best' choice according to user set standards. Kill all branches * at once since a global txn have to be aborted when any of its branch is * aborted. */ static void kill_victim(GTxnBest *best) { TxnBranch *tb = GetGTDDVictim(best); if (!tb) return; GlobalTxn *gt = tb->owner; StringInfoData str; initStringInfo2(&str, 256, gdd_stmts_memcxt); appendStringInfoString(&str, "Global deadlock detector found a deadlock and killed the victim(gtxnid: "); print_gtxnid(&str, &gt->gtxnid); appendStringInfoString(&str, "). Killed txn branches (shardid, connection-id):"); /* * TODO: Some of the txn branches may have finished the query, i.e. there is no * blocked query to kill. * */ for (int i = 0; i < gt->nbranches; i++) { TxnBranch *gn = gt->branches[i]; AsyncStmtInfo *asi = GetAsyncStmtInfo(gn->waiting_shardid); size_t stmtlen = 64; char *stmt = MemoryContextAlloc(gdd_stmts_memcxt, stmtlen); Assert(gn->mysql_connid != 0); int slen = snprintf(stmt, stmtlen, "kill query %d", gn->mysql_connid); Assert(slen < stmtlen); append_async_stmt(asi, stmt, slen, CMD_UTILITY, false, SQLCOM_KILL); gn->killed_dd = true; appendStringInfo(&str, " (%u, %u)", gn->waiting_shardid, gn->mysql_connid); } gt->nbranches_killed = gt->nbranches; elog(LOG, "Global deadlock detector: %s", str.data); } inline static uint64 GRF_TRVS_MASK(uint32 isect, uint32 i) { uint64 ret = isect; ret <<= 32; ret |= (i+1); return ret; } static void find_and_resolve_global_deadlock() { uint32 isect = 0; GTxnDD_Victim_Policy victim_policy = g_glob_txnmgr_deadlock_detector_victim_policy; Stack stk; memset(&stk, 0, sizeof(stk)); for (GlobalTxnSection *gs = &g_all_gnodes; gs; gs = gs->next, isect++) { Assert(isect < UINT_MAX && gs->end < UINT_MAX); for (int i = 0; i < gs->end; i++) { CHECK_FOR_INTERRUPTS(); Shard_id_t cur_shardid = Invalid_shard_id; bool single_shard_cycle = true; GlobalTxn *gn = gs->nodes + i; GTxnBest best, *pbest = NULL; InitBestCandidate(&best, victim_policy); StringInfoData gddlog; initStringInfo2(&gddlog, 1024, gdd_stmts_memcxt); pbest = &best; /* * One round of traverse, starting from gn. All nodes accessible * will all be visited if they are not yet so. Since the * wait-for graph is a directed graph, part of the nodes may not * be accessible in this round of traverse, and they will be visited in * next round with a different starting point 'gn'. * */ do { PathNode pnode; bool hasit = false; CHECK_FOR_INTERRUPTS(); /* * all wait-for cycles having a gn node that was killed already, * are no longer cyclic, such deadlocks are all resolved, so * stop traversing. * */ if (gn->nbranches_killed > 0) goto dfs_next; if (gn->visit_id == 0) { /* * Consider whether any of the txn branches gn waits for * should be killed, i.e. to visit it. * */ gn->visit_id = GRF_TRVS_MASK(isect, i); // LOG level is special, it's high for elog/ereport, but has a low number. #define SHOULD_LOG (log_min_messages <= gdd_log_level() || gdd_log_level() == LOG) if (SHOULD_LOG) appendStringInfo(&gddlog, "gdd visit (%lu) gtxn(%u-%ld-%u) %s", gn->visit_id, gn->gtxnid.compnodeid, gn->gtxnid.ts, gn->gtxnid.txnid, gn->nblockers > 1 ? "push alt paths to stack:": ""); /* * Push the rest blockers if any to stack for DFS traverse later. * dup the best candidate found so far for the blockers, we * will use the cached best * when we pop a blocker out to resume our search. */ GTxnBest *pbest_dup = NULL; if (gn->nblockers > 1) { pbest_dup = (GTxnBest *)MemoryContextAllocZero(gdd_stmts_memcxt, sizeof(GTxnBest)); *pbest_dup = *pbest; } for (int i = 1; i < gn->nblockers; i++) { PathNode pnd; pnd.blocker = gn->blockers[i]; Assert(pnd.blocker); pnd.best_so_far = pbest_dup; pnd.cur_shardid = cur_shardid; pnd.single_shard_cycle = single_shard_cycle; stack_push(&stk, &pnd); if (SHOULD_LOG) appendStringInfo(&gddlog, "(%u, %u) of (%u-%ld-%u); ", pnd.blocker->waiting_shardid, pnd.blocker->mysql_connid, pnd.blocker->owner->gtxnid.compnodeid, pnd.blocker->owner->gtxnid.ts, pnd.blocker->owner->gtxnid.txnid); } elog(gdd_log_level(), "%s", gddlog.data); resetStringInfo(&gddlog); if (gn->nblockers > 0) { UpdateCandidate(pbest, gn->blockers[0]); if (cur_shardid == Invalid_shard_id) cur_shardid = gn->blockers[0]->tbid.shardid; else if (cur_shardid != gn->blockers[0]->tbid.shardid) single_shard_cycle = false; gn = gn->blockers[0]->owner; continue; } // else pop nodes in stack to continue the DFS traverse. } else if (gn->visit_id == GRF_TRVS_MASK(isect, i)) { /* * A cycle is found, if it's not in a single shard node, * kill the chosen victim gn. note that gn can be a global * txn started by another computing node, so we have no stats * like 'startup time' or 'NO. of rows changed' here, * thus do such a simple kill. */ elog(gdd_log_level(), "gdd visit (%lu) : at gtxn(%u-%ld-%u) found a %s wait-for cycle%s.", gn->visit_id, gn->gtxnid.compnodeid, gn->gtxnid.ts, gn->gtxnid.txnid, single_shard_cycle ? "single shard" : "", single_shard_cycle ? ", it is left for local shard node to resolve" : ", victim will be killed"); if (!single_shard_cycle) kill_victim(pbest); //goto dfs_next; } else { //goto dfs_next; } dfs_next: hasit = stack_pop(&stk, &pnode); if (!hasit) break; TxnBranch *tb = pnode.blocker; gn = tb->owner; elog(gdd_log_level(), "gdd visit (%lu) : pop stack: (%u, %u) branch of gtxn(%u-%ld-%u)", gn->visit_id, tb->waiting_shardid, tb->mysql_connid, gn->gtxnid.compnodeid, gn->gtxnid.ts, gn->gtxnid.txnid); // We are starting another candidate path from the diverging // point. use the cached best candidate, it's the best up to // the diverging point. pbest = pnode.best_so_far; cur_shardid = pnode.cur_shardid; single_shard_cycle = pnode.single_shard_cycle; if (cur_shardid == Invalid_shard_id) cur_shardid = tb->waiting_shardid; else if (cur_shardid != tb->waiting_shardid) single_shard_cycle = false; UpdateCandidate(pbest, tb); } while (gn); } } enable_remote_timeout(); send_multi_stmts_to_multi(); disable_remote_timeout(); if (stk.base) pfree(stk.base); } /* * Do one round of deadlock detection. * */ void perform_deadlock_detect() { if (!enable_global_deadlock_detection) return; elog(gdd_log_level(), "Performing one round of global deadlock detection on %d requests.", g_gdd_state->num_reqs); g_gdd_state->num_reqs = 0; g_gdd_state->when_last_gdd = time(0); sigjmp_buf pdd_local_sigjmp_buf, *old_sjb = NULL; if (sigsetjmp(pdd_local_sigjmp_buf, 1) != 0) { /* Since not using PG_TRY, must reset error stack by hand */ error_context_stack = NULL; /* Prevent interrupts while cleaning up */ HOLD_INTERRUPTS(); /* Report the error to the server log EmitErrorReport(); done in errfinish(0) */ /* * Need to downgrade the elevel to WARNING for errfinish(0) to pop * error stack top. NOTE that we can do this because all functions * called in this function don't touch shared memory or any pg tables, * all operations are purely performed in current process's private * address space. If shared memory is accessed and error occurs in the * while, all other pg processes can be impacted. * */ downgrade_error(); errfinish(0); AbortCurrentTransaction(); LWLockReleaseAll(); AbortBufferIO(); UnlockBuffers(); if (CurrentResourceOwner) { ResourceOwnerRelease(CurrentResourceOwner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true); /* we needn't bother with the other ResourceOwnerRelease phases */ } AtEOXact_Buffers(false); AtEOXact_SMgr(); AtEOXact_Files(false); AtEOXact_HashTables(false); MemoryContextSwitchTo(gdd_stmts_memcxt); FlushErrorState(); PG_exception_stack = old_sjb; /* * In a background process, we can't rethrow here, it must keep running. * So we must do proper cleanup and get rid of the error. * */ ResetCommunicationHubStmt(false); MemoryContextResetAndDeleteChildren(gdd_stmts_memcxt); RESUME_INTERRUPTS(); /* * Sleep at least 1 second after any error. We don't want to be * filling the error logs as fast as we can. */ pg_usleep(1000000L); return; } /* We can now handle ereport(ERROR) */ old_sjb = PG_exception_stack; PG_exception_stack = &pdd_local_sigjmp_buf; ResetDeadlockDetectorState(); SetCurrentStatementStartTimestamp(); /* Both build_wait_for_graph() and kill_victim() needs master info. they should be in a txn, or in seperate txns (more prompt). */ Assert(!IsTransactionState()); StartTransactionCommand(); SPI_connect(); PushActiveSnapshot(GetTransactionSnapshot()); bool gdd_supported; if ((gdd_supported = build_wait_for_graph())) { CHECK_FOR_INTERRUPTS(); find_and_resolve_global_deadlock(); } /* Can't do this before the scan finishes. */ SPI_finish(); PopActiveSnapshot(); CommitTransactionCommand(); if (!gdd_supported) sleep(10000); } static bool check_gdd_supported(AsyncStmtInfo *asi) { bool ret = false; char *verstr = get_storage_node_version(asi); if (!verstr) { elog(WARNING, "GDD: Can't get storage node version from shard.node(%u.%u), won't perform GDD.", asi->shard_id, asi->node_id); return false; } if (strcasestr(verstr, "kunlun-storage")) ret = true; else elog(LOG, "GDD: Not using kunlun-storage as storage nodes, won't perform GDD."); pfree(verstr); return ret; } /* All storage nodes in a Kunlun cluster must be of same version, so it's OK to connect to any shard node for such a check. */ static char*get_storage_node_version(AsyncStmtInfo *asi) { const char *stmt = "select version()"; append_async_stmt(asi, stmt, strlen(stmt), CMD_SELECT, false, SQLCOM_SELECT); enable_remote_timeout(); send_multi_stmts_to_multi(); MYSQL_RES *mres = asi->mysql_res; char *verstr = NULL; if (mres == NULL) goto end; MYSQL_ROW row = mysql_fetch_row(mres); if (row == NULL) { check_mysql_fetch_row_status(asi); goto end; } verstr = pstrdup(row[0]); end: free_mysql_result(asi); return verstr; }
27.831475
223
0.685641
[ "object" ]
2c303da4a3f46913510e828f95bd714c34535d86
2,837
h
C
Source/DynamicalModels/InternalForceModel/imstkStVKForceModel.h
Kitware/iMSTK
fa84907c77c524a45c126d836f15275d76648be6
[ "Apache-2.0" ]
15
2021-09-20T17:33:52.000Z
2022-02-12T09:49:57.000Z
Source/DynamicalModels/InternalForceModel/imstkStVKForceModel.h
Kitware/iMSTK
fa84907c77c524a45c126d836f15275d76648be6
[ "Apache-2.0" ]
null
null
null
Source/DynamicalModels/InternalForceModel/imstkStVKForceModel.h
Kitware/iMSTK
fa84907c77c524a45c126d836f15275d76648be6
[ "Apache-2.0" ]
3
2021-10-06T19:55:41.000Z
2022-02-17T21:59:16.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic Institute. 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.txt 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 "imstkInternalForceModel.h" #include <StVKStiffnessMatrix.h> namespace vega { class StvkInternalForces; class VolumetricMesh; } // namespace vega namespace imstk { /// /// \class StvkForceModel /// /// \brief /// class StvkForceModel : public InternalForceModel { public: StvkForceModel(std::shared_ptr<vega::VolumetricMesh> mesh, const bool withGravity = true, const double gravity = 10.0); ~StvkForceModel() override = default; /// /// \brief Get the internal force /// inline void getInternalForce(const Vectord& u, Vectord& internalForce) override { double* data = const_cast<double*>(u.data()); m_stVKInternalForces->ComputeForces(data, internalForce.data()); } /// /// \brief Get the tangent stiffness matrix topology /// inline void getTangentStiffnessMatrixTopology(vega::SparseMatrix** tangentStiffnessMatrix) override { m_vegaStVKStiffnessMatrix->GetStiffnessMatrixTopology(tangentStiffnessMatrix); } /// /// \brief Set the tangent stiffness matrix /// inline void getTangentStiffnessMatrix(const Vectord& u, SparseMatrixd& tangentStiffnessMatrix) override { double* data = const_cast<double*>(u.data()); m_vegaStVKStiffnessMatrix->ComputeStiffnessMatrix(data, m_vegaTangentStiffnessMatrix.get()); InternalForceModel::updateValuesFromMatrix(m_vegaTangentStiffnessMatrix, tangentStiffnessMatrix.valuePtr()); } /// /// \brief Speficy tangent stiffness matrix /// inline void setTangentStiffness(std::shared_ptr<vega::SparseMatrix> K) override { m_vegaTangentStiffnessMatrix = K; } protected: std::shared_ptr<vega::StVKInternalForces> m_stVKInternalForces; std::shared_ptr<vega::SparseMatrix> m_vegaTangentStiffnessMatrix; std::shared_ptr<vega::StVKStiffnessMatrix> m_vegaStVKStiffnessMatrix; bool ownStiffnessMatrix; }; } // namespace imstk
31.876404
116
0.681354
[ "mesh" ]
2c30b0c78e38cafc8c7ac98fc9b98275d0deede2
4,270
c
C
gtk/src/rbgtktreerowreference.c
pkorenev/ruby-gnome2
08011d8535529a3866f877817f29361b1b0703d7
[ "Ruby" ]
2
2016-05-08T20:57:12.000Z
2017-07-28T21:00:42.000Z
gtk/src/rbgtktreerowreference.c
pkorenev/ruby-gnome2
08011d8535529a3866f877817f29361b1b0703d7
[ "Ruby" ]
null
null
null
gtk/src/rbgtktreerowreference.c
pkorenev/ruby-gnome2
08011d8535529a3866f877817f29361b1b0703d7
[ "Ruby" ]
2
2016-07-23T09:53:08.000Z
2021-07-13T07:21:05.000Z
/* -*- c-file-style: "ruby"; indent-tabs-mode: nil -*- */ /************************************************ rbgtktreerowreference.c - $Author: mutoh $ $Date: 2006/10/21 16:58:00 $ Copyright (C) 2002-2006 Masao Mutoh ************************************************/ #include "global.h" /*****************************************/ #ifndef GTK_TYPE_TREE_ROW_REFERENCE static GtkTreeRowReference* treerowref_copy(ref) const GtkTreeRowReference* ref; { return (GtkTreeRowReference*)ref; } GType rbgtk_tree_row_reference_get_type() { static GType our_type = 0; if (our_type == 0) our_type = g_boxed_type_register_static ("GtkTreeRowReference", (GBoxedCopyFunc)treerowref_copy, (GBoxedFreeFunc)gtk_tree_row_reference_free); return our_type; } GtkTreeRowReference * rbgtk_get_tree_row_reference(obj) VALUE obj; { return (GtkTreeRowReference*)RVAL2BOXED(obj, GTK_TYPE_TREE_ROW_REFERENCE); } #endif /*****************************************/ #define _SELF(s) RVAL2TREEROWREFERENCE(s) /*****************************************/ static ID id_proxy; static ID id_model; static ID id_path; static VALUE treerowref_initialize(argc, argv, self) int argc; VALUE* argv; VALUE self; { VALUE proxy, model, path; GtkTreeRowReference* ref; if (argc == 3){ rb_scan_args(argc, argv, "3", &proxy, &model, &path); G_CHILD_SET(self, id_proxy, proxy); ref = gtk_tree_row_reference_new_proxy(RVAL2GOBJ(proxy), GTK_TREE_MODEL(RVAL2GOBJ(model)), RVAL2GTKTREEPATH(path)); } else { rb_scan_args(argc, argv, "2", &model, &path); ref = gtk_tree_row_reference_new(GTK_TREE_MODEL(RVAL2GOBJ(model)), RVAL2GTKTREEPATH(path)); } if (ref == NULL) rb_raise(rb_eArgError, "Invalid arguments were passed."); G_CHILD_SET(self, id_model, model); G_CHILD_SET(self, id_path, path); G_INITIALIZE(self, ref); return Qnil; } static VALUE treerowref_get_path(self) VALUE self; { VALUE ret = GTKTREEPATH2RVAL(gtk_tree_row_reference_get_path(_SELF(self))); G_CHILD_SET(self, id_path, ret); return ret; } #if GTK_CHECK_VERSION(2,8,0) static VALUE treerowref_get_model(self) VALUE self; { VALUE ret = GOBJ2RVAL(gtk_tree_row_reference_get_model(_SELF(self))); G_CHILD_SET(self, id_model, ret); return ret; } #endif static VALUE treerowref_valid(self) VALUE self; { return CBOOL2RVAL(gtk_tree_row_reference_valid(_SELF(self))); } static VALUE treerowref_s_inserted(self, proxy, path) VALUE self, proxy, path; { gtk_tree_row_reference_inserted(RVAL2GOBJ(proxy), RVAL2GTKTREEPATH(path)); return self; } static VALUE treerowref_s_deleted(self, proxy, path) VALUE self, proxy, path; { gtk_tree_row_reference_deleted(RVAL2GOBJ(proxy), RVAL2GTKTREEPATH(path)); return self; } static VALUE treerowref_s_reordered(self, proxy, path, iter, new_orders) VALUE self, proxy, path, iter, new_orders; { gint i, len; gint* orders; Check_Type(new_orders, T_ARRAY); len = RARRAY_LEN(new_orders); orders = ALLOCA_N(gint, len); for (i = 0; i < len; i++) { orders[i] = RARRAY_PTR(new_orders)[i]; } gtk_tree_row_reference_reordered(RVAL2GOBJ(proxy), RVAL2GTKTREEPATH(path), RVAL2GTKTREEITER(iter), orders); return self; } void Init_gtk_treerowreference() { id_proxy = rb_intern("proxy"); id_model = rb_intern("model"); id_path = rb_intern("path"); VALUE gTreeref = G_DEF_CLASS(GTK_TYPE_TREE_ROW_REFERENCE, "TreeRowReference", mGtk); rb_define_method(gTreeref, "initialize", treerowref_initialize, -1); rb_define_method(gTreeref, "path", treerowref_get_path, 0); #if GTK_CHECK_VERSION(2,8,0) rb_define_method(gTreeref, "model", treerowref_get_model, 0); #endif rb_define_method(gTreeref, "valid?", treerowref_valid, 0); rb_define_singleton_method(gTreeref, "inserted", treerowref_s_inserted, 2); rb_define_singleton_method(gTreeref, "deleted", treerowref_s_deleted, 2); rb_define_singleton_method(gTreeref, "reordered", treerowref_s_reordered, 4); }
25.266272
88
0.649649
[ "model" ]
2c3599dddc01e0dba60a1b9a229175459594f2d1
4,250
h
C
Pods/Parse/Parse/PFObject+Subclass.h
Cessation/Even.tr
8f426c980fe920af4bfcff2e6729bc8155026203
[ "Apache-2.0" ]
122
2017-02-25T23:59:44.000Z
2022-02-22T19:15:11.000Z
Pods/Parse/Parse/PFObject+Subclass.h
Cessation/Even.tr
8f426c980fe920af4bfcff2e6729bc8155026203
[ "Apache-2.0" ]
16
2016-04-18T16:20:23.000Z
2016-05-04T16:18:08.000Z
Pods/Parse/Parse/PFObject+Subclass.h
Cessation/Even.tr
8f426c980fe920af4bfcff2e6729bc8155026203
[ "Apache-2.0" ]
53
2017-01-31T12:02:12.000Z
2021-03-21T05:52:06.000Z
/** * Copyright (c) 2015-present, Parse, LLC. * 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. */ #import <Foundation/Foundation.h> #import <Parse/PFObject.h> @class PFQuery<PFGenericObject : PFObject *>; NS_ASSUME_NONNULL_BEGIN /** ### Subclassing Notes Developers can subclass `PFObject` for a more native object-oriented class structure. Strongly-typed subclasses of `PFObject` must conform to the `PFSubclassing` protocol and must call `PFSubclassing.+registerSubclass` before `Parse.+setApplicationId:clientKey:` is called. After this it will be returned by `PFQuery` and other `PFObject` factories. All methods in `PFSubclassing` except for `PFSubclassing.+parseClassName` are already implemented in the `PFObject(Subclass)` category. Including `PFObject+Subclass.h` in your implementation file provides these implementations automatically. Subclasses support simpler initializers, query syntax, and dynamic synthesizers. The following shows an example subclass: \@interface MYGame : PFObject <PFSubclassing> // Accessing this property is the same as objectForKey:@"title" @property (nonatomic, copy) NSString *title; + (NSString *)parseClassName; @end @implementation MYGame @dynamic title; + (NSString *)parseClassName { return @"Game"; } @end MYGame *game = [[MYGame alloc] init]; game.title = @"Bughouse"; [game saveInBackground]; */ @interface PFObject (Subclass) ///-------------------------------------- #pragma mark - Methods for Subclasses ///-------------------------------------- /** Creates an instance of the registered subclass with this class's `PFSubclassing.+parseClassName`. This helps a subclass ensure that it can be subclassed itself. For example, `[PFUser object]` will return a `MyUser` object if `MyUser` is a registered subclass of `PFUser`. For this reason, `[MyClass object]` is preferred to `[[MyClass alloc] init]`. This method can only be called on subclasses which conform to `PFSubclassing`. A default implementation is provided by `PFObject` which should always be sufficient. */ + (instancetype)object; /** Creates a reference to an existing `PFObject` for use in creating associations between `PFObjects`. Calling `dataAvailable` on this object will return `NO` until `-fetchIfNeeded` or `-fetch` has been called. This method can only be called on subclasses which conform to `PFSubclassing`. A default implementation is provided by `PFObject` which should always be sufficient. No network request will be made. @param objectId The object id for the referenced object. @return An instance of `PFObject` without data. */ + (instancetype)objectWithoutDataWithObjectId:(nullable NSString *)objectId; /** Registers an Objective-C class for Parse to use for representing a given Parse class. Once this is called on a `PFObject` subclass, any `PFObject` Parse creates with a class name that matches `[self parseClassName]` will be an instance of subclass. This method can only be called on subclasses which conform to `PFSubclassing`. A default implementation is provided by `PFObject` which should always be sufficient. */ + (void)registerSubclass; /** Returns a query for objects of type `PFSubclassing.+parseClassName`. This method can only be called on subclasses which conform to `PFSubclassing`. A default implementation is provided by `PFObject` which should always be sufficient. @see `PFQuery` */ + (nullable PFQuery *)query; /** Returns a query for objects of type `PFSubclassing.+parseClassName` with a given predicate. A default implementation is provided by `PFObject` which should always be sufficient. @warning This method can only be called on subclasses which conform to `PFSubclassing`. @param predicate The predicate to create conditions from. @return An instance of `PFQuery`. @see `PFQuery.+queryWithClassName:predicate:` */ + (nullable PFQuery *)queryWithPredicate:(nullable NSPredicate *)predicate; @end NS_ASSUME_NONNULL_END
33.464567
111
0.738824
[ "object" ]
2c373510e15eabd7d853453ab089883b4afc5dbb
27,303
c
C
ext/phalcon/loader.zep.c
dschissler/cphalcon
171b6cda908154c96e4358a75707a668b2346323
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
null
null
null
ext/phalcon/loader.zep.c
dschissler/cphalcon
171b6cda908154c96e4358a75707a668b2346323
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
null
null
null
ext/phalcon/loader.zep.c
dschissler/cphalcon
171b6cda908154c96e4358a75707a668b2346323
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
null
null
null
#ifdef HAVE_CONFIG_H #include "../ext_config.h" #endif #include <php.h> #include "../php_ext.h" #include "../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/operators.h" #include "kernel/object.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "ext/spl/spl_exceptions.h" #include "kernel/fcall.h" #include "kernel/array.h" #include "kernel/require.h" #include "kernel/string.h" #include "kernel/concat.h" /** * This file is part of the Phalcon Framework. * * (c) Phalcon Team <team@phalconphp.com> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ /** * Phalcon\Loader * * This component helps to load your project classes automatically based on some conventions * *<code> * use Phalcon\Loader; * * // Creates the autoloader * $loader = new Loader(); * * // Register some namespaces * $loader->registerNamespaces( * [ * "Example\\Base" => "vendor/example/base/", * "Example\\Adapter" => "vendor/example/adapter/", * "Example" => "vendor/example/", * ] * ); * * // Register autoloader * $loader->register(); * * // Requiring this class will automatically include file vendor/example/adapter/Some.php * $adapter = new \Example\Adapter\Some(); *</code> */ ZEPHIR_INIT_CLASS(Phalcon_Loader) { ZEPHIR_REGISTER_CLASS(Phalcon, Loader, phalcon, loader, phalcon_loader_method_entry, 0); zend_declare_property_null(phalcon_loader_ce, SL("_eventsManager"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_foundPath"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_checkedPath"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_classes"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_extensions"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_namespaces"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_directories"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_loader_ce, SL("_files"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_loader_ce, SL("_registered"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(phalcon_loader_ce, SL("fileCheckingCallback"), "is_file", ZEND_ACC_PROTECTED TSRMLS_CC); phalcon_loader_ce->create_object = zephir_init_properties_Phalcon_Loader; zend_class_implements(phalcon_loader_ce TSRMLS_CC, 1, phalcon_events_eventsawareinterface_ce); return SUCCESS; } /** * Sets the file check callback. * * <code> * // Default behavior. * $loader->setFileCheckingCallback("is_file"); * * // Faster than `is_file()`, but implies some issues if * // the file is removed from the filesystem. * $loader->setFileCheckingCallback("stream_resolve_include_path"); * * // Do not check file existence. * $loader->setFileCheckingCallback(null); * </code> */ PHP_METHOD(Phalcon_Loader, setFileCheckingCallback) { zval *callback = NULL, callback_sub, __$null, _0$$4; zval *this_ptr = getThis(); ZVAL_UNDEF(&callback_sub); ZVAL_NULL(&__$null); ZVAL_UNDEF(&_0$$4); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 1, &callback); if (!callback) { callback = &callback_sub; callback = &__$null; } if (EXPECTED(zephir_is_callable(callback TSRMLS_CC))) { zephir_update_property_zval(this_ptr, SL("fileCheckingCallback"), callback); } else if (Z_TYPE_P(callback) == IS_NULL) { ZEPHIR_INIT_VAR(&_0$$4); ZEPHIR_INIT_NVAR(&_0$$4); zephir_create_closure_ex(&_0$$4, NULL, phalcon_25__closure_ce, SL("__invoke")); zephir_update_property_zval(this_ptr, SL("fileCheckingCallback"), &_0$$4); } else { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_loader_exception_ce, "The 'callback' parameter must be either a callable or NULL.", "phalcon/loader.zep", 91); return; } RETURN_THIS(); } /** * Sets the events manager */ PHP_METHOD(Phalcon_Loader, setEventsManager) { zval *eventsManager, eventsManager_sub; zval *this_ptr = getThis(); ZVAL_UNDEF(&eventsManager_sub); zephir_fetch_params(0, 1, 0, &eventsManager); zephir_update_property_zval(this_ptr, SL("_eventsManager"), eventsManager); } /** * Returns the internal event manager */ PHP_METHOD(Phalcon_Loader, getEventsManager) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_eventsManager"); } /** * Sets an array of file extensions that the loader must try in each attempt to locate the file */ PHP_METHOD(Phalcon_Loader, setExtensions) { zval *extensions_param = NULL; zval extensions; zval *this_ptr = getThis(); ZVAL_UNDEF(&extensions); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &extensions_param); ZEPHIR_OBS_COPY_OR_DUP(&extensions, extensions_param); zephir_update_property_zval(this_ptr, SL("_extensions"), &extensions); RETURN_THIS(); } /** * Returns the file extensions registered in the loader */ PHP_METHOD(Phalcon_Loader, getExtensions) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_extensions"); } /** * Register namespaces and their related directories */ PHP_METHOD(Phalcon_Loader, registerNamespaces) { zend_string *_2$$3; zend_ulong _1$$3; zend_long ZEPHIR_LAST_CALL_STATUS; zend_bool merge; zval *namespaces_param = NULL, *merge_param = NULL, preparedNamespaces, name, paths, *_0$$3, _3$$4, _5$$4, _6$$4, _7$$4, _4$$5; zval namespaces; zval *this_ptr = getThis(); ZVAL_UNDEF(&namespaces); ZVAL_UNDEF(&preparedNamespaces); ZVAL_UNDEF(&name); ZVAL_UNDEF(&paths); ZVAL_UNDEF(&_3$$4); ZVAL_UNDEF(&_5$$4); ZVAL_UNDEF(&_6$$4); ZVAL_UNDEF(&_7$$4); ZVAL_UNDEF(&_4$$5); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &namespaces_param, &merge_param); ZEPHIR_OBS_COPY_OR_DUP(&namespaces, namespaces_param); if (!merge_param) { merge = 0; } else { merge = zephir_get_boolval(merge_param); } ZEPHIR_CALL_METHOD(&preparedNamespaces, this_ptr, "preparenamespace", NULL, 0, &namespaces); zephir_check_call_status(); if (merge) { zephir_is_iterable(&preparedNamespaces, 0, "phalcon/loader.zep", 147); ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(&preparedNamespaces), _1$$3, _2$$3, _0$$3) { ZEPHIR_INIT_NVAR(&name); if (_2$$3 != NULL) { ZVAL_STR_COPY(&name, _2$$3); } else { ZVAL_LONG(&name, _1$$3); } ZEPHIR_INIT_NVAR(&paths); ZVAL_COPY(&paths, _0$$3); zephir_read_property(&_3$$4, this_ptr, SL("_namespaces"), PH_NOISY_CC | PH_READONLY); if (!(zephir_array_isset(&_3$$4, &name))) { ZEPHIR_INIT_NVAR(&_4$$5); array_init(&_4$$5); zephir_update_property_array(this_ptr, SL("_namespaces"), &name, &_4$$5 TSRMLS_CC); } ZEPHIR_INIT_NVAR(&_5$$4); zephir_read_property(&_6$$4, this_ptr, SL("_namespaces"), PH_NOISY_CC | PH_READONLY); zephir_array_fetch(&_7$$4, &_6$$4, &name, PH_NOISY | PH_READONLY, "phalcon/loader.zep", 145 TSRMLS_CC); zephir_fast_array_merge(&_5$$4, &_7$$4, &paths TSRMLS_CC); zephir_update_property_array(this_ptr, SL("_namespaces"), &name, &_5$$4 TSRMLS_CC); } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&paths); ZEPHIR_INIT_NVAR(&name); } else { zephir_update_property_zval(this_ptr, SL("_namespaces"), &preparedNamespaces); } RETURN_THIS(); } PHP_METHOD(Phalcon_Loader, prepareNamespace) { zend_string *_2; zend_ulong _1; zval *namespace_param = NULL, localPaths, name, paths, prepared, *_0; zval namespace; zval *this_ptr = getThis(); ZVAL_UNDEF(&namespace); ZVAL_UNDEF(&localPaths); ZVAL_UNDEF(&name); ZVAL_UNDEF(&paths); ZVAL_UNDEF(&prepared); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &namespace_param); ZEPHIR_OBS_COPY_OR_DUP(&namespace, namespace_param); ZEPHIR_INIT_VAR(&prepared); array_init(&prepared); zephir_is_iterable(&namespace, 0, "phalcon/loader.zep", 169); ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(&namespace), _1, _2, _0) { ZEPHIR_INIT_NVAR(&name); if (_2 != NULL) { ZVAL_STR_COPY(&name, _2); } else { ZVAL_LONG(&name, _1); } ZEPHIR_INIT_NVAR(&paths); ZVAL_COPY(&paths, _0); if (Z_TYPE_P(&paths) != IS_ARRAY) { ZEPHIR_INIT_NVAR(&localPaths); zephir_create_array(&localPaths, 1, 0 TSRMLS_CC); zephir_array_fast_append(&localPaths, &paths); } else { ZEPHIR_CPY_WRT(&localPaths, &paths); } zephir_array_update_zval(&prepared, &name, &localPaths, PH_COPY | PH_SEPARATE); } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&paths); ZEPHIR_INIT_NVAR(&name); RETURN_CCTOR(&prepared); } /** * Returns the namespaces currently registered in the autoloader */ PHP_METHOD(Phalcon_Loader, getNamespaces) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_namespaces"); } /** * Register directories in which "not found" classes could be found */ PHP_METHOD(Phalcon_Loader, registerDirs) { zend_bool merge; zval *directories_param = NULL, *merge_param = NULL, _0$$3, _1$$3; zval directories; zval *this_ptr = getThis(); ZVAL_UNDEF(&directories); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$3); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &directories_param, &merge_param); ZEPHIR_OBS_COPY_OR_DUP(&directories, directories_param); if (!merge_param) { merge = 0; } else { merge = zephir_get_boolval(merge_param); } if (merge) { ZEPHIR_INIT_VAR(&_0$$3); zephir_read_property(&_1$$3, this_ptr, SL("_directories"), PH_NOISY_CC | PH_READONLY); zephir_fast_array_merge(&_0$$3, &_1$$3, &directories TSRMLS_CC); zephir_update_property_zval(this_ptr, SL("_directories"), &_0$$3); } else { zephir_update_property_zval(this_ptr, SL("_directories"), &directories); } RETURN_THIS(); } /** * Returns the directories currently registered in the autoloader */ PHP_METHOD(Phalcon_Loader, getDirs) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_directories"); } /** * Registers files that are "non-classes" hence need a "require". This is very useful for including files that only * have functions */ PHP_METHOD(Phalcon_Loader, registerFiles) { zend_bool merge; zval *files_param = NULL, *merge_param = NULL, _0$$3, _1$$3; zval files; zval *this_ptr = getThis(); ZVAL_UNDEF(&files); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$3); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &files_param, &merge_param); ZEPHIR_OBS_COPY_OR_DUP(&files, files_param); if (!merge_param) { merge = 0; } else { merge = zephir_get_boolval(merge_param); } if (merge) { ZEPHIR_INIT_VAR(&_0$$3); zephir_read_property(&_1$$3, this_ptr, SL("_files"), PH_NOISY_CC | PH_READONLY); zephir_fast_array_merge(&_0$$3, &_1$$3, &files TSRMLS_CC); zephir_update_property_zval(this_ptr, SL("_files"), &_0$$3); } else { zephir_update_property_zval(this_ptr, SL("_files"), &files); } RETURN_THIS(); } /** * Returns the files currently registered in the autoloader */ PHP_METHOD(Phalcon_Loader, getFiles) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_files"); } /** * Register classes and their locations */ PHP_METHOD(Phalcon_Loader, registerClasses) { zend_bool merge; zval *classes_param = NULL, *merge_param = NULL, _0$$3, _1$$3; zval classes; zval *this_ptr = getThis(); ZVAL_UNDEF(&classes); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$3); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &classes_param, &merge_param); ZEPHIR_OBS_COPY_OR_DUP(&classes, classes_param); if (!merge_param) { merge = 0; } else { merge = zephir_get_boolval(merge_param); } if (merge) { ZEPHIR_INIT_VAR(&_0$$3); zephir_read_property(&_1$$3, this_ptr, SL("_classes"), PH_NOISY_CC | PH_READONLY); zephir_fast_array_merge(&_0$$3, &_1$$3, &classes TSRMLS_CC); zephir_update_property_zval(this_ptr, SL("_classes"), &_0$$3); } else { zephir_update_property_zval(this_ptr, SL("_classes"), &classes); } RETURN_THIS(); } /** * Returns the class-map currently registered in the autoloader */ PHP_METHOD(Phalcon_Loader, getClasses) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_classes"); } /** * Register the autoload method */ PHP_METHOD(Phalcon_Loader, register) { zval _1$$3; zend_long ZEPHIR_LAST_CALL_STATUS; zval *prepend_param = NULL, __$true, __$false, _0, _2$$3, _3$$3; zend_bool prepend; zval *this_ptr = getThis(); ZVAL_BOOL(&__$true, 1); ZVAL_BOOL(&__$false, 0); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_2$$3); ZVAL_UNDEF(&_3$$3); ZVAL_UNDEF(&_1$$3); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 1, &prepend_param); if (!prepend_param) { prepend = 0; } else { prepend = zephir_get_boolval(prepend_param); } zephir_read_property(&_0, this_ptr, SL("_registered"), PH_NOISY_CC | PH_READONLY); if (ZEPHIR_IS_FALSE_IDENTICAL(&_0)) { ZEPHIR_CALL_METHOD(NULL, this_ptr, "loadfiles", NULL, 0); zephir_check_call_status(); ZEPHIR_INIT_VAR(&_1$$3); zephir_create_array(&_1$$3, 2, 0 TSRMLS_CC); zephir_array_fast_append(&_1$$3, this_ptr); ZEPHIR_INIT_VAR(&_2$$3); ZVAL_STRING(&_2$$3, "autoLoad"); zephir_array_fast_append(&_1$$3, &_2$$3); ZVAL_BOOL(&_3$$3, (prepend ? 1 : 0)); ZEPHIR_CALL_FUNCTION(NULL, "spl_autoload_register", NULL, 284, &_1$$3, &__$true, &_3$$3); zephir_check_call_status(); if (1) { zephir_update_property_zval(this_ptr, SL("_registered"), &__$true); } else { zephir_update_property_zval(this_ptr, SL("_registered"), &__$false); } } RETURN_THIS(); } /** * Unregister the autoload method */ PHP_METHOD(Phalcon_Loader, unregister) { zval _1$$3; zval __$true, __$false, _0, _2$$3; zend_long ZEPHIR_LAST_CALL_STATUS; zval *this_ptr = getThis(); ZVAL_BOOL(&__$true, 1); ZVAL_BOOL(&__$false, 0); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_2$$3); ZVAL_UNDEF(&_1$$3); ZEPHIR_MM_GROW(); zephir_read_property(&_0, this_ptr, SL("_registered"), PH_NOISY_CC | PH_READONLY); if (ZEPHIR_IS_TRUE_IDENTICAL(&_0)) { ZEPHIR_INIT_VAR(&_1$$3); zephir_create_array(&_1$$3, 2, 0 TSRMLS_CC); zephir_array_fast_append(&_1$$3, this_ptr); ZEPHIR_INIT_VAR(&_2$$3); ZVAL_STRING(&_2$$3, "autoLoad"); zephir_array_fast_append(&_1$$3, &_2$$3); ZEPHIR_CALL_FUNCTION(NULL, "spl_autoload_unregister", NULL, 285, &_1$$3); zephir_check_call_status(); if (0) { zephir_update_property_zval(this_ptr, SL("_registered"), &__$true); } else { zephir_update_property_zval(this_ptr, SL("_registered"), &__$false); } } RETURN_THIS(); } /** * Checks if a file exists and then adds the file by doing virtual require */ PHP_METHOD(Phalcon_Loader, loadFiles) { zval filePath, fileCheckingCallback, _0, *_1, _2$$3, _5$$3, _3$$4, _4$$4, _7$$5, _8$$6, _9$$6; zephir_fcall_cache_entry *_6 = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *this_ptr = getThis(); ZVAL_UNDEF(&filePath); ZVAL_UNDEF(&fileCheckingCallback); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_2$$3); ZVAL_UNDEF(&_5$$3); ZVAL_UNDEF(&_3$$4); ZVAL_UNDEF(&_4$$4); ZVAL_UNDEF(&_7$$5); ZVAL_UNDEF(&_8$$6); ZVAL_UNDEF(&_9$$6); ZEPHIR_MM_GROW(); zephir_read_property(&_0, this_ptr, SL("fileCheckingCallback"), PH_NOISY_CC | PH_READONLY); ZEPHIR_CPY_WRT(&fileCheckingCallback, &_0); zephir_read_property(&_0, this_ptr, SL("_files"), PH_NOISY_CC | PH_READONLY); zephir_is_iterable(&_0, 0, "phalcon/loader.zep", 314); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(&_0), _1) { ZEPHIR_INIT_NVAR(&filePath); ZVAL_COPY(&filePath, _1); ZEPHIR_OBS_NVAR(&_2$$3); zephir_read_property(&_2$$3, this_ptr, SL("_eventsManager"), PH_NOISY_CC); if (Z_TYPE_P(&_2$$3) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_checkedPath"), &filePath); zephir_read_property(&_3$$4, this_ptr, SL("_eventsManager"), PH_NOISY_CC | PH_READONLY); ZEPHIR_INIT_NVAR(&_4$$4); ZVAL_STRING(&_4$$4, "loader:beforeCheckPath"); ZEPHIR_CALL_METHOD(NULL, &_3$$4, "fire", NULL, 0, &_4$$4, this_ptr, &filePath); zephir_check_call_status(); } ZEPHIR_CALL_FUNCTION(&_5$$3, "call_user_func", &_6, 286, &fileCheckingCallback, &filePath); zephir_check_call_status(); if (zephir_is_true(&_5$$3)) { ZEPHIR_OBS_NVAR(&_7$$5); zephir_read_property(&_7$$5, this_ptr, SL("_eventsManager"), PH_NOISY_CC); if (Z_TYPE_P(&_7$$5) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_foundPath"), &filePath); zephir_read_property(&_8$$6, this_ptr, SL("_eventsManager"), PH_NOISY_CC | PH_READONLY); ZEPHIR_INIT_NVAR(&_9$$6); ZVAL_STRING(&_9$$6, "loader:pathFound"); ZEPHIR_CALL_METHOD(NULL, &_8$$6, "fire", NULL, 0, &_9$$6, this_ptr, &filePath); zephir_check_call_status(); } if (zephir_require_zval(&filePath TSRMLS_CC) == FAILURE) { RETURN_MM_NULL(); } } } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&filePath); ZEPHIR_MM_RESTORE(); } /** * Autoloads the registered classes */ PHP_METHOD(Phalcon_Loader, autoLoad) { zend_string *_5; zend_ulong _4; zephir_fcall_cache_entry *_13 = NULL, *_15 = NULL, *_17 = NULL, *_22 = NULL, *_25 = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *className_param = NULL, eventsManager, classes, extensions, filePath, ds, fixedDirectory, directories, ns, namespaces, nsPrefix, directory, fileName, extension, nsClassName, fileCheckingCallback, _2, *_3, *_18, _0$$3, _1$$5, _6$$6, _7$$6, _8$$6, *_9$$6, _10$$9, *_11$$9, _12$$11, _14$$10, _16$$13, _19$$14, *_20$$14, _21$$16, _23$$15, _24$$18, _26$$19; zval className; zval *this_ptr = getThis(); ZVAL_UNDEF(&className); ZVAL_UNDEF(&eventsManager); ZVAL_UNDEF(&classes); ZVAL_UNDEF(&extensions); ZVAL_UNDEF(&filePath); ZVAL_UNDEF(&ds); ZVAL_UNDEF(&fixedDirectory); ZVAL_UNDEF(&directories); ZVAL_UNDEF(&ns); ZVAL_UNDEF(&namespaces); ZVAL_UNDEF(&nsPrefix); ZVAL_UNDEF(&directory); ZVAL_UNDEF(&fileName); ZVAL_UNDEF(&extension); ZVAL_UNDEF(&nsClassName); ZVAL_UNDEF(&fileCheckingCallback); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$5); ZVAL_UNDEF(&_6$$6); ZVAL_UNDEF(&_7$$6); ZVAL_UNDEF(&_8$$6); ZVAL_UNDEF(&_10$$9); ZVAL_UNDEF(&_12$$11); ZVAL_UNDEF(&_14$$10); ZVAL_UNDEF(&_16$$13); ZVAL_UNDEF(&_19$$14); ZVAL_UNDEF(&_21$$16); ZVAL_UNDEF(&_23$$15); ZVAL_UNDEF(&_24$$18); ZVAL_UNDEF(&_26$$19); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &className_param); if (UNEXPECTED(Z_TYPE_P(className_param) != IS_STRING && Z_TYPE_P(className_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'className' must be of the type string") TSRMLS_CC); RETURN_MM_NULL(); } if (EXPECTED(Z_TYPE_P(className_param) == IS_STRING)) { zephir_get_strval(&className, className_param); } else { ZEPHIR_INIT_VAR(&className); ZVAL_EMPTY_STRING(&className); } ZEPHIR_OBS_VAR(&eventsManager); zephir_read_property(&eventsManager, this_ptr, SL("_eventsManager"), PH_NOISY_CC); if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { ZEPHIR_INIT_VAR(&_0$$3); ZVAL_STRING(&_0$$3, "loader:beforeCheckClass"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", NULL, 0, &_0$$3, this_ptr, &className); zephir_check_call_status(); } ZEPHIR_OBS_VAR(&classes); zephir_read_property(&classes, this_ptr, SL("_classes"), PH_NOISY_CC); ZEPHIR_OBS_VAR(&filePath); if (zephir_array_isset_fetch(&filePath, &classes, &className, 0 TSRMLS_CC)) { if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_foundPath"), &filePath); ZEPHIR_INIT_VAR(&_1$$5); ZVAL_STRING(&_1$$5, "loader:pathFound"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", NULL, 0, &_1$$5, this_ptr, &filePath); zephir_check_call_status(); } if (zephir_require_zval(&filePath TSRMLS_CC) == FAILURE) { RETURN_MM_NULL(); } RETURN_MM_BOOL(1); } ZEPHIR_OBS_VAR(&extensions); zephir_read_property(&extensions, this_ptr, SL("_extensions"), PH_NOISY_CC); ZEPHIR_INIT_VAR(&ds); ZVAL_STRING(&ds, "/"); ZEPHIR_INIT_VAR(&ns); ZVAL_STRING(&ns, "\\"); ZEPHIR_OBS_VAR(&namespaces); zephir_read_property(&namespaces, this_ptr, SL("_namespaces"), PH_NOISY_CC); zephir_read_property(&_2, this_ptr, SL("fileCheckingCallback"), PH_NOISY_CC | PH_READONLY); ZEPHIR_CPY_WRT(&fileCheckingCallback, &_2); zephir_is_iterable(&namespaces, 0, "phalcon/loader.zep", 420); ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(&namespaces), _4, _5, _3) { ZEPHIR_INIT_NVAR(&nsPrefix); if (_5 != NULL) { ZVAL_STR_COPY(&nsPrefix, _5); } else { ZVAL_LONG(&nsPrefix, _4); } ZEPHIR_INIT_NVAR(&directories); ZVAL_COPY(&directories, _3); if (!(zephir_start_with(&className, &nsPrefix, NULL))) { continue; } ZEPHIR_INIT_LNVAR(_6$$6); ZEPHIR_CONCAT_VV(&_6$$6, &nsPrefix, &ns); ZVAL_LONG(&_7$$6, zephir_fast_strlen_ev(&_6$$6)); ZEPHIR_INIT_NVAR(&fileName); zephir_substr(&fileName, &className, zephir_get_intval(&_7$$6), 0, ZEPHIR_SUBSTR_NO_LENGTH); if (!(zephir_is_true(&fileName))) { continue; } ZEPHIR_INIT_NVAR(&_8$$6); zephir_fast_str_replace(&_8$$6, &ns, &ds, &fileName TSRMLS_CC); ZEPHIR_CPY_WRT(&fileName, &_8$$6); zephir_is_iterable(&directories, 0, "phalcon/loader.zep", 415); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(&directories), _9$$6) { ZEPHIR_INIT_NVAR(&directory); ZVAL_COPY(&directory, _9$$6); ZEPHIR_INIT_NVAR(&_10$$9); zephir_fast_trim(&_10$$9, &directory, &ds, ZEPHIR_TRIM_RIGHT TSRMLS_CC); ZEPHIR_INIT_NVAR(&fixedDirectory); ZEPHIR_CONCAT_VV(&fixedDirectory, &_10$$9, &ds); zephir_is_iterable(&extensions, 0, "phalcon/loader.zep", 414); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(&extensions), _11$$9) { ZEPHIR_INIT_NVAR(&extension); ZVAL_COPY(&extension, _11$$9); ZEPHIR_INIT_NVAR(&filePath); ZEPHIR_CONCAT_VVSV(&filePath, &fixedDirectory, &fileName, ".", &extension); if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_checkedPath"), &filePath); ZEPHIR_INIT_NVAR(&_12$$11); ZVAL_STRING(&_12$$11, "loader:beforeCheckPath"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", &_13, 0, &_12$$11, this_ptr); zephir_check_call_status(); } ZEPHIR_CALL_FUNCTION(&_14$$10, "call_user_func", &_15, 286, &fileCheckingCallback, &filePath); zephir_check_call_status(); if (zephir_is_true(&_14$$10)) { if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_foundPath"), &filePath); ZEPHIR_INIT_NVAR(&_16$$13); ZVAL_STRING(&_16$$13, "loader:pathFound"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", &_17, 0, &_16$$13, this_ptr, &filePath); zephir_check_call_status(); } if (zephir_require_zval(&filePath TSRMLS_CC) == FAILURE) { RETURN_MM_NULL(); } RETURN_MM_BOOL(1); } } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&extension); } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&directory); } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&directories); ZEPHIR_INIT_NVAR(&nsPrefix); ZEPHIR_INIT_VAR(&nsClassName); zephir_fast_str_replace(&nsClassName, &ns, &ds, &className TSRMLS_CC); ZEPHIR_OBS_NVAR(&directories); zephir_read_property(&directories, this_ptr, SL("_directories"), PH_NOISY_CC); zephir_is_iterable(&directories, 0, "phalcon/loader.zep", 475); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(&directories), _18) { ZEPHIR_INIT_NVAR(&directory); ZVAL_COPY(&directory, _18); ZEPHIR_INIT_NVAR(&_19$$14); zephir_fast_trim(&_19$$14, &directory, &ds, ZEPHIR_TRIM_RIGHT TSRMLS_CC); ZEPHIR_INIT_NVAR(&fixedDirectory); ZEPHIR_CONCAT_VV(&fixedDirectory, &_19$$14, &ds); zephir_is_iterable(&extensions, 0, "phalcon/loader.zep", 470); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(&extensions), _20$$14) { ZEPHIR_INIT_NVAR(&extension); ZVAL_COPY(&extension, _20$$14); ZEPHIR_INIT_NVAR(&filePath); ZEPHIR_CONCAT_VVSV(&filePath, &fixedDirectory, &nsClassName, ".", &extension); if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_checkedPath"), &filePath); ZEPHIR_INIT_NVAR(&_21$$16); ZVAL_STRING(&_21$$16, "loader:beforeCheckPath"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", &_22, 0, &_21$$16, this_ptr, &filePath); zephir_check_call_status(); } ZEPHIR_CALL_FUNCTION(&_23$$15, "call_user_func", &_15, 286, &fileCheckingCallback, &filePath); zephir_check_call_status(); if (zephir_is_true(&_23$$15)) { if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { zephir_update_property_zval(this_ptr, SL("_foundPath"), &filePath); ZEPHIR_INIT_NVAR(&_24$$18); ZVAL_STRING(&_24$$18, "loader:pathFound"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", &_25, 0, &_24$$18, this_ptr, &filePath); zephir_check_call_status(); } if (zephir_require_zval(&filePath TSRMLS_CC) == FAILURE) { RETURN_MM_NULL(); } RETURN_MM_BOOL(1); } } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&extension); } ZEND_HASH_FOREACH_END(); ZEPHIR_INIT_NVAR(&directory); if (Z_TYPE_P(&eventsManager) == IS_OBJECT) { ZEPHIR_INIT_VAR(&_26$$19); ZVAL_STRING(&_26$$19, "loader:afterCheckClass"); ZEPHIR_CALL_METHOD(NULL, &eventsManager, "fire", NULL, 0, &_26$$19, this_ptr, &className); zephir_check_call_status(); } RETURN_MM_BOOL(0); } /** * Get the path when a class was found */ PHP_METHOD(Phalcon_Loader, getFoundPath) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_foundPath"); } /** * Get the path the loader is checking for a path */ PHP_METHOD(Phalcon_Loader, getCheckedPath) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "_checkedPath"); } zend_object *zephir_init_properties_Phalcon_Loader(zend_class_entry *class_type TSRMLS_DC) { zval _7$$6; zval _0, _2, _4, _6, _9, _1$$3, _3$$4, _5$$5, _8$$6, _10$$7; ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&_4); ZVAL_UNDEF(&_6); ZVAL_UNDEF(&_9); ZVAL_UNDEF(&_1$$3); ZVAL_UNDEF(&_3$$4); ZVAL_UNDEF(&_5$$5); ZVAL_UNDEF(&_8$$6); ZVAL_UNDEF(&_10$$7); ZVAL_UNDEF(&_7$$6); ZEPHIR_MM_GROW(); { zval local_this_ptr, *this_ptr = &local_this_ptr; ZEPHIR_CREATE_OBJECT(this_ptr, class_type); zephir_read_property(&_0, this_ptr, SL("_files"), PH_NOISY_CC | PH_READONLY); if (Z_TYPE_P(&_0) == IS_NULL) { ZEPHIR_INIT_VAR(&_1$$3); array_init(&_1$$3); zephir_update_property_zval(this_ptr, SL("_files"), &_1$$3); } zephir_read_property(&_2, this_ptr, SL("_directories"), PH_NOISY_CC | PH_READONLY); if (Z_TYPE_P(&_2) == IS_NULL) { ZEPHIR_INIT_VAR(&_3$$4); array_init(&_3$$4); zephir_update_property_zval(this_ptr, SL("_directories"), &_3$$4); } zephir_read_property(&_4, this_ptr, SL("_namespaces"), PH_NOISY_CC | PH_READONLY); if (Z_TYPE_P(&_4) == IS_NULL) { ZEPHIR_INIT_VAR(&_5$$5); array_init(&_5$$5); zephir_update_property_zval(this_ptr, SL("_namespaces"), &_5$$5); } zephir_read_property(&_6, this_ptr, SL("_extensions"), PH_NOISY_CC | PH_READONLY); if (Z_TYPE_P(&_6) == IS_NULL) { ZEPHIR_INIT_VAR(&_7$$6); zephir_create_array(&_7$$6, 1, 0 TSRMLS_CC); ZEPHIR_INIT_VAR(&_8$$6); ZVAL_STRING(&_8$$6, "php"); zephir_array_fast_append(&_7$$6, &_8$$6); zephir_update_property_zval(this_ptr, SL("_extensions"), &_7$$6); } zephir_read_property(&_9, this_ptr, SL("_classes"), PH_NOISY_CC | PH_READONLY); if (Z_TYPE_P(&_9) == IS_NULL) { ZEPHIR_INIT_VAR(&_10$$7); array_init(&_10$$7); zephir_update_property_zval(this_ptr, SL("_classes"), &_10$$7); } ZEPHIR_MM_RESTORE(); return Z_OBJ_P(this_ptr); } }
29.076677
359
0.712449
[ "object" ]
2c38d58bf03828618a0ab1b348daa96cfbd2c5ca
92,362
c
C
zircon/third_party/ulib/musl/ldso/dynlink.c
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
zircon/third_party/ulib/musl/ldso/dynlink.c
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
zircon/third_party/ulib/musl/ldso/dynlink.c
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
#define _GNU_SOURCE #include "dynlink.h" #include "relr.h" #include "libc.h" #include "asan_impl.h" #include "zircon_impl.h" #include "threads_impl.h" #include "stdio_impl.h" #include <ctype.h> #include <dlfcn.h> #include <elf.h> #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <ldmsg/ldmsg.h> #include <lib/processargs/processargs.h> #include <lib/zircon-internal/default_stack_size.h> #include <limits.h> #include <link.h> #include <pthread.h> #include <runtime/thread.h> #include <setjmp.h> #include <stdalign.h> #include <stdarg.h> #include <stdatomic.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include <zircon/dlfcn.h> #include <zircon/process.h> #include <zircon/status.h> #include <zircon/syscalls/log.h> static void early_init(void); static void error(const char*, ...); static void debugmsg(const char*, ...); static zx_status_t get_library_vmo(const char* name, zx_handle_t* vmo); static void loader_svc_config(const char* config); #define MAXP2(a, b) (-(-(a) & -(b))) #define ALIGN(x, y) (((x) + (y)-1) & -(y)) #define VMO_NAME_DL_ALLOC "ld.so.1-internal-heap" #define VMO_NAME_UNKNOWN "<unknown ELF file>" #define VMO_NAME_PREFIX_BSS "bss:" #define VMO_NAME_PREFIX_DATA "data:" #define KEEP_DSO_VMAR __has_feature(xray_instrument) struct dso { // Must be first. struct link_map l_map; const struct gnu_note* build_id_note; // TODO(mcgrathr): Remove build_id_log when everything uses markup. struct iovec build_id_log; atomic_flag logged; // ID of this module for symbolizer markup. unsigned int module_id; const char* soname; Phdr* phdr; unsigned int phnum; size_t phentsize; int refcnt; zx_handle_t vmar; // Closed after relocation. Sym* syms; uint32_t* hashtab; uint32_t* ghashtab; int16_t* versym; char* strings; unsigned char* map; size_t map_len; signed char global; char relocated; char constructed; struct dso **deps, *needed_by; struct tls_module tls; size_t tls_id; size_t code_start, code_end; size_t relro_start, relro_end; void** new_dtv; unsigned char* new_tls; atomic_int new_dtv_idx, new_tls_idx; struct dso* fini_next; struct funcdesc { void* addr; size_t* got; } * funcdescs; size_t* got; struct dso* buf[]; }; struct symdef { Sym* sym; struct dso* dso; }; union gnu_note_name { char name[sizeof("GNU")]; uint32_t word; }; #define GNU_NOTE_NAME ((union gnu_note_name){.name = "GNU"}) _Static_assert(sizeof(GNU_NOTE_NAME.name) == sizeof(GNU_NOTE_NAME.word), ""); struct gnu_note { Elf64_Nhdr nhdr; union gnu_note_name name; alignas(4) uint8_t desc[]; }; #define MIN_TLS_ALIGN alignof(struct pthread) #define ADDEND_LIMIT 4096 static size_t *saved_addends, *apply_addends_to; static struct dso ldso, vdso; static struct dso *head, *tail, *fini_head; static struct dso *detached_head; static unsigned long long gencnt; static int runtime __asm__("_dynlink_runtime") __USED; static int ldso_fail; static jmp_buf* rtld_fail; static pthread_rwlock_t lock; static struct r_debug debug; static struct tls_module* tls_tail; static size_t tls_cnt, tls_offset = 16, tls_align = MIN_TLS_ALIGN; static size_t static_tls_cnt; static pthread_mutex_t init_fini_lock = { ._m_attr = PTHREAD_MUTEX_MAKE_ATTR(PTHREAD_MUTEX_RECURSIVE, PTHREAD_PRIO_NONE) }; static bool log_libs = false; static atomic_uintptr_t unlogged_tail; static zx_handle_t loader_svc = ZX_HANDLE_INVALID; static zx_handle_t logger = ZX_HANDLE_INVALID; // Various tools use this value to bootstrap their knowledge of the process. // E.g., the list of loaded shared libraries is obtained from here. // The value is stored in the process's ZX_PROPERTY_PROCESS_DEBUG_ADDR so that // tools can obtain the value when aslr is enabled. struct r_debug* _dl_debug_addr = &debug; // If true then dump load map data in a specific format for tracing. // This is used by Intel PT (Processor Trace) support for example when // post-processing the h/w trace. static bool trace_maps = false; NO_ASAN static int dl_strcmp(const char* l, const char* r) { for (; *l == *r && *l; l++, r++) ; return *(unsigned char*)l - *(unsigned char*)r; } #define strcmp(l, r) dl_strcmp(l, r) // Signals a debug breakpoint. It does't use __builtin_trap() because that's // actually an "undefined instruction" rather than a debug breakpoint, and // __builtin_trap() documented to never return. We don't want the compiler to // optimize later code away because it assumes the trap will never be returned // from. static void debug_break(void) { #if defined(__x86_64__) __asm__("int3"); #elif defined(__aarch64__) __asm__("brk 0"); #else #error #endif } // Simple bump allocator for dynamic linker internal data structures. // This allocator is single-threaded: it can be used only at startup or // while holding the big lock. These allocations can never be freed // once in use. But it does support a simple checkpoint and rollback // mechanism to undo all allocations since the checkpoint, used for the // abortive dlopen case. union allocated_types { struct dso dso; size_t tlsdesc[2]; }; #define DL_ALLOC_ALIGN alignof(union allocated_types) static uintptr_t alloc_base, alloc_limit, alloc_ptr; __NO_SAFESTACK NO_ASAN __attribute__((malloc)) static void* dl_alloc(size_t size) { // Round the size up so the allocation pointer always stays aligned. size = (size + DL_ALLOC_ALIGN - 1) & -DL_ALLOC_ALIGN; // Get more pages if needed. The remaining partial page, if any, // is wasted unless the system happens to give us the adjacent page. if (alloc_limit - alloc_ptr < size) { size_t chunk_size = (size + PAGE_SIZE - 1) & -PAGE_SIZE; zx_handle_t vmo; zx_status_t status = _zx_vmo_create(chunk_size, 0, &vmo); if (status != ZX_OK) return NULL; _zx_object_set_property(vmo, ZX_PROP_NAME, VMO_NAME_DL_ALLOC, sizeof(VMO_NAME_DL_ALLOC)); uintptr_t chunk; status = _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, chunk_size, &chunk); _zx_handle_close(vmo); if (status != ZX_OK) return NULL; if (chunk != alloc_limit) alloc_ptr = alloc_base = chunk; alloc_limit = chunk + chunk_size; } void* block = (void*)alloc_ptr; alloc_ptr += size; return block; } struct dl_alloc_checkpoint { uintptr_t ptr, base; }; __NO_SAFESTACK static void dl_alloc_checkpoint(struct dl_alloc_checkpoint *state) { state->ptr = alloc_ptr; state->base = alloc_base; } __NO_SAFESTACK static void dl_alloc_rollback(const struct dl_alloc_checkpoint *state) { uintptr_t frontier = alloc_ptr; // If we're still using the same contiguous chunk as the checkpoint // state, we can just restore the old state directly and waste nothing. // If we've allocated new chunks since then, the best we can do is // reset to the beginning of the current chunk, since we haven't kept // track of the past chunks. alloc_ptr = alloc_base == state->base ? state->ptr : alloc_base; memset((void*)alloc_ptr, 0, frontier - alloc_ptr); } /* Compute load address for a virtual address in a given dso. */ __NO_SAFESTACK NO_ASAN static inline size_t saddr(struct dso* p, size_t v) { return p->l_map.l_addr + v; } __NO_SAFESTACK NO_ASAN static inline void* laddr(struct dso* p, size_t v) { return (void*)saddr(p, v); } __NO_SAFESTACK NO_ASAN static inline void (*fpaddr(struct dso* p, size_t v))(void) { return (void (*)(void))saddr(p, v); } // Accessors for dso previous and next pointers. __NO_SAFESTACK NO_ASAN static inline struct dso* dso_next(struct dso* p) { return (struct dso*)p->l_map.l_next; } __NO_SAFESTACK NO_ASAN static inline struct dso* dso_prev(struct dso* p) { return (struct dso*)p->l_map.l_prev; } __NO_SAFESTACK NO_ASAN static inline void dso_set_next(struct dso* p, struct dso* next) { p->l_map.l_next = next ? &next->l_map : NULL; } __NO_SAFESTACK NO_ASAN static inline void dso_set_prev(struct dso* p, struct dso* prev) { p->l_map.l_prev = prev ? &prev->l_map : NULL; } // TODO(mcgrathr): Working around arcane compiler issues; find a better way. // The compiler can decide to turn the loop below into a memset call. Since // memset is an exported symbol, calls to that name are PLT calls. But this // code runs before PLT calls are available. So use the .weakref trick to // tell the assembler to rename references (the compiler generates) to memset // to __libc_memset. That's a hidden symbol that won't cause a PLT entry to // be generated, so it's safe to use in calls here. __asm__(".weakref memset,__libc_memset"); __NO_SAFESTACK NO_ASAN static void decode_vec(ElfW(Dyn)* v, size_t* a, size_t cnt) { size_t i; for (i = 0; i < cnt; i++) a[i] = 0; for (; v->d_tag; v++) if (v->d_tag - 1 < cnt - 1) { a[0] |= 1UL << v->d_tag; a[v->d_tag] = v->d_un.d_val; } } __NO_SAFESTACK NO_ASAN static int search_vec(ElfW(Dyn)* v, size_t* r, size_t key) { for (; v->d_tag != key; v++) if (!v->d_tag) return 0; *r = v->d_un.d_val; return 1; } __NO_SAFESTACK NO_ASAN static uint32_t sysv_hash(const char* s0) { const unsigned char* s = (void*)s0; uint_fast32_t h = 0; while (*s) { h = 16 * h + *s++; h ^= h >> 24 & 0xf0; } return h & 0xfffffff; } __NO_SAFESTACK NO_ASAN static uint32_t gnu_hash(const char* s0) { const unsigned char* s = (void*)s0; uint_fast32_t h = 5381; for (; *s; s++) h += h * 32 + *s; return h; } __NO_SAFESTACK NO_ASAN static Sym* sysv_lookup(const char* s, uint32_t h, struct dso* dso) { size_t i; Sym* syms = dso->syms; uint32_t* hashtab = dso->hashtab; char* strings = dso->strings; for (i = hashtab[2 + h % hashtab[0]]; i; i = hashtab[2 + hashtab[0] + i]) { if ((!dso->versym || dso->versym[i] >= 0) && (!strcmp(s, strings + syms[i].st_name))) return syms + i; } return 0; } __NO_SAFESTACK NO_ASAN static Sym* gnu_lookup(uint32_t h1, uint32_t* hashtab, struct dso* dso, const char* s) { uint32_t nbuckets = hashtab[0]; uint32_t* buckets = hashtab + 4 + hashtab[2] * (sizeof(size_t) / 4); uint32_t i = buckets[h1 % nbuckets]; if (!i) return 0; uint32_t* hashval = buckets + nbuckets + (i - hashtab[1]); for (h1 |= 1;; i++) { uint32_t h2 = *hashval++; if ((h1 == (h2 | 1)) && (!dso->versym || dso->versym[i] >= 0) && !strcmp(s, dso->strings + dso->syms[i].st_name)) return dso->syms + i; if (h2 & 1) break; } return 0; } __NO_SAFESTACK NO_ASAN static Sym* gnu_lookup_filtered(uint32_t h1, uint32_t* hashtab, struct dso* dso, const char* s, uint32_t fofs, size_t fmask) { const size_t* bloomwords = (const void*)(hashtab + 4); size_t f = bloomwords[fofs & (hashtab[2] - 1)]; if (!(f & fmask)) return 0; f >>= (h1 >> hashtab[3]) % (8 * sizeof f); if (!(f & 1)) return 0; return gnu_lookup(h1, hashtab, dso, s); } #define OK_TYPES \ (1 << STT_NOTYPE | 1 << STT_OBJECT | 1 << STT_FUNC | 1 << STT_COMMON | 1 << STT_TLS) #define OK_BINDS (1 << STB_GLOBAL | 1 << STB_WEAK | 1 << STB_GNU_UNIQUE) __NO_SAFESTACK NO_ASAN static struct symdef find_sym(struct dso* dso, const char* s, int need_def) { uint32_t h = 0, gh = 0, gho = 0, *ght; size_t ghm = 0; struct symdef def = {}; for (; dso; dso = dso_next(dso)) { Sym* sym; if (!dso->global) continue; if ((ght = dso->ghashtab)) { if (!ghm) { gh = gnu_hash(s); int maskbits = 8 * sizeof ghm; gho = gh / maskbits; ghm = 1ul << gh % maskbits; } sym = gnu_lookup_filtered(gh, ght, dso, s, gho, ghm); } else { if (!h) h = sysv_hash(s); sym = sysv_lookup(s, h, dso); } if (!sym) continue; if (!sym->st_shndx) if (need_def || (sym->st_info & 0xf) == STT_TLS) continue; if (!sym->st_value) if ((sym->st_info & 0xf) != STT_TLS) continue; if (!(1 << (sym->st_info & 0xf) & OK_TYPES)) continue; if (!(1 << (sym->st_info >> 4) & OK_BINDS)) continue; if (def.sym && sym->st_info >> 4 == STB_WEAK) continue; def.sym = sym; def.dso = dso; if (sym->st_info >> 4 == STB_GLOBAL) break; } return def; } __attribute__((__visibility__("hidden"))) ptrdiff_t __tlsdesc_static(void), __tlsdesc_dynamic(void); __NO_SAFESTACK NO_ASAN static void do_relocs(struct dso* dso, size_t* rel, size_t rel_size, size_t stride) { ElfW(Addr) base = dso->l_map.l_addr; Sym* syms = dso->syms; char* strings = dso->strings; Sym* sym; const char* name; void* ctx; int type; int sym_index; struct symdef def; size_t* reloc_addr; size_t sym_val; size_t tls_val; size_t addend; int skip_relative = 0, reuse_addends = 0, save_slot = 0; if (dso == &ldso) { /* Only ldso's REL table needs addend saving/reuse. */ if (rel == apply_addends_to) reuse_addends = 1; skip_relative = 1; } for (; rel_size; rel += stride, rel_size -= stride * sizeof(size_t)) { if (skip_relative && R_TYPE(rel[1]) == REL_RELATIVE) continue; type = R_TYPE(rel[1]); if (type == REL_NONE) continue; sym_index = R_SYM(rel[1]); reloc_addr = laddr(dso, rel[0]); if (sym_index) { sym = syms + sym_index; name = strings + sym->st_name; ctx = type == REL_COPY ? dso_next(head) : head; def = (sym->st_info & 0xf) == STT_SECTION ? (struct symdef){.dso = dso, .sym = sym} : find_sym(ctx, name, type == REL_PLT); if (!def.sym && (sym->st_shndx != SHN_UNDEF || sym->st_info >> 4 != STB_WEAK)) { error("Error relocating %s: %s: symbol not found", dso->l_map.l_name, name); if (runtime) longjmp(*rtld_fail, 1); continue; } } else { name = "(local)"; sym = 0; def.sym = 0; def.dso = dso; } if (stride > 2) { addend = rel[2]; } else if (type == REL_GOT || type == REL_PLT || type == REL_COPY) { addend = 0; } else if (reuse_addends) { /* Save original addend in stage 2 where the dso * chain consists of just ldso; otherwise read back * saved addend since the inline one was clobbered. */ if (head == &ldso) saved_addends[save_slot] = *reloc_addr; addend = saved_addends[save_slot++]; } else { addend = *reloc_addr; } sym_val = def.sym ? saddr(def.dso, def.sym->st_value) : 0; tls_val = def.sym ? def.sym->st_value : 0; switch (type) { case REL_NONE: break; case REL_OFFSET: addend -= (size_t)reloc_addr; case REL_SYMBOLIC: case REL_GOT: case REL_PLT: *reloc_addr = sym_val + addend; break; case REL_RELATIVE: *reloc_addr = base + addend; break; case REL_COPY: memcpy(reloc_addr, (void*)sym_val, sym->st_size); break; case REL_OFFSET32: *(uint32_t*)reloc_addr = sym_val + addend - (size_t)reloc_addr; break; case REL_FUNCDESC: *reloc_addr = def.sym ? (size_t)(def.dso->funcdescs + (def.sym - def.dso->syms)) : 0; break; case REL_FUNCDESC_VAL: if ((sym->st_info & 0xf) == STT_SECTION) *reloc_addr += sym_val; else *reloc_addr = sym_val; reloc_addr[1] = def.sym ? (size_t)def.dso->got : 0; break; case REL_DTPMOD: *reloc_addr = def.dso->tls_id; break; case REL_DTPOFF: *reloc_addr = tls_val + addend - DTP_OFFSET; break; #ifdef TLS_ABOVE_TP case REL_TPOFF: *reloc_addr = tls_val + def.dso->tls.offset + addend; break; #else case REL_TPOFF: *reloc_addr = tls_val - def.dso->tls.offset + addend; break; case REL_TPOFF_NEG: *reloc_addr = def.dso->tls.offset - tls_val + addend; break; #endif case REL_TLSDESC: if (stride < 3) addend = reloc_addr[1]; if (runtime && def.dso->tls_id >= static_tls_cnt) { size_t* new = dl_alloc(2 * sizeof(size_t)); if (!new) { error("Error relocating %s: cannot allocate TLSDESC for %s", dso->l_map.l_name, name); longjmp(*rtld_fail, 1); } new[0] = def.dso->tls_id; new[1] = tls_val + addend; reloc_addr[0] = (size_t)__tlsdesc_dynamic; reloc_addr[1] = (size_t) new; } else { reloc_addr[0] = (size_t)__tlsdesc_static; #ifdef TLS_ABOVE_TP reloc_addr[1] = tls_val + def.dso->tls.offset + addend; #else reloc_addr[1] = tls_val - def.dso->tls.offset + addend; #endif } break; default: error("Error relocating %s: unsupported relocation type %d", dso->l_map.l_name, type); if (runtime) longjmp(*rtld_fail, 1); continue; } } } __NO_SAFESTACK static void unmap_library(struct dso* dso) { if (dso->map && dso->map_len) { munmap(dso->map, dso->map_len); } if (dso->vmar != ZX_HANDLE_INVALID) { _zx_vmar_destroy(dso->vmar); _zx_handle_close(dso->vmar); dso->vmar = ZX_HANDLE_INVALID; } } // app.module_id is always zero, so assignments start with 1. __NO_SAFESTACK NO_ASAN static void assign_module_id(struct dso* dso) { static unsigned int last_module_id; dso->module_id = ++last_module_id; } // Locate the build ID note just after mapping the segments in. // This is called from dls2, so it cannot use any non-static functions. __NO_SAFESTACK NO_ASAN static bool find_buildid_note(struct dso* dso, const Phdr* seg) { const char* end = laddr(dso, seg->p_vaddr + seg->p_filesz); for (const struct gnu_note* n = laddr(dso, seg->p_vaddr); (const char*)n < end; n = (const void*)(n->name.name + ((n->nhdr.n_namesz + 3) & -4) + ((n->nhdr.n_descsz + 3) & -4))) { if (n->nhdr.n_type == NT_GNU_BUILD_ID && n->nhdr.n_namesz == sizeof(GNU_NOTE_NAME) && n->name.word == GNU_NOTE_NAME.word) { dso->build_id_note = n; return true; } } return false; } // TODO(mcgrathr): Remove this all when everything uses markup. // We pre-format the log line for each DSO early so that we can log it // without running any nontrivial code. We use hand-rolled formatting // code to avoid using large and complex code like the printf engine. // Each line looks like "dso: id=... base=0x... name=...\n". #define BUILD_ID_LOG_1 "dso: id=" #define BUILD_ID_LOG_NONE "none" #define BUILD_ID_LOG_2 " base=0x" #define BUILD_ID_LOG_3 " name=" __NO_SAFESTACK static size_t build_id_log_size(struct dso* dso, size_t namelen) { size_t id_size = (dso->build_id_note == NULL ? sizeof(BUILD_ID_LOG_NONE) - 1 : dso->build_id_note->nhdr.n_descsz * 2); return (sizeof(BUILD_ID_LOG_1) - 1 + id_size + sizeof(BUILD_ID_LOG_2) - 1 + (sizeof(size_t) * 2) + sizeof(BUILD_ID_LOG_3) - 1 + namelen + 1); } __NO_SAFESTACK static void format_build_id_log( struct dso* dso, char *buffer, const char *name, size_t namelen) { #define HEXDIGITS "0123456789abcdef" const struct gnu_note* note = dso->build_id_note; dso->build_id_log.iov_base = buffer; memcpy(buffer, BUILD_ID_LOG_1, sizeof(BUILD_ID_LOG_1) - 1); char *p = buffer + sizeof(BUILD_ID_LOG_1) - 1; if (note == NULL) { memcpy(p, BUILD_ID_LOG_NONE, sizeof(BUILD_ID_LOG_NONE) - 1); p += sizeof(BUILD_ID_LOG_NONE) - 1; } else { for (Elf64_Word i = 0; i < note->nhdr.n_descsz; ++i) { uint8_t byte = note->desc[i]; *p++ = HEXDIGITS[byte >> 4]; *p++ = HEXDIGITS[byte & 0xf]; } } memcpy(p, BUILD_ID_LOG_2, sizeof(BUILD_ID_LOG_2) - 1); p += sizeof(BUILD_ID_LOG_2) - 1; uintptr_t base = (uintptr_t)dso->l_map.l_addr; unsigned int shift = sizeof(uintptr_t) * 8; do { shift -= 4; *p++ = HEXDIGITS[(base >> shift) & 0xf]; } while (shift > 0); memcpy(p, BUILD_ID_LOG_3, sizeof(BUILD_ID_LOG_3) - 1); p += sizeof(BUILD_ID_LOG_3) - 1; memcpy(p, name, namelen); p += namelen; *p++ = '\n'; dso->build_id_log.iov_len = p - buffer; #undef HEXDIGITS } __NO_SAFESTACK static void allocate_and_format_build_id_log(struct dso* dso) { const char* name = dso->l_map.l_name; if (name[0] == '\0') name = dso->soname == NULL ? "<application>" : dso->soname; size_t namelen = strlen(name); char *buffer = dl_alloc(build_id_log_size(dso, namelen)); format_build_id_log(dso, buffer, name, namelen); } // TODO(mcgrathr): Remove above when everything uses markup. // Format the markup elements by hand to avoid using large and complex code // like the printf engine. __NO_SAFESTACK static char* format_string(char* p, const char* string, size_t len) { return memcpy(p, string, len) + len; } #define FORMAT_HEX_VALUE_SIZE (2 + (sizeof(uint64_t) * 2)) #define HEXDIGITS "0123456789abcdef" __NO_SAFESTACK static char* format_hex_value( char buffer[FORMAT_HEX_VALUE_SIZE], uint64_t value) { char* p = buffer; if (value == 0) { // No "0x" prefix on zero. *p++ = '0'; } else { *p++ = '0'; *p++ = 'x'; // Skip the high nybbles that are zero. int shift = 60; while ((value >> shift) == 0) { shift -= 4; } do { *p++ = HEXDIGITS[(value >> shift) & 0xf]; shift -= 4; } while (shift >= 0); } return p; } __NO_SAFESTACK static char* format_hex_string(char* p, const uint8_t* string, size_t len) { for (size_t i = 0; i < len; ++i) { uint8_t byte = string[i]; *p++ = HEXDIGITS[byte >> 4]; *p++ = HEXDIGITS[byte & 0xf]; } return p; } // The format theoretically does not constrain the size of build ID notes, // but there is a reasonable upper bound. #define MAX_BUILD_ID_SIZE 64 // Likewise, there's no real limit on the length of module names. // But they're only included in the markup output to be informative, // so truncating them is OK. #define MODULE_NAME_SIZE 64 #define MODULE_ELEMENT_BEGIN "{{{module:" #define MODULE_ELEMENT_BUILD_ID_BEGIN ":elf:" #define MODULE_ELEMENT_END "}}}\n" #define MODULE_ELEMENT_SIZE \ (sizeof(MODULE_ELEMENT_BEGIN) - 1 + FORMAT_HEX_VALUE_SIZE + \ 1 + MODULE_NAME_SIZE + sizeof(MODULE_ELEMENT_BUILD_ID_BEGIN) - 1 + \ (MAX_BUILD_ID_SIZE * 2) + 1 + sizeof(MODULE_ELEMENT_END)) __NO_SAFESTACK static void log_module_element(struct dso* dso) { char buffer[MODULE_ELEMENT_SIZE]; char* p = format_string(buffer, MODULE_ELEMENT_BEGIN, sizeof(MODULE_ELEMENT_BEGIN) - 1); p = format_hex_value(p, dso->module_id); *p++ = ':'; const char* name = dso->l_map.l_name; if (name[0] == '\0') { name = dso->soname == NULL ? "<application>" : dso->soname; } size_t namelen = strlen(name); if (namelen > MODULE_NAME_SIZE) { namelen = MODULE_NAME_SIZE; } p = format_string(p, name, namelen); p = format_string(p, MODULE_ELEMENT_BUILD_ID_BEGIN, sizeof(MODULE_ELEMENT_BUILD_ID_BEGIN) - 1); if (dso->build_id_note) { p = format_hex_string(p, dso->build_id_note->desc, dso->build_id_note->nhdr.n_descsz); } p = format_string(p, MODULE_ELEMENT_END, sizeof(MODULE_ELEMENT_END) - 1); _dl_log_write(buffer, p - buffer); } #define MMAP_ELEMENT_BEGIN "{{{mmap:" #define MMAP_ELEMENT_LOAD_BEGIN ":load:" #define MMAP_ELEMENT_END "}}}\n" #define MMAP_ELEMENT_SIZE \ (sizeof(MMAP_ELEMENT_BEGIN) - 1 + \ FORMAT_HEX_VALUE_SIZE + 1 + \ FORMAT_HEX_VALUE_SIZE + 1 + \ sizeof(MMAP_ELEMENT_LOAD_BEGIN) - 1 + FORMAT_HEX_VALUE_SIZE + 1 + \ 3 + 1 + FORMAT_HEX_VALUE_SIZE) __NO_SAFESTACK static void log_mmap_element(struct dso* dso, const Phdr* ph) { size_t start = ph->p_vaddr & -PAGE_SIZE; size_t end = (ph->p_vaddr + ph->p_memsz + PAGE_SIZE - 1) & -PAGE_SIZE; char buffer[MMAP_ELEMENT_SIZE]; char* p = format_string(buffer, MMAP_ELEMENT_BEGIN, sizeof(MMAP_ELEMENT_BEGIN) - 1); p = format_hex_value(p, saddr(dso, start)); *p++ = ':'; p = format_hex_value(p, end - start); p = format_string(p, MMAP_ELEMENT_LOAD_BEGIN, sizeof(MMAP_ELEMENT_LOAD_BEGIN) - 1); p = format_hex_value(p, dso->module_id); *p++ = ':'; if (ph->p_flags & PF_R) { *p++ = 'r'; } if (ph->p_flags & PF_W) { *p++ = 'w'; } if (ph->p_flags & PF_X) { *p++ = 'x'; } *p++ = ':'; p = format_hex_value(p, start); p = format_string(p, MMAP_ELEMENT_END, sizeof(MMAP_ELEMENT_END) - 1); _dl_log_write(buffer, p - buffer); } // No newline because it's immediately followed by a {{{module:...}}}. #define RESET_ELEMENT "{{{reset}}}" __NO_SAFESTACK static void log_dso(struct dso* dso) { if (dso == head) { // Write the reset element before the first thing listed. _dl_log_write(RESET_ELEMENT, sizeof(RESET_ELEMENT) - 1); } log_module_element(dso); if (dso->phdr) { for (unsigned int i = 0; i < dso->phnum; ++i) { if (dso->phdr[i].p_type == PT_LOAD) { log_mmap_element(dso, &dso->phdr[i]); } } } // TODO(mcgrathr): Remove this when everything uses markup. _dl_log_write(dso->build_id_log.iov_base, dso->build_id_log.iov_len); } __NO_SAFESTACK void _dl_log_unlogged(void) { // The first thread to successfully swap in 0 and get an old value // for unlogged_tail is responsible for logging all the unlogged // DSOs up through that pointer. If dlopen calls move the tail // and another thread then calls into here, we can race with that // thread. So we use a separate atomic_flag on each 'struct dso' // to ensure only one thread prints each one. uintptr_t last_unlogged = atomic_load_explicit(&unlogged_tail, memory_order_acquire); do { if (last_unlogged == 0) return; } while (!atomic_compare_exchange_weak_explicit(&unlogged_tail, &last_unlogged, 0, memory_order_acq_rel, memory_order_relaxed)); for (struct dso* p = head; true; p = dso_next(p)) { if (!atomic_flag_test_and_set_explicit( &p->logged, memory_order_relaxed)) { log_dso(p); } if ((struct dso*)last_unlogged == p) { break; } } } __NO_SAFESTACK NO_ASAN static zx_status_t map_library(zx_handle_t vmo, struct dso* dso) { struct { Ehdr ehdr; // A typical ELF file has 7 or 8 phdrs, so in practice // this is always enough. Life is simpler if there is no // need for dynamic allocation here. Phdr phdrs[16]; } buf; size_t phsize; size_t addr_min = SIZE_MAX, addr_max = 0, map_len; size_t this_min, this_max; size_t nsegs = 0; const Ehdr* const eh = &buf.ehdr; Phdr *ph, *ph0; unsigned char *map = MAP_FAILED, *base; size_t dyn = 0; size_t tls_image = 0; size_t i; size_t l; zx_status_t status = _zx_vmo_get_size(vmo, &l); if (status != ZX_OK) return status; status = _zx_vmo_read(vmo, &buf, 0, sizeof(buf) < l ? sizeof(buf) : l); if (status != ZX_OK) return status; // We cannot support ET_EXEC in the general case, because its fixed // addresses might conflict with where the dynamic linker has already // been loaded. It's also policy in Fuchsia that all executables are // PIEs to maximize ASLR security benefits. So don't even try to // handle loading ET_EXEC. if (l < sizeof *eh || eh->e_type != ET_DYN) goto noexec; phsize = eh->e_phentsize * eh->e_phnum; if (phsize > sizeof(buf.phdrs)) goto noexec; if (eh->e_phoff + phsize > l) { status = _zx_vmo_read(vmo, buf.phdrs, eh->e_phoff, phsize); if (status != ZX_OK) goto error; ph = ph0 = buf.phdrs; } else { ph = ph0 = (void*)((char*)&buf + eh->e_phoff); } const Phdr* first_note = NULL; const Phdr* last_note = NULL; for (i = eh->e_phnum; i; i--, ph = (void*)((char*)ph + eh->e_phentsize)) { switch (ph->p_type) { case PT_LOAD: nsegs++; if (ph->p_vaddr < addr_min) { addr_min = ph->p_vaddr; } if (ph->p_vaddr + ph->p_memsz > addr_max) { addr_max = ph->p_vaddr + ph->p_memsz; } if (ph->p_flags & PF_X) { dso->code_start = addr_min; dso->code_end = addr_max; } break; case PT_DYNAMIC: dyn = ph->p_vaddr; break; case PT_TLS: tls_image = ph->p_vaddr; dso->tls.align = ph->p_align; dso->tls.len = ph->p_filesz; dso->tls.size = ph->p_memsz; break; case PT_GNU_RELRO: dso->relro_start = ph->p_vaddr & -PAGE_SIZE; dso->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE; break; case PT_NOTE: if (first_note == NULL) first_note = ph; last_note = ph; break; case PT_GNU_STACK: if (ph->p_flags & PF_X) { error("%s requires executable stack" " (built with -z execstack?)," " which Fuchsia will never support", dso->soname == NULL ? dso->l_map.l_name : dso->soname); goto noexec; } break; } } if (!dyn) goto noexec; addr_max += PAGE_SIZE - 1; addr_max &= -PAGE_SIZE; addr_min &= -PAGE_SIZE; map_len = addr_max - addr_min; // Allocate a VMAR to reserve the whole address range. Stash // the new VMAR's handle until relocation has finished, because // we need it to adjust page protections for RELRO. uintptr_t vmar_base; status = _zx_vmar_allocate(__zircon_vmar_root_self, ZX_VM_CAN_MAP_READ | ZX_VM_CAN_MAP_WRITE | ZX_VM_CAN_MAP_EXECUTE | ZX_VM_CAN_MAP_SPECIFIC, 0, map_len, &dso->vmar, &vmar_base); if (status != ZX_OK) { error("failed to reserve %zu bytes of address space: %d\n", map_len, status); goto error; } char vmo_name[ZX_MAX_NAME_LEN]; if (_zx_object_get_property(vmo, ZX_PROP_NAME, vmo_name, sizeof(vmo_name)) != ZX_OK || vmo_name[0] == '\0') memcpy(vmo_name, VMO_NAME_UNKNOWN, sizeof(VMO_NAME_UNKNOWN)); dso->map = map = (void*)vmar_base; dso->map_len = map_len; base = map - addr_min; dso->phdr = 0; dso->phnum = 0; for (ph = ph0, i = eh->e_phnum; i; i--, ph = (void*)((char*)ph + eh->e_phentsize)) { if (ph->p_type != PT_LOAD) continue; /* Check if the programs headers are in this load segment, and * if so, record the address for use by dl_iterate_phdr. */ if (!dso->phdr && eh->e_phoff >= ph->p_offset && eh->e_phoff + phsize <= ph->p_offset + ph->p_filesz) { dso->phdr = (void*)(base + ph->p_vaddr + (eh->e_phoff - ph->p_offset)); dso->phnum = eh->e_phnum; dso->phentsize = eh->e_phentsize; } this_min = ph->p_vaddr & -PAGE_SIZE; this_max = (ph->p_vaddr + ph->p_memsz + PAGE_SIZE - 1) & -PAGE_SIZE; size_t off_start = ph->p_offset & -PAGE_SIZE; zx_vm_option_t zx_options = ZX_VM_SPECIFIC | ZX_VM_ALLOW_FAULTS; zx_options |= (ph->p_flags & PF_R) ? ZX_VM_PERM_READ : 0; zx_options |= (ph->p_flags & PF_W) ? ZX_VM_PERM_WRITE : 0; zx_options |= (ph->p_flags & PF_X) ? ZX_VM_PERM_EXECUTE : 0; uintptr_t mapaddr = (uintptr_t)base + this_min; zx_handle_t map_vmo = vmo; size_t map_size = this_max - this_min; if (map_size == 0) continue; if (ph->p_flags & PF_W) { size_t data_size = ((ph->p_vaddr + ph->p_filesz + PAGE_SIZE - 1) & -PAGE_SIZE) - this_min; if (data_size == 0) { // This segment is purely zero-fill. status = _zx_vmo_create(map_size, 0, &map_vmo); if (status == ZX_OK) { char name[ZX_MAX_NAME_LEN] = VMO_NAME_PREFIX_BSS; memcpy(&name[sizeof(VMO_NAME_PREFIX_BSS) - 1], vmo_name, ZX_MAX_NAME_LEN - sizeof(VMO_NAME_PREFIX_BSS)); _zx_object_set_property(map_vmo, ZX_PROP_NAME, name, strlen(name)); } } else { // Get a writable (lazy) copy of the portion of the file VMO. status = _zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE | ZX_VMO_CHILD_RESIZABLE, off_start, data_size, &map_vmo); if (status == ZX_OK && map_size > data_size) { // Extend the writable VMO to cover the .bss pages too. // These pages will be zero-filled, not copied from the // file VMO. status = _zx_vmo_set_size(map_vmo, map_size); if (status != ZX_OK) { _zx_handle_close(map_vmo); goto error; } } if (status == ZX_OK) { char name[ZX_MAX_NAME_LEN] = VMO_NAME_PREFIX_DATA; memcpy(&name[sizeof(VMO_NAME_PREFIX_DATA) - 1], vmo_name, ZX_MAX_NAME_LEN - sizeof(VMO_NAME_PREFIX_DATA)); _zx_object_set_property(map_vmo, ZX_PROP_NAME, name, strlen(name)); } } if (status != ZX_OK) goto error; off_start = 0; } else if (ph->p_memsz > ph->p_filesz) { // Read-only .bss is not a thing. goto noexec; } status = _zx_vmar_map(dso->vmar, zx_options, mapaddr - vmar_base, map_vmo, off_start, map_size, &mapaddr); if (map_vmo != vmo) _zx_handle_close(map_vmo); if (status != ZX_OK) goto error; if (ph->p_memsz > ph->p_filesz) { // The final partial page of data from the file is followed by // whatever the file's contents there are, but in the memory // image that partial page should be all zero. uintptr_t file_end = (uintptr_t)base + ph->p_vaddr + ph->p_filesz; uintptr_t map_end = mapaddr + map_size; if (map_end > file_end) memset((void*)file_end, 0, map_end - file_end); } } dso->l_map.l_addr = (uintptr_t)base; dso->l_map.l_ld = laddr(dso, dyn); if (dso->tls.size) dso->tls.image = laddr(dso, tls_image); for (const Phdr* seg = first_note; seg <= last_note; ++seg) { if (seg->p_type == PT_NOTE && find_buildid_note(dso, seg)) break; } return ZX_OK; noexec: // We overload this to translate into ENOEXEC later. status = ZX_ERR_WRONG_TYPE; error: if (map != MAP_FAILED) unmap_library(dso); if (dso->vmar != ZX_HANDLE_INVALID && !KEEP_DSO_VMAR) _zx_handle_close(dso->vmar); dso->vmar = ZX_HANDLE_INVALID; return status; } __NO_SAFESTACK NO_ASAN static void decode_dyn(struct dso* p) { size_t dyn[DT_NUM]; decode_vec(p->l_map.l_ld, dyn, DT_NUM); p->syms = laddr(p, dyn[DT_SYMTAB]); p->strings = laddr(p, dyn[DT_STRTAB]); if (dyn[0] & (1 << DT_SONAME)) p->soname = p->strings + dyn[DT_SONAME]; if (dyn[0] & (1 << DT_HASH)) p->hashtab = laddr(p, dyn[DT_HASH]); if (dyn[0] & (1 << DT_PLTGOT)) p->got = laddr(p, dyn[DT_PLTGOT]); if (search_vec(p->l_map.l_ld, dyn, DT_GNU_HASH)) p->ghashtab = laddr(p, *dyn); if (search_vec(p->l_map.l_ld, dyn, DT_VERSYM)) p->versym = laddr(p, *dyn); } static size_t count_syms(struct dso* p) { if (p->hashtab) return p->hashtab[1]; size_t nsym, i; uint32_t* buckets = p->ghashtab + 4 + (p->ghashtab[2] * sizeof(size_t) / 4); uint32_t* hashval; for (i = nsym = 0; i < p->ghashtab[0]; i++) { if (buckets[i] > nsym) nsym = buckets[i]; } if (nsym) { hashval = buckets + p->ghashtab[0] + (nsym - p->ghashtab[1]); do nsym++; while (!(*hashval++ & 1)); } return nsym; } __NO_SAFESTACK static struct dso* find_library_in(struct dso* p, const char* name) { while (p != NULL) { if (!strcmp(p->l_map.l_name, name) || (p->soname != NULL && !strcmp(p->soname, name))) { ++p->refcnt; break; } p = dso_next(p); } return p; } __NO_SAFESTACK static struct dso* find_library(const char* name) { // First see if it's in the general list. struct dso* p = find_library_in(head, name); if (p == NULL && detached_head != NULL) { // ldso is not in the list yet, so the first search didn't notice // anything that is only a dependency of ldso, i.e. the vDSO. // See if the lookup by name matches ldso or its dependencies. p = find_library_in(detached_head, name); if (p == &ldso) { // If something depends on libc (&ldso), we actually want // to pull in the entire detached list in its existing // order (&ldso is always last), so that libc stays after // its own dependencies. dso_set_prev(detached_head, tail); dso_set_next(tail, detached_head); tail = p; detached_head = NULL; } else if (p != NULL) { // Take it out of its place in the list rooted at detached_head. if (dso_prev(p) != NULL) dso_set_next(dso_prev(p), dso_next(p)); else detached_head = dso_next(p); if (dso_next(p) != NULL) { dso_set_prev(dso_next(p), dso_prev(p)); dso_set_next(p, NULL); } // Stick it on the main list. dso_set_next(tail, p); dso_set_prev(p, tail); tail = p; } } return p; } #define MAX_BUILDID_SIZE 64 __NO_SAFESTACK static void trace_load(struct dso* p) { static zx_koid_t pid = ZX_KOID_INVALID; if (pid == ZX_KOID_INVALID) { zx_info_handle_basic_t process_info; if (_zx_object_get_info(__zircon_process_self, ZX_INFO_HANDLE_BASIC, &process_info, sizeof(process_info), NULL, NULL) == ZX_OK) { pid = process_info.koid; } else { // No point in continually calling zx_object_get_info. // The first 100 are reserved. pid = 1; } } // Compute extra values useful to tools. // This is done here so that it's only done when necessary. char buildid[MAX_BUILDID_SIZE * 2 + 1]; if (p->build_id_note) { if (p->build_id_note->nhdr.n_descsz > MAX_BUILD_ID_SIZE) { snprintf(buildid, sizeof(buildid), "build_id_too_large_%u", p->build_id_note->nhdr.n_descsz); } else { char* end = format_hex_string(buildid, p->build_id_note->desc, p->build_id_note->nhdr.n_descsz); *end = '\0'; } } else { strcpy(buildid, "<none>"); } const char* name = p->soname == NULL ? "<application>" : p->l_map.l_name; const char* soname = p->soname == NULL ? "<application>" : p->soname; // The output is in multiple lines to cope with damn line wrapping. // N.B. Programs like the Intel Processor Trace decoder parse this output. // Do not change without coordination with consumers. // TODO(ZX-519): Switch to official tracing mechanism when ready. static int seqno; debugmsg("@trace_load: %" PRIu64 ":%da %p %p %p", pid, seqno, p->l_map.l_addr, p->map, p->map + p->map_len); debugmsg("@trace_load: %" PRIu64 ":%db %s", pid, seqno, buildid); debugmsg("@trace_load: %" PRIu64 ":%dc %s %s", pid, seqno, soname, name); ++seqno; } __NO_SAFESTACK static void do_tls_layout(struct dso* p, char* tls_buffer, int n_th) { if (p->tls.size == 0) return; p->tls_id = ++tls_cnt; tls_align = MAXP2(tls_align, p->tls.align); #ifdef TLS_ABOVE_TP p->tls.offset = (tls_offset + p->tls.align - 1) & -p->tls.align; tls_offset = p->tls.offset + p->tls.size; #else tls_offset += p->tls.size + p->tls.align - 1; tls_offset -= (tls_offset + (uintptr_t)p->tls.image) & (p->tls.align - 1); p->tls.offset = tls_offset; #endif if (tls_buffer != NULL) { p->new_dtv = (void*)(-sizeof(size_t) & (uintptr_t)(tls_buffer + sizeof(size_t))); p->new_tls = (void*)(p->new_dtv + n_th * (tls_cnt + 1)); } if (tls_tail) tls_tail->next = &p->tls; else libc.tls_head = &p->tls; tls_tail = &p->tls; } __NO_SAFESTACK static zx_status_t load_library_vmo(zx_handle_t vmo, const char* name, int rtld_mode, struct dso* needed_by, struct dso** loaded) { struct dso *p, temp_dso = {}; size_t alloc_size; int n_th = 0; if (rtld_mode & RTLD_NOLOAD) { *loaded = NULL; return ZX_OK; } zx_status_t status = map_library(vmo, &temp_dso); if (status != ZX_OK) return status; decode_dyn(&temp_dso); if (temp_dso.soname != NULL) { // Now check again if we opened the same file a second time. // That is, a file with the same DT_SONAME string. p = find_library(temp_dso.soname); if (p != NULL) { unmap_library(&temp_dso); *loaded = p; return ZX_OK; } } // If this was loaded by VMO rather than by name, we have to synthesize // one. If the SONAME if present. Otherwise synthesize something // informative from the VMO (that won't look like any sensible SONAME). char synthetic_name[ZX_MAX_NAME_LEN + 32]; if (name == NULL) name = temp_dso.soname; if (name == NULL) { char vmo_name[ZX_MAX_NAME_LEN]; if (_zx_object_get_property(vmo, ZX_PROP_NAME, vmo_name, sizeof(vmo_name)) != ZX_OK) vmo_name[0] = '\0'; zx_info_handle_basic_t info; if (_zx_object_get_info(vmo, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), NULL, NULL) != ZX_OK) { name = "<dlopen_vmo>"; } else { if (vmo_name[0] == '\0') { snprintf(synthetic_name, sizeof(synthetic_name), "<VMO#%" PRIu64 ">", info.koid); } else { snprintf(synthetic_name, sizeof(synthetic_name), "<VMO#%" PRIu64 "=%s>", info.koid, vmo_name); } name = synthetic_name; } } // Calculate how many slots are needed for dependencies. size_t ndeps = 1; // Account for a NULL terminator. for (size_t i = 0; temp_dso.l_map.l_ld[i].d_tag; i++) { if (temp_dso.l_map.l_ld[i].d_tag == DT_NEEDED) ++ndeps; } /* Allocate storage for the new DSO. When there is TLS, this * storage must include a reservation for all pre-existing * threads to obtain copies of both the new TLS, and an * extended DTV capable of storing an additional slot for * the newly-loaded DSO. */ size_t namelen = strlen(name); size_t build_id_log_len = build_id_log_size(&temp_dso, namelen); alloc_size = (sizeof *p + ndeps * sizeof(p->deps[0]) + namelen + 1 + build_id_log_len); if (runtime && temp_dso.tls.image) { size_t per_th = temp_dso.tls.size + temp_dso.tls.align + sizeof(void*) * (tls_cnt + 3); n_th = atomic_load(&libc.thread_count); if (n_th > SSIZE_MAX / per_th) alloc_size = SIZE_MAX; else alloc_size += n_th * per_th; } p = dl_alloc(alloc_size); if (!p) { unmap_library(&temp_dso); return ZX_ERR_NO_MEMORY; } *p = temp_dso; p->refcnt = 1; p->needed_by = needed_by; p->l_map.l_name = (void*)&p->buf[ndeps]; memcpy(p->l_map.l_name, name, namelen); p->l_map.l_name[namelen] = '\0'; assign_module_id(p); format_build_id_log(p, p->l_map.l_name + namelen + 1, p->l_map.l_name, namelen); if (runtime) do_tls_layout(p, p->l_map.l_name + namelen + 1 + build_id_log_len, n_th); dso_set_next(tail, p); dso_set_prev(p, tail); tail = p; *loaded = p; return ZX_OK; } __NO_SAFESTACK static zx_status_t load_library(const char* name, int rtld_mode, struct dso* needed_by, struct dso** loaded) { if (!*name) return ZX_ERR_INVALID_ARGS; *loaded = find_library(name); if (*loaded != NULL) return ZX_OK; zx_handle_t vmo; zx_status_t status = get_library_vmo(name, &vmo); if (status == ZX_OK) { status = load_library_vmo(vmo, name, rtld_mode, needed_by, loaded); _zx_handle_close(vmo); } return status; } __NO_SAFESTACK static void load_deps(struct dso* p) { for (; p; p = dso_next(p)) { struct dso** deps = NULL; // The two preallocated DSOs don't get space allocated for ->deps. if (runtime && p->deps == NULL && p != &ldso && p != &vdso) deps = p->deps = p->buf; for (size_t i = 0; p->l_map.l_ld[i].d_tag; i++) { if (p->l_map.l_ld[i].d_tag != DT_NEEDED) continue; const char* name = p->strings + p->l_map.l_ld[i].d_un.d_val; struct dso* dep; zx_status_t status = load_library(name, 0, p, &dep); if (status != ZX_OK) { error("Error loading shared library %s: %s (needed by %s)", name, _zx_status_get_string(status), p->l_map.l_name); if (runtime) longjmp(*rtld_fail, 1); } else if (deps != NULL) { *deps++ = dep; } } } } __NO_SAFESTACK NO_ASAN static void reloc_all(struct dso* p) { size_t dyn[DT_NUM]; for (; p; p = dso_next(p)) { if (p->relocated) continue; decode_vec(p->l_map.l_ld, dyn, DT_NUM); // _dl_start did apply_relr already. if (p != &ldso) { apply_relr(p->l_map.l_addr, laddr(p, dyn[DT_RELR]), dyn[DT_RELRSZ]); } do_relocs(p, laddr(p, dyn[DT_JMPREL]), dyn[DT_PLTRELSZ], 2 + (dyn[DT_PLTREL] == DT_RELA)); do_relocs(p, laddr(p, dyn[DT_REL]), dyn[DT_RELSZ], 2); do_relocs(p, laddr(p, dyn[DT_RELA]), dyn[DT_RELASZ], 3); if (head != &ldso && p->relro_start != p->relro_end) { zx_status_t status = _zx_vmar_protect(p->vmar, ZX_VM_PERM_READ, saddr(p, p->relro_start), p->relro_end - p->relro_start); if (status == ZX_ERR_BAD_HANDLE && p == &ldso && p->vmar == ZX_HANDLE_INVALID) { debugmsg("No VMAR_LOADED handle received;" " cannot protect RELRO for %s\n", p->l_map.l_name); } else if (status != ZX_OK) { error("Error relocating %s: RELRO protection" " %p+%#zx failed: %s", p->l_map.l_name, laddr(p, p->relro_start), p->relro_end - p->relro_start, _zx_status_get_string(status)); if (runtime) longjmp(*rtld_fail, 1); } } // Hold the VMAR handle only long enough to apply RELRO. // Now it's no longer needed and the mappings cannot be // changed any more (only unmapped). if (p->vmar != ZX_HANDLE_INVALID && !KEEP_DSO_VMAR) { _zx_handle_close(p->vmar); p->vmar = ZX_HANDLE_INVALID; } p->relocated = 1; } } __NO_SAFESTACK NO_ASAN static void kernel_mapped_dso(struct dso* p) { size_t min_addr = -1, max_addr = 0, cnt; const Phdr* ph = p->phdr; for (cnt = p->phnum; cnt--; ph = (void*)((char*)ph + p->phentsize)) { switch (ph->p_type) { case PT_LOAD: if (ph->p_vaddr < min_addr) min_addr = ph->p_vaddr; if (ph->p_vaddr + ph->p_memsz > max_addr) max_addr = ph->p_vaddr + ph->p_memsz; break; case PT_DYNAMIC: p->l_map.l_ld = laddr(p, ph->p_vaddr); break; case PT_GNU_RELRO: p->relro_start = ph->p_vaddr & -PAGE_SIZE; p->relro_end = (ph->p_vaddr + ph->p_memsz) & -PAGE_SIZE; break; case PT_NOTE: if (p->build_id_note == NULL) find_buildid_note(p, ph); break; } } min_addr &= -PAGE_SIZE; max_addr = (max_addr + PAGE_SIZE - 1) & -PAGE_SIZE; p->map = laddr(p, min_addr); p->map_len = max_addr - min_addr; assign_module_id(p); } void __libc_exit_fini(void) { struct dso* p; size_t dyn[DT_NUM]; for (p = fini_head; p; p = p->fini_next) { if (!p->constructed) continue; decode_vec(p->l_map.l_ld, dyn, DT_NUM); if (dyn[0] & (1 << DT_FINI_ARRAY)) { size_t n = dyn[DT_FINI_ARRAYSZ] / sizeof(size_t); size_t* fn = (size_t*)laddr(p, dyn[DT_FINI_ARRAY]) + n; while (n--) ((void (*)(void)) * --fn)(); } #ifndef NO_LEGACY_INITFINI if ((dyn[0] & (1 << DT_FINI)) && dyn[DT_FINI]) fpaddr(p, dyn[DT_FINI])(); #endif } } static void do_init_fini(struct dso* p) { size_t dyn[DT_NUM]; /* Allow recursive calls that arise when a library calls * dlopen from one of its constructors, but block any * other threads until all ctors have finished. */ pthread_mutex_lock(&init_fini_lock); for (; p; p = dso_prev(p)) { if (p->constructed) continue; p->constructed = 1; decode_vec(p->l_map.l_ld, dyn, DT_NUM); if (dyn[0] & ((1 << DT_FINI) | (1 << DT_FINI_ARRAY))) { p->fini_next = fini_head; fini_head = p; } #ifndef NO_LEGACY_INITFINI if ((dyn[0] & (1 << DT_INIT)) && dyn[DT_INIT]) fpaddr(p, dyn[DT_INIT])(); #endif if (dyn[0] & (1 << DT_INIT_ARRAY)) { size_t n = dyn[DT_INIT_ARRAYSZ] / sizeof(size_t); size_t* fn = laddr(p, dyn[DT_INIT_ARRAY]); while (n--) ((void (*)(void)) * fn++)(); } } pthread_mutex_unlock(&init_fini_lock); } void __libc_start_init(void) { // If a preinit hook spawns a thread that calls dlopen, that thread will // get to do_init_fini and block on the lock. Now the main thread finishes // preinit hooks and releases the lock. Then it's a race for which thread // gets the lock and actually runs all the normal constructors. This is // expected, but to avoid such races preinit hooks should be very careful // about what they do and rely on. pthread_mutex_lock(&init_fini_lock); size_t dyn[DT_NUM]; decode_vec(head->l_map.l_ld, dyn, DT_NUM); if (dyn[0] & (1ul << DT_PREINIT_ARRAY)) { size_t n = dyn[DT_PREINIT_ARRAYSZ] / sizeof(size_t); size_t* fn = laddr(head, dyn[DT_PREINIT_ARRAY]); while (n--) ((void (*)(void)) * fn++)(); } pthread_mutex_unlock(&init_fini_lock); do_init_fini(tail); } static void dl_debug_state(void) {} weak_alias(dl_debug_state, _dl_debug_state); __attribute__((__visibility__("hidden"))) void* __tls_get_new(size_t* v) { pthread_t self = __pthread_self(); if (v[0] <= (size_t)self->head.dtv[0]) { return (char*)self->head.dtv[v[0]] + v[1] + DTP_OFFSET; } /* This is safe without any locks held because, if the caller * is able to request the Nth entry of the DTV, the DSO list * must be valid at least that far out and it was synchronized * at program startup or by an already-completed call to dlopen. */ struct dso* p; for (p = head; p->tls_id != v[0]; p = dso_next(p)) ; /* Get new DTV space from new DSO if needed */ if (v[0] > (size_t)self->head.dtv[0]) { void** newdtv = p->new_dtv + (v[0] + 1) * atomic_fetch_add(&p->new_dtv_idx, 1); memcpy(newdtv, self->head.dtv, ((size_t)self->head.dtv[0] + 1) * sizeof(void*)); newdtv[0] = (void*)v[0]; self->head.dtv = newdtv; } /* Get new TLS memory from all new DSOs up to the requested one */ unsigned char* mem; for (p = head;; p = dso_next(p)) { if (!p->tls_id || self->head.dtv[p->tls_id]) continue; mem = p->new_tls + (p->tls.size + p->tls.align) * atomic_fetch_add(&p->new_tls_idx, 1); mem += ((uintptr_t)p->tls.image - (uintptr_t)mem) & (p->tls.align - 1); self->head.dtv[p->tls_id] = mem; memcpy(mem, p->tls.image, p->tls.len); if (p->tls_id == v[0]) break; } return mem + v[1] + DTP_OFFSET; } __NO_SAFESTACK struct pthread* __init_main_thread(zx_handle_t thread_self) { pthread_attr_t attr = DEFAULT_PTHREAD_ATTR; char thread_self_name[ZX_MAX_NAME_LEN]; if (_zx_object_get_property(thread_self, ZX_PROP_NAME, thread_self_name, sizeof(thread_self_name)) != ZX_OK) strcpy(thread_self_name, "(initial-thread)"); thrd_t td = __allocate_thread(attr._a_guardsize, attr._a_stacksize, thread_self_name, NULL); if (td == NULL) { debugmsg("No memory for %zu bytes thread-local storage.\n", libc.tls_size); _exit(127); } zx_status_t status = zxr_thread_adopt(thread_self, &td->zxr_thread); if (status != ZX_OK) __builtin_trap(); zxr_tp_set(thread_self, pthread_to_tp(td)); // Now that the thread descriptor is set up, it's safe to use the // dlerror machinery. runtime = 1; return td; } __NO_SAFESTACK static void update_tls_size(void) { libc.tls_cnt = tls_cnt; libc.tls_align = tls_align; libc.tls_size = ALIGN((1 + tls_cnt) * sizeof(void*) + tls_offset + sizeof(struct pthread) + tls_align * 2, tls_align); // TODO(mcgrathr): The TLS block is always allocated in whole pages. // We should keep track of the available slop to the end of the page // and make dlopen use that for new dtv/TLS space when it fits. } /* Stage 1 of the dynamic linker is defined in dlstart.c. It calls the * following stage 2 and stage 3 functions via primitive symbolic lookup * since it does not have access to their addresses to begin with. */ /* Stage 2 of the dynamic linker is called after relative relocations * have been processed. It can make function calls to static functions * and access string literals and static data, but cannot use extern * symbols. Its job is to perform symbolic relocations on the dynamic * linker itself, but some of the relocations performed may need to be * replaced later due to copy relocations in the main program. */ static dl_start_return_t __dls3(void* start_arg); __NO_SAFESTACK NO_ASAN __attribute__((__visibility__("hidden"))) dl_start_return_t __dls2(void* start_arg, void* vdso_map) { ldso.l_map.l_addr = (uintptr_t)__ehdr_start; Ehdr* ehdr = (void*)ldso.l_map.l_addr; ldso.l_map.l_name = (char*)"libc.so"; ldso.global = -1; ldso.phnum = ehdr->e_phnum; ldso.phdr = laddr(&ldso, ehdr->e_phoff); ldso.phentsize = ehdr->e_phentsize; kernel_mapped_dso(&ldso); decode_dyn(&ldso); if (vdso_map != NULL) { // The vDSO was mapped in by our creator. Stitch it in as // a preloaded shared object right away, so ld.so itself // can depend on it and require its symbols. vdso.l_map.l_addr = (uintptr_t)vdso_map; vdso.l_map.l_name = (char*)"<vDSO>"; vdso.global = -1; Ehdr* ehdr = vdso_map; vdso.phnum = ehdr->e_phnum; vdso.phdr = laddr(&vdso, ehdr->e_phoff); vdso.phentsize = ehdr->e_phentsize; kernel_mapped_dso(&vdso); decode_dyn(&vdso); dso_set_prev(&vdso, &ldso); dso_set_next(&ldso, &vdso); tail = &vdso; } /* Prepare storage for to save clobbered REL addends so they * can be reused in stage 3. There should be very few. If * something goes wrong and there are a huge number, abort * instead of risking stack overflow. */ size_t dyn[DT_NUM]; decode_vec(ldso.l_map.l_ld, dyn, DT_NUM); size_t* rel = laddr(&ldso, dyn[DT_REL]); size_t rel_size = dyn[DT_RELSZ]; size_t symbolic_rel_cnt = 0; apply_addends_to = rel; for (; rel_size; rel += 2, rel_size -= 2 * sizeof(size_t)) if (R_TYPE(rel[1]) != REL_RELATIVE) symbolic_rel_cnt++; if (symbolic_rel_cnt >= ADDEND_LIMIT) __builtin_trap(); size_t addends[symbolic_rel_cnt + 1]; saved_addends = addends; head = &ldso; reloc_all(&ldso); ldso.relocated = 0; // Make sure all the relocations have landed before calling __dls3, // which relies on them. atomic_signal_fence(memory_order_seq_cst); return __dls3(start_arg); } #define LIBS_VAR "LD_DEBUG=" #define TRACE_VAR "LD_TRACE=" __NO_SAFESTACK static void scan_env_strings(const char* strings, const char* limit, uint32_t count) { while (count-- > 0) { char* end = memchr(strings, '\0', limit - strings); if (end == NULL) { break; } if (end - strings >= sizeof(LIBS_VAR) - 1 && !memcmp(strings, LIBS_VAR, sizeof(LIBS_VAR) - 1)) { if (strings[sizeof(LIBS_VAR) - 1] != '\0') { log_libs = true; } } else if (end - strings >= sizeof(TRACE_VAR) - 1 && !memcmp(strings, TRACE_VAR, sizeof(TRACE_VAR) - 1)) { // Features like Intel Processor Trace require specific output in a // specific format. Thus this output has its own env var. if (strings[sizeof(TRACE_VAR) - 1] != '\0') { trace_maps = true; } } strings = end + 1; } } /* Stage 3 of the dynamic linker is called with the dynamic linker/libc * fully functional. Its job is to load (if not already loaded) and * process dependencies and relocations for the main application and * transfer control to its entry point. */ __NO_SAFESTACK static void* dls3(zx_handle_t exec_vmo, const char* argv0, const char* env_strings, const char* env_strings_limit, uint32_t env_strings_count) { // First load our own dependencies. Usually this will be just the // vDSO, which is already loaded, so there will be nothing to do. // In a sanitized build, we'll depend on the sanitizer runtime DSO // and load that now (and its dependencies, such as the unwinder). load_deps(&ldso); // Now reorder the list so that we appear last, after all our // dependencies. This ensures that e.g. the sanitizer runtime's // malloc will be chosen over ours, even if the application // doesn't itself depend on the sanitizer runtime SONAME. dso_set_prev(dso_next(&ldso), NULL); detached_head = dso_next(&ldso); dso_set_prev(&ldso, tail); dso_set_next(&ldso, NULL); dso_set_next(tail, &ldso); static struct dso app; libc.page_size = PAGE_SIZE; scan_env_strings(env_strings, env_strings_limit, env_strings_count); zx_status_t status = map_library(exec_vmo, &app); _zx_handle_close(exec_vmo); if (status != ZX_OK) { debugmsg("%s: %s: Not a valid dynamic program (%s)\n", ldso.l_map.l_name, argv0, _zx_status_get_string(status)); _exit(1); } app.l_map.l_name = (char*)argv0; if (app.tls.size) { libc.tls_head = tls_tail = &app.tls; app.tls_id = tls_cnt = 1; #ifdef TLS_ABOVE_TP app.tls.offset = (tls_offset + app.tls.align - 1) & -app.tls.align; tls_offset = app.tls.offset + app.tls.size; #else tls_offset = app.tls.offset = app.tls.size + (-((uintptr_t)app.tls.image + app.tls.size) & (app.tls.align - 1)); #endif tls_align = MAXP2(tls_align, app.tls.align); } app.global = 1; decode_dyn(&app); // Format the build ID log lines for the three special cases. allocate_and_format_build_id_log(&ldso); allocate_and_format_build_id_log(&vdso); allocate_and_format_build_id_log(&app); /* Initial dso chain consists only of the app. */ head = tail = &app; // Load preload/needed libraries, add their symbols to the global // namespace, and perform all remaining relocations. // // Do TLS layout for DSOs after loading, but before relocation. // This needs to be after the main program's TLS setup (just // above), which has to be the first since it can use static TLS // offsets (local-exec TLS model) that are presumed to start at // the beginning of the static TLS block. But we may have loaded // some libraries (sanitizer runtime) before that, so we don't do // each library's TLS setup directly in load_library_vmo. load_deps(&app); app.global = 1; for (struct dso* p = dso_next(&app); p != NULL; p = dso_next(p)) { p->global = 1; do_tls_layout(p, NULL, 0); } for (size_t i = 0; app.l_map.l_ld[i].d_tag; i++) { if (!DT_DEBUG_INDIRECT && app.l_map.l_ld[i].d_tag == DT_DEBUG) app.l_map.l_ld[i].d_un.d_ptr = (size_t)&debug; if (DT_DEBUG_INDIRECT && app.l_map.l_ld[i].d_tag == DT_DEBUG_INDIRECT) { size_t* ptr = (size_t*)app.l_map.l_ld[i].d_un.d_ptr; *ptr = (size_t)&debug; } } /* The main program must be relocated LAST since it may contin * copy relocations which depend on libraries' relocations. */ reloc_all(dso_next(&app)); reloc_all(&app); update_tls_size(); static_tls_cnt = tls_cnt; if (ldso_fail) _exit(127); // Logically we could now switch to "runtime mode", because // startup-time dynamic linking work per se is done now. However, // the real concrete meaning of "runtime mode" is that the dlerror // machinery is usable. It's not usable until the thread descriptor // has been set up. So the switch to "runtime mode" happens in // __init_main_thread instead. atomic_init(&unlogged_tail, (uintptr_t)tail); debug.r_version = 1; debug.r_brk = (uintptr_t)dl_debug_state; debug.r_map = &head->l_map; debug.r_ldbase = ldso.l_map.l_addr; debug.r_state = 0; // The ZX_PROP_PROCESS_DEBUG_ADDR being set to 1 on startup is a signal // to issue a debug breakpoint after setting the property to signal to a // debugger that the property is now valid. intptr_t existing_debug_addr = 0; status = _zx_object_get_property(__zircon_process_self, ZX_PROP_PROCESS_DEBUG_ADDR, &existing_debug_addr, sizeof(existing_debug_addr)); bool break_after_set = (status == ZX_OK) && (existing_debug_addr == ZX_PROCESS_DEBUG_ADDR_BREAK_ON_SET); status = _zx_object_set_property(__zircon_process_self, ZX_PROP_PROCESS_DEBUG_ADDR, &_dl_debug_addr, sizeof(_dl_debug_addr)); if (status != ZX_OK) { // Bummer. Crashlogger backtraces, debugger sessions, etc. will be // problematic, but this isn't fatal. // TODO(dje): Is there a way to detect we're here because of being // an injected process (launchpad_start_injected)? IWBN to print a // warning here but launchpad_start_injected can trigger this. } if (break_after_set) { debug_break(); } _dl_debug_state(); if (log_libs) _dl_log_unlogged(); if (trace_maps) { for (struct dso* p = &app; p != NULL; p = dso_next(p)) { trace_load(p); } } // Reset from the argv0 value so we don't save a dangling pointer // into the caller's stack frame. app.l_map.l_name = (char*)""; // Check for a PT_GNU_STACK header requesting a main thread stack size. libc.stack_size = ZIRCON_DEFAULT_STACK_SIZE; for (size_t i = 0; i < app.phnum; i++) { if (app.phdr[i].p_type == PT_GNU_STACK) { size_t size = app.phdr[i].p_memsz; if (size > 0) libc.stack_size = size; break; } } const Ehdr* ehdr = (void*)app.map; return laddr(&app, ehdr->e_entry); } __NO_SAFESTACK NO_ASAN static dl_start_return_t __dls3(void* start_arg) { zx_handle_t bootstrap = (uintptr_t)start_arg; uint32_t nbytes, nhandles; zx_status_t status = processargs_message_size(bootstrap, &nbytes, &nhandles); if (status != ZX_OK) { error("processargs_message_size bootstrap handle %#x failed: %d (%s)", bootstrap, status, _zx_status_get_string(status)); nbytes = nhandles = 0; } PROCESSARGS_BUFFER(buffer, nbytes); zx_handle_t handles[nhandles]; zx_proc_args_t* procargs; uint32_t* handle_info; if (status == ZX_OK) status = processargs_read(bootstrap, buffer, nbytes, handles, nhandles, &procargs, &handle_info); if (status != ZX_OK) { error("bad message of %u bytes, %u handles" " from bootstrap handle %#x: %d (%s)", nbytes, nhandles, bootstrap, status, _zx_status_get_string(status)); nbytes = nhandles = 0; } zx_handle_t exec_vmo = ZX_HANDLE_INVALID; for (int i = 0; i < nhandles; ++i) { switch (PA_HND_TYPE(handle_info[i])) { case PA_LDSVC_LOADER: if (loader_svc != ZX_HANDLE_INVALID || handles[i] == ZX_HANDLE_INVALID) { error("bootstrap message bad LOADER_SVC %#x vs %#x", handles[i], loader_svc); } loader_svc = handles[i]; break; case PA_VMO_EXECUTABLE: if (exec_vmo != ZX_HANDLE_INVALID || handles[i] == ZX_HANDLE_INVALID) { error("bootstrap message bad EXEC_VMO %#x vs %#x", handles[i], exec_vmo); } exec_vmo = handles[i]; break; case PA_FD: if (logger != ZX_HANDLE_INVALID || handles[i] == ZX_HANDLE_INVALID) { error("bootstrap message bad FD %#x vs %#x", handles[i], logger); } logger = handles[i]; break; case PA_VMAR_LOADED: if (ldso.vmar != ZX_HANDLE_INVALID || handles[i] == ZX_HANDLE_INVALID) { error("bootstrap message bad VMAR_LOADED %#x vs %#x", handles[i], ldso.vmar); } ldso.vmar = handles[i]; break; case PA_PROC_SELF: __zircon_process_self = handles[i]; break; case PA_VMAR_ROOT: __zircon_vmar_root_self = handles[i]; break; default: _zx_handle_close(handles[i]); break; } } // TODO(mcgrathr): For now, always use a kernel log channel. // This needs to be replaced by a proper unprivileged logging scheme ASAP. if (logger == ZX_HANDLE_INVALID) { _zx_debuglog_create(ZX_HANDLE_INVALID, 0, &logger); } if (__zircon_process_self == ZX_HANDLE_INVALID) error("bootstrap message bad no proc self"); if (__zircon_vmar_root_self == ZX_HANDLE_INVALID) error("bootstrap message bad no root vmar"); // At this point we can make system calls and have our essential // handles, so things are somewhat normal. early_init(); // The initial processargs message may not pass the application // name or any other arguments, so we check that condition. void* entry = dls3(exec_vmo, procargs->args_num == 0 ? "" : (const char*)&buffer[procargs->args_off], (const char*)&buffer[procargs->environ_off], (const char*)&buffer[nbytes], procargs->environ_num); if (vdso.global <= 0) { // Nothing linked against the vDSO. Ideally we would unmap the // vDSO, but there is no way to do it because the unmap system call // would try to return to the vDSO code and crash. if (ldso.global < 0) { // TODO(mcgrathr): We could free all heap data structures, and // with some vDSO assistance unmap ourselves and unwind back to // the user entry point. Thus a program could link against the // vDSO alone and not use this libc/ldso at all after startup. // We'd need to be sure there are no TLSDESC entries pointing // back to our code, but other than that there should no longer // be a way to enter our code. } else { debugmsg("Dynamic linker %s doesn't link in vDSO %s???\n", ldso.l_map.l_name, vdso.l_map.l_name); _exit(127); } } else if (ldso.global <= 0) { // This should be impossible. __builtin_trap(); } return DL_START_RETURN(entry, start_arg); } // Do sanitizer setup and whatever else must be done before dls3. __NO_SAFESTACK NO_ASAN static void early_init(void) { #if __has_feature(address_sanitizer) __asan_early_init(); #endif #ifdef DYNLINK_LDSVC_CONFIG // Inform the loader service to look for libraries of the right variant. loader_svc_config(DYNLINK_LDSVC_CONFIG); #elif __has_feature(address_sanitizer) // Inform the loader service that we prefer ASan-supporting libraries. loader_svc_config("asan"); #endif } static void set_global(struct dso* p, int global) { if (p->global > 0) { // Short-circuit if it's already fully global. Its deps will be too. return; } else if (p->global == global) { // This catches circular references as well as other redundant walks. return; } p->global = global; if (p->deps != NULL) { for (struct dso **dep = p->deps; *dep != NULL; ++dep) { set_global(*dep, global); } } } static void* dlopen_internal(zx_handle_t vmo, const char* file, int mode) { pthread_rwlock_wrlock(&lock); __thread_allocation_inhibit(); struct dso* orig_tail = tail; struct dso* p; zx_status_t status = (vmo != ZX_HANDLE_INVALID ? load_library_vmo(vmo, file, mode, head, &p) : load_library(file, mode, head, &p)); if (status != ZX_OK) { error("Error loading shared library %s: %s", file, _zx_status_get_string(status)); fail: __thread_allocation_release(); pthread_rwlock_unlock(&lock); return NULL; } if (p == NULL) { if (!(mode & RTLD_NOLOAD)) __builtin_trap(); error("Library %s is not already loaded", file); goto fail; } struct tls_module* orig_tls_tail = tls_tail; size_t orig_tls_cnt = tls_cnt; size_t orig_tls_offset = tls_offset; size_t orig_tls_align = tls_align; struct dl_alloc_checkpoint checkpoint; dl_alloc_checkpoint(&checkpoint); jmp_buf jb; rtld_fail = &jb; if (setjmp(*rtld_fail)) { /* Clean up anything new that was (partially) loaded */ if (p && p->deps) set_global(p, 0); for (p = dso_next(orig_tail); p; p = dso_next(p)) unmap_library(p); if (!orig_tls_tail) libc.tls_head = 0; tls_tail = orig_tls_tail; tls_cnt = orig_tls_cnt; tls_offset = orig_tls_offset; tls_align = orig_tls_align; tail = orig_tail; dso_set_next(tail, NULL); dl_alloc_rollback(&checkpoint); goto fail; } /* First load handling */ if (!p->deps) { load_deps(p); set_global(p, -1); reloc_all(p); set_global(p, 0); } if (mode & RTLD_GLOBAL) { set_global(p, 1); } update_tls_size(); _dl_debug_state(); if (trace_maps) { trace_load(p); } // Allow thread creation, now that the TLS bookkeeping is consistent. __thread_allocation_release(); // Bump the dl_iterate_phdr dlpi_adds counter. gencnt++; // Collect the current new tail before we release the lock. // Another dlopen can come in and advance the tail, but we // alone are responsible for making sure that do_init_fini // starts with the first object we just added. struct dso* new_tail = tail; // The next _dl_log_unlogged can safely read the 'struct dso' list from // head up through new_tail. Most fields will never change again. atomic_store_explicit(&unlogged_tail, (uintptr_t)new_tail, memory_order_release); pthread_rwlock_unlock(&lock); if (log_libs) _dl_log_unlogged(); do_init_fini(new_tail); return p; } void* dlopen(const char* file, int mode) { if (!file) return head; return dlopen_internal(ZX_HANDLE_INVALID, file, mode); } void* dlopen_vmo(zx_handle_t vmo, int mode) { if (vmo == ZX_HANDLE_INVALID) { errno = EINVAL; return NULL; } return dlopen_internal(vmo, NULL, mode); } zx_handle_t dl_set_loader_service(zx_handle_t new_svc) { zx_handle_t old_svc; pthread_rwlock_wrlock(&lock); old_svc = loader_svc; loader_svc = new_svc; pthread_rwlock_unlock(&lock); return old_svc; } __attribute__((__visibility__("hidden"))) int __dl_invalid_handle(void* h) { struct dso* p; for (p = head; p; p = dso_next(p)) if (h == p) return 0; error("Invalid library handle %p", (void*)h); return 1; } static void* addr2dso(size_t a) { struct dso* p; for (p = head; p; p = dso_next(p)) { if (a - (size_t)p->map < p->map_len) return p; } return 0; } void* __tls_get_addr(size_t*); static bool find_sym_for_dlsym(struct dso* p, const char* name, uint32_t* name_gnu_hash, uint32_t* name_sysv_hash, void** result) { const Sym* sym; if (p->ghashtab != NULL) { if (*name_gnu_hash == 0) *name_gnu_hash = gnu_hash(name); sym = gnu_lookup(*name_gnu_hash, p->ghashtab, p, name); } else { if (*name_sysv_hash == 0) *name_sysv_hash = sysv_hash(name); sym = sysv_lookup(name, *name_sysv_hash, p); } if (sym && (sym->st_info & 0xf) == STT_TLS) { *result = __tls_get_addr((size_t[]){p->tls_id, sym->st_value}); return true; } if (sym && sym->st_value && (1 << (sym->st_info & 0xf) & OK_TYPES)) { *result = laddr(p, sym->st_value); return true; } if (p->deps) { for (struct dso** dep = p->deps; *dep != NULL; ++dep) { if (find_sym_for_dlsym(*dep, name, name_gnu_hash, name_sysv_hash, result)) return true; } } return false; } static void* do_dlsym(struct dso* p, const char* s, void* ra) { if (p == head || p == RTLD_DEFAULT || p == RTLD_NEXT) { if (p == RTLD_DEFAULT) { p = head; } else if (p == RTLD_NEXT) { p = addr2dso((size_t)ra); if (!p) p = head; p = dso_next(p); } struct symdef def = find_sym(p, s, 0); if (!def.sym) goto failed; if ((def.sym->st_info & 0xf) == STT_TLS) return __tls_get_addr((size_t[]){def.dso->tls_id, def.sym->st_value}); return laddr(def.dso, def.sym->st_value); } if (__dl_invalid_handle(p)) return 0; uint32_t gnu_hash = 0, sysv_hash = 0; void* result; if (find_sym_for_dlsym(p, s, &gnu_hash, &sysv_hash, &result)) return result; failed: error("Symbol not found: %s", s); return 0; } int dladdr(const void* addr, Dl_info* info) { struct dso* p; pthread_rwlock_rdlock(&lock); p = addr2dso((size_t)addr); pthread_rwlock_unlock(&lock); if (!p) return 0; Sym* bestsym = NULL; void* best = 0; Sym* sym = p->syms; uint32_t nsym = count_syms(p); for (; nsym; nsym--, sym++) { if (sym->st_value && (1 << (sym->st_info & 0xf) & OK_TYPES) && (1 << (sym->st_info >> 4) & OK_BINDS)) { void* symaddr = laddr(p, sym->st_value); if (symaddr > addr || symaddr < best) continue; best = symaddr; bestsym = sym; if (addr == symaddr) break; } } info->dli_fname = p->l_map.l_name; info->dli_fbase = (void*)p->l_map.l_addr; info->dli_sname = bestsym == NULL ? NULL : p->strings + bestsym->st_name; info->dli_saddr = bestsym == NULL ? NULL : best; return 1; } void* dlsym(void* restrict p, const char* restrict s) { void* res; pthread_rwlock_rdlock(&lock); res = do_dlsym(p, s, __builtin_return_address(0)); pthread_rwlock_unlock(&lock); return res; } int dl_iterate_phdr(int (*callback)(struct dl_phdr_info* info, size_t size, void* data), void* data) { struct dso* current; struct dl_phdr_info info; int ret = 0; for (current = head; current;) { info.dlpi_addr = (uintptr_t)current->l_map.l_addr; info.dlpi_name = current->l_map.l_name; info.dlpi_phdr = current->phdr; info.dlpi_phnum = current->phnum; info.dlpi_adds = gencnt; info.dlpi_subs = 0; info.dlpi_tls_modid = current->tls_id; info.dlpi_tls_data = current->tls.image; ret = (callback)(&info, sizeof(info), data); if (ret != 0) break; pthread_rwlock_rdlock(&lock); current = dso_next(current); pthread_rwlock_unlock(&lock); } return ret; } __attribute__((__visibility__("hidden"))) void __dl_vseterr(const char*, va_list); #define LOADER_SVC_MSG_MAX 1024 __NO_SAFESTACK static zx_status_t loader_svc_rpc(uint64_t ordinal, const void* data, size_t len, zx_handle_t request_handle, zx_handle_t* result) { // Use a static buffer rather than one on the stack to avoid growing // the stack size too much. Calls to this function are always // serialized anyway, so there is no danger of collision. static ldmsg_req_t req; memset(&req.header, 0, sizeof(req.header)); req.header.ordinal = ordinal; size_t req_len; zx_status_t status = ldmsg_req_encode(&req, &req_len, (const char*) data, len); if (status != ZX_OK) { _zx_handle_close(request_handle); error("message of %zu bytes too large for loader service protocol", len); return status; } if (result != NULL) { // Don't return an uninitialized value if the channel call // succeeds but doesn't provide any handles. *result = ZX_HANDLE_INVALID; } ldmsg_rsp_t rsp; memset(&rsp, 0, sizeof(rsp)); zx_channel_call_args_t call = { .wr_bytes = &req, .wr_num_bytes = req_len, .wr_handles = &request_handle, .wr_num_handles = request_handle == ZX_HANDLE_INVALID ? 0 : 1, .rd_bytes = &rsp, .rd_num_bytes = sizeof(rsp), .rd_handles = result, .rd_num_handles = result == NULL ? 0 : 1, }; uint32_t reply_size; uint32_t handle_count; status = _zx_channel_call(loader_svc, 0, ZX_TIME_INFINITE, &call, &reply_size, &handle_count); if (status != ZX_OK) { error("_zx_channel_call of %u bytes to loader service: %d (%s)", call.wr_num_bytes, status, _zx_status_get_string(status)); return status; } size_t expected_reply_size = ldmsg_rsp_get_size(&rsp); if (reply_size != expected_reply_size) { error("loader service reply %u bytes != %u", reply_size, expected_reply_size); status = ZX_ERR_INVALID_ARGS; goto err; } if (rsp.header.ordinal != ordinal) { error("loader service reply opcode %u != %u", rsp.header.ordinal, ordinal); status = ZX_ERR_INVALID_ARGS; goto err; } if (rsp.rv != ZX_OK) { // |result| is non-null if |handle_count| > 0, because // |handle_count| <= |rd_num_handles|. if (handle_count > 0 && *result != ZX_HANDLE_INVALID) { error("loader service error %d reply contains handle %#x", rsp.rv, *result); status = ZX_ERR_INVALID_ARGS; goto err; } status = rsp.rv; } return status; err: if (handle_count > 0) { _zx_handle_close(*result); *result = ZX_HANDLE_INVALID; } return status; } __NO_SAFESTACK static void loader_svc_config(const char* config) { zx_status_t status = loader_svc_rpc(LDMSG_OP_CONFIG, config, strlen(config), ZX_HANDLE_INVALID, NULL); if (status != ZX_OK) debugmsg("LDMSG_OP_CONFIG(%s): %s\n", config, _zx_status_get_string(status)); } __NO_SAFESTACK static zx_status_t get_library_vmo(const char* name, zx_handle_t* result) { if (loader_svc == ZX_HANDLE_INVALID) { error("cannot look up \"%s\" with no loader service", name); return ZX_ERR_UNAVAILABLE; } return loader_svc_rpc(LDMSG_OP_LOAD_OBJECT, name, strlen(name), ZX_HANDLE_INVALID, result); } __NO_SAFESTACK zx_status_t dl_clone_loader_service(zx_handle_t* out) { if (loader_svc == ZX_HANDLE_INVALID) { return ZX_ERR_UNAVAILABLE; } zx_handle_t h0, h1; zx_status_t status; if ((status = _zx_channel_create(0, &h0, &h1)) != ZX_OK) { return status; } struct { fidl_message_header_t header; ldmsg_clone_t clone; } req = { .header = { .ordinal = LDMSG_OP_CLONE, }, .clone = { .object = FIDL_HANDLE_PRESENT, }, }; ldmsg_rsp_t rsp; memset(&rsp, 0, sizeof(rsp)); zx_channel_call_args_t call = { .wr_bytes = &req, .wr_num_bytes = sizeof(req), .wr_handles = &h1, .wr_num_handles = 1, .rd_bytes = &rsp, .rd_num_bytes = sizeof(rsp), .rd_handles = NULL, .rd_num_handles = 0, }; uint32_t reply_size; uint32_t handle_count; if ((status = _zx_channel_call(loader_svc, 0, ZX_TIME_INFINITE, &call, &reply_size, &handle_count)) != ZX_OK) { // Do nothing. } else if ((reply_size != ldmsg_rsp_get_size(&rsp)) || (rsp.header.ordinal != LDMSG_OP_CLONE && rsp.header.ordinal != LDMSG_OP_CLONE_OLD)) { status = ZX_ERR_INVALID_ARGS; } else if (rsp.rv != ZX_OK) { status = rsp.rv; } if (status != ZX_OK) { _zx_handle_close(h0); } else { *out = h0; } return status; } __NO_SAFESTACK __attribute__((__visibility__("hidden"))) void _dl_log_write( const char* buffer, size_t len) { if (logger != ZX_HANDLE_INVALID) { const size_t kLogWriteMax = (ZX_LOG_RECORD_MAX - offsetof(zx_log_record_t, data)); while (len > 0) { size_t chunk = len < kLogWriteMax ? len : kLogWriteMax; // Write only a single line at a time so each line gets tagged. const char* nl = memchr(buffer, '\n', chunk); if (nl != NULL) { chunk = nl + 1 - buffer; } zx_status_t status = _zx_debuglog_write(logger, 0, buffer, chunk); if (status != ZX_OK) { __builtin_trap(); } buffer += chunk; len -= chunk; } } else { zx_status_t status = _zx_debug_write(buffer, len); if (status != ZX_OK) { __builtin_trap(); } } } __NO_SAFESTACK static size_t errormsg_write(FILE* f, const unsigned char* buf, size_t len) { if (f != NULL && f->wpos > f->wbase) { _dl_log_write((const char*)f->wbase, f->wpos - f->wbase); } if (len > 0) { _dl_log_write((const char*)buf, len); } if (f != NULL) { f->wend = f->buf + f->buf_size; f->wpos = f->wbase = f->buf; } return len; } __NO_SAFESTACK static int errormsg_vprintf(const char* restrict fmt, va_list ap) { FILE f = { .lbf = EOF, .write = errormsg_write, .buf = (void*)fmt, .buf_size = 0, .lock = -1, }; return vfprintf(&f, fmt, ap); } __NO_SAFESTACK static void debugmsg(const char* fmt, ...) { va_list ap; va_start(ap, fmt); errormsg_vprintf(fmt, ap); va_end(ap); } __NO_SAFESTACK static void error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (!runtime) { errormsg_vprintf(fmt, ap); ldso_fail = 1; va_end(ap); return; } __dl_vseterr(fmt, ap); va_end(ap); } zx_status_t __sanitizer_change_code_protection(uintptr_t addr, size_t len, bool writable) { static const char kBadDepsMessage[] = "module compiled with -fxray-instrument loaded in process without it"; if (!KEEP_DSO_VMAR) { __sanitizer_log_write(kBadDepsMessage, sizeof(kBadDepsMessage) - 1); __builtin_trap(); } struct dso* p; pthread_rwlock_rdlock(&lock); p = addr2dso((size_t)__builtin_return_address(0)); pthread_rwlock_unlock(&lock); if (!p) { return ZX_ERR_OUT_OF_RANGE; } if (addr < saddr(p, p->code_start) || len > saddr(p, p->code_end) - addr) { debugmsg("Cannot change protection outside of the code range\n"); return ZX_ERR_OUT_OF_RANGE; } uint32_t options = ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE | (writable ? ZX_VM_PERM_WRITE : 0); zx_status_t status = _zx_vmar_protect(p->vmar, options, (zx_vaddr_t)addr, len); if (status != ZX_OK) { debugmsg("Failed to change protection of [%p, %p): %s\n", addr, addr + len, _zx_status_get_string(status)); } return status; } #ifdef __clang__ // Under -fsanitize-coverage, the startup code path before __dls3 cannot // use PLT calls, so its calls to the sancov hook are a problem. We use // some assembler chicanery to redirect those calls to the local symbol // _dynlink_sancov_trampoline. Since the target of the PLT relocs is // local, the linker will elide the PLT entry and resolve the calls // directly to our definition. The trampoline checks the 'runtime' flag to // distinguish calls before final relocation is complete, and only calls // into the sanitizer runtime once it's actually up. Because of the // .weakref chicanery, the _dynlink_sancov_* symbols must be in a separate // assembly file. # include "sancov-stubs.h" # define SANCOV_STUB(name) SANCOV_STUB_ASM(#name) # define SANCOV_STUB_ASM(name) \ __asm__( \ ".weakref __sanitizer_cov_" name ", _dynlink_sancov_trampoline_" name "\n" \ ".hidden _dynlink_sancov_" name "\n" \ ".pushsection .text._dynlink_sancov_trampoline_" name ",\"ax\",%progbits\n"\ ".local _dynlink_sancov_trampoline_" name "\n" \ ".type _dynlink_sancov_trampoline_" name ",%function\n" \ "_dynlink_sancov_trampoline_" name ":\n" \ SANCOV_STUB_ASM_BODY(name) \ ".size _dynlink_sancov_trampoline_" name ", . - _dynlink_sancov_trampoline_" name "\n" \ ".popsection"); # ifdef __x86_64__ # define SANCOV_STUB_ASM_BODY(name) \ "cmpl $0, _dynlink_runtime(%rip)\n" \ "jne _dynlink_sancov_" name "\n" \ "ret\n" # elif defined(__aarch64__) # define SANCOV_STUB_ASM_BODY(name) \ "adrp x16, _dynlink_runtime\n" \ "ldr w16, [x16, #:lo12:_dynlink_runtime]\n" \ "cbnz w16, _dynlink_sancov_" name "\n" \ "ret\n" # else # error unsupported architecture # endif SANCOV_STUBS #endif
34.709508
100
0.578084
[ "object", "model" ]
2c453d332f40822b4997d474c884f59a8e4d14f3
1,332
h
C
Pathfinder/Pathfinder/enemy.h
wa5yl/gra_PSIO
db614ef6cde12664afc4c3b1e6004b0189e56c21
[ "MIT" ]
null
null
null
Pathfinder/Pathfinder/enemy.h
wa5yl/gra_PSIO
db614ef6cde12664afc4c3b1e6004b0189e56c21
[ "MIT" ]
null
null
null
Pathfinder/Pathfinder/enemy.h
wa5yl/gra_PSIO
db614ef6cde12664afc4c3b1e6004b0189e56c21
[ "MIT" ]
null
null
null
#pragma once #include<iostream> #include <ctime> #include <SFML\Window.hpp> #include <SFML\Graphics.hpp> #include <SFML\System.hpp> #include <vector> #include <stdlib.h> #include "fireball.h" class enemy { protected: float hp; float maxHp; float maxHpBar; public: sf::Sprite sprite; sf::Texture texture; sf::Vector2f moveVec; sf::RectangleShape hpBar; float points; float dmg; float vecLangth; bool amIDead; bool canIMove; bool mageId; std::vector<std::unique_ptr<fireball>> fireballs; virtual void render(sf::RenderTarget& target); virtual void update(float pos_x, float pos_y, double delta, int& hit) = 0; virtual void takeDmg(float dmg); virtual void stillAlive(); virtual void changeHpBar(float dmg); }; class george : public enemy { private: public: void initTexture(); void initSprite(); void initVariables(); george(); ~george(); void update(float pos_x, float pos_y, double delta, int& hit) override; }; class bigBen : public enemy { public: void initTexture(); void initSprite(); void initVariables(); bigBen(); ~bigBen(); float maxFireballs; float elapsedTime; //std::vector<std::unique_ptr<fireball>> fireballs; void update(float pos_x, float pos_y, double delta, int& hit) override; void addFireball(double delta); void render(sf::RenderTarget& target) override; };
18
75
0.723724
[ "render", "vector" ]
2c4a2d336370b17d22f17436484f355e3f561315
526
h
C
readPixel.h
megrimm/pd-acourcelle
1ea6e1dbc261aff2bb8244a7720032b6ac6ad8a2
[ "MIT" ]
1
2018-04-28T01:33:17.000Z
2018-04-28T01:33:17.000Z
readPixel.h
megrimm/pd-acourcelle
1ea6e1dbc261aff2bb8244a7720032b6ac6ad8a2
[ "MIT" ]
null
null
null
readPixel.h
megrimm/pd-acourcelle
1ea6e1dbc261aff2bb8244a7720032b6ac6ad8a2
[ "MIT" ]
1
2018-09-12T20:37:29.000Z
2018-09-12T20:37:29.000Z
/* ArNO Courcelle 2014, simple Reader du ViewPort en openGL 2 width GEM. */ #include "Base/GemBase.h" class GEM_EXTERN readPixel : public GemBase { CPPEXTERN_HEADER(readPixel, GemBase); public: // Constructor readPixel(); int ok; t_outlet *m_outTexInfo; GLuint worldTexture; int xx,yy; protected: void find(int,int); // Rendering virtual void startRendering(); virtual void render(GemState *state); virtual void postrender(GemState *state){}; // Stop Transfer virtual void stopRendering(); };
15.939394
59
0.71673
[ "render" ]
2c5592e2dfd0e08d4f81f363695a22d2c5886b55
12,271
c
C
ports/machikania/flash.c
elect-gombe/micropython
5587ab031eb2892610b36b4780b569605cee7f3f
[ "MIT" ]
null
null
null
ports/machikania/flash.c
elect-gombe/micropython
5587ab031eb2892610b36b4780b569605cee7f3f
[ "MIT" ]
null
null
null
ports/machikania/flash.c
elect-gombe/micropython
5587ab031eb2892610b36b4780b569605cee7f3f
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdint.h> #include "py/runtime.h" #include "extmod/vfs_fat.h" #include <string.h> #include "NVMem.h" #define _FLASH_PAGE_SIZE 4096 #define _BUFFER_SIZE_KiB 80 const uint8_t flash_buffer[_BUFFER_SIZE_KiB*1024] __attribute__((aligned(_FLASH_PAGE_SIZE)))={ #include "makefat/fat.csv" }; #define SECTOR_SIZE 512 #define FLASH_PART1_START_BLOCK (0x100) #define FLASH_PART1_NUM_BLOCKS (_BUFFER_SIZE_KiB*2) #define FLASH_ROW_SIZE 512 #define printf(...) mp_printf(&mp_plat_print,__VA_ARGS__);wait60thsec(60); static void build_partition(uint8_t *buf, int boot, int type, uint32_t start_block, uint32_t num_blocks) { buf[0] = boot; if (num_blocks == 0) { buf[1] = 0; buf[2] = 0; buf[3] = 0; } else { buf[1] = 0xff; buf[2] = 0xff; buf[3] = 0xff; } buf[4] = type; if (num_blocks == 0) { buf[5] = 0; buf[6] = 0; buf[7] = 0; } else { buf[5] = 0xff; buf[6] = 0xff; buf[7] = 0xff; } buf[8] = start_block; buf[9] = start_block >> 8; buf[10] = start_block >> 16; buf[11] = start_block >> 24; buf[12] = num_blocks; buf[13] = num_blocks >> 8; buf[14] = num_blocks >> 16; buf[15] = num_blocks >> 24; } static int sector_read(uint8_t *buffer,const unsigned int page,const unsigned int number_of_sector){ if(page == 0){ memset(buffer,0,446); build_partition(buffer + 446, 0, 0x01 /* FAT12 */, FLASH_PART1_START_BLOCK, FLASH_PART1_NUM_BLOCKS); build_partition(buffer + 462, 0, 0, 0, 0);/* empty */ build_partition(buffer + 478, 0, 0, 0, 0); build_partition(buffer + 494, 0, 0, 0, 0); buffer[510] = 0x55; buffer[511] = 0xaa; return 0; } else if (page-FLASH_PART1_START_BLOCK < _BUFFER_SIZE_KiB*2){ memcpy(buffer,flash_buffer+(page-FLASH_PART1_START_BLOCK)*SECTOR_SIZE,number_of_sector*SECTOR_SIZE); return 0; } else { return 1; } } #if 1 // // check if itself is blank, erase accordingly, then write. static int blankcheck(const void *buff,int len){ int i; for(i=0;i<len&&((uint32_t*)buff)[i]==0xFFFFFFFF;i++); return i!=len;//0..pass other..erase required } int writerow(const void *buff,const void*p){ uint32_t u; u=(uint32_t)p; if(u >= (uint32_t)flash_buffer&& u < (uint32_t)flash_buffer + _BUFFER_SIZE_KiB*1024&& (u&(512-1))==0){ int ret = NVMemWriteRow(p,buff); if(ret){ //printf("write err\n (%p)\n",p); } return ret; }else{ //printf("write err\n wrong addr(%p)",p); //printf("(%p~%p)\n",flash_buffer,flash_buffer+_BUFFER_SIZE_KiB*1024); return 1; } } static int write1page(const void *buff,const void *flashaddr){ int ret; const void *b = buff; do{ ret = writerow(b,flashaddr); b += 512,flashaddr += 512; }while(ret==0&&b!=buff+_FLASH_PAGE_SIZE); return ret; } static int erasepage(const void *p){ uint32_t u; u=(uint32_t)p; if(u >= (uint32_t)flash_buffer&& u < (uint32_t)flash_buffer + _BUFFER_SIZE_KiB*1024&& (u&(_FLASH_PAGE_SIZE-1))==0){ int r=NVMemErasePage(p); if(r){ //printf("erase err(%d)",r); return 1; } }else{ //printf("erase err\n wrong addr(%p)",p); //printf("(%p~%p)\n",flash_buffer,flash_buffer+_BUFFER_SIZE_KiB*1024); return 1; } return 0; } int sector_write(const uint8_t *buff,const unsigned int page,int n){ const void *flash_addr; const void *flash_page; int iscontinue = 1; n*=512; flash_addr = (page-FLASH_PART1_START_BLOCK) * SECTOR_SIZE + flash_buffer; flash_page = ((uint32_t)flash_addr)&(~(_FLASH_PAGE_SIZE-1));// align to flash page size if (page >= FLASH_PART1_START_BLOCK&&page-FLASH_PART1_START_BLOCK < _BUFFER_SIZE_KiB*2); else return 1; while(iscontinue){ int pp = (uint32_t)flash_addr-(uint32_t)flash_page;// offset within this page. int nc = _FLASH_PAGE_SIZE - pp; if(nc >= n){//limit 1 page write at the same time. nc = n; iscontinue = 0; } //printf("n:%05x,pp:%05x,nc:%05x\n",n,pp,nc); //printf("buf:%p,page:%p,adr%p",buff,flash_page,flash_addr); if(blankcheck(flash_addr,nc)){ //printf("erase required\n"); //let it erase //bkup, be sure that enough stack space is available(at least flash page + alpha) uint32_t b[_FLASH_PAGE_SIZE/4]; memcpy(b,flash_page,_FLASH_PAGE_SIZE); memcpy(((uint8_t*)b)+pp,buff,nc); int ret = erasepage(flash_page); if(ret){ return ret; } ret=write1page(b,flash_page); if(ret!=0){ //printf("write err\n"); return ret; } flash_addr+=nc; buff+=nc; n-=nc; }else{ //No erase needed. do{ int ret = writerow(buff,flash_addr); if(ret!=0){ //printf("write err\n"); return ret; } flash_addr+=512; buff+=512; n-=512; nc-=SECTOR_SIZE; }while(nc); } flash_page += _FLASH_PAGE_SIZE; } //printf("exit success\n"); return 0; } //MachiKaniaで使われているps2keyboard.cをできれば公開してもらえますか。それとももしかしてhttp://www.ze.em-net.ne.jp/~kenken/ps2kb/index.htmlの中身と同じですか? micropythonのCtrl-Cの中断の実装中で、割り込みハンドラ内少し書き換えたいです。 /* static */ /* int sector_write(const unsigned int page,unsigned int number_of_sector,const uint8_t *buffer){ */ /* int ret; */ /* uint8_t flash_temp_buffer[1024] __attribute__((aligned(4))); */ /* if(page == 0||number_of_sector == 0){ */ /* return 0; */ /* } else if (page-FLASH_PART1_START_BLOCK < _BUFFER_SIZE_KiB*2){ */ /* const void* flash_addr; */ /* if((unsigned int)flash_addr & SECTOR_SIZE){//sector alignment required! */ /* memcpy(flash_temp_buffer,flash_addr-SECTOR_SIZE,SECTOR_SIZE); */ /* memcpy(flash_temp_buffer+SECTOR_SIZE,buffer,SECTOR_SIZE); */ /* ret = NVMemErasePage(flash_addr-SECTOR_SIZE); */ /* if(ret)return ret; */ /* ret = write1page(flash_temp_buffer,flash_addr-SECTOR_SIZE); */ /* if(ret)return ret; */ /* if(number_of_sector!=1)sector_write(page+1, number_of_sector-1, buffer+SECTOR_SIZE); */ /* }else if(number_of_sector == 1){//last write */ /* memcpy(flash_temp_buffer,buffer,SECTOR_SIZE); */ /* memcpy(flash_temp_buffer+SECTOR_SIZE,flash_addr+SECTOR_SIZE,SECTOR_SIZE); */ /* ret = NVMemErasePage(flash_addr); */ /* if(ret)return ret; */ /* ret = write1page(flash_temp_buffer,flash_addr); */ /* if(ret)return ret; */ /* }else{//2sectors aligned */ /* memcpy(flash_temp_buffer,buffer,SECTOR_SIZE*2); */ /* ret = NVMemErasePage(flash_addr); */ /* if(ret)return ret; */ /* ret = write1page(flash_temp_buffer,flash_addr); */ /* if(ret)return ret; */ /* if(number_of_sector!=1)sector_write(page+2, number_of_sector-2, buffer+SECTOR_SIZE*2); */ /* } */ /* } */ /* return 0; */ /* } */ #endif /* DRESULT disk_ioctl_flash ( */ /* uint8_t ctrl, /\* Control code *\/ */ /* void *buff /\* Buffer to send/receive control data *\/ */ /* ) */ /* { */ /* if(ctrl == GET_SECTOR_COUNT){ */ /* *(DWORD*)buff = _BUFFER_SIZE_KiB*2; */ /* }else if(ctrl == GET_SECTOR_SIZE){ */ /* *(DWORD*)buff = 512; */ /* }else if(ctrl == GET_BLOCK_SIZE){ */ /* *(DWORD*)buff = 2; */ /* } */ /* return 0; */ /* } */ /* DSTATUS disk_status_flash(void){ */ /* return 0; */ /* } */ /* DRESULT disk_read_flash ( BYTE* buff, DWORD sector, UINT count){ */ /* sector_read(sector,count,buff); */ /* return 0; */ /* } */ /* DRESULT disk_write_flash (const BYTE* buff, DWORD sector, UINT count){ */ /* sector_write(sector,count,buff); */ /* return 0; */ /* } */ /* DSTATUS disk_initialize_flash (void){ */ /* return 0; */ /* } */ /******************************************************************************/ // MicroPython bindings // // Expose the flash as an object with the block protocol. // there is a singleton Flash object extern const mp_obj_type_t pyb_flash_type; STATIC const mp_obj_base_t pyb_flash_obj = {&pyb_flash_type}; STATIC mp_obj_t pyb_flash_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { // check arguments mp_arg_check_num(n_args, n_kw, 0, 0, false); // return singleton object return MP_OBJ_FROM_PTR(&pyb_flash_obj); } STATIC mp_obj_t pyb_flash_readblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_WRITE); mp_uint_t ret = sector_read(bufinfo.buf,mp_obj_get_int(block_num), bufinfo.len / 512); return MP_OBJ_NEW_SMALL_INT(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_readblocks_obj, pyb_flash_readblocks); STATIC mp_obj_t pyb_flash_writeblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); mp_uint_t ret = 0;//storage_write_blocks(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / FLASH_BLOCK_SIZE); todo return MP_OBJ_NEW_SMALL_INT(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_writeblocks_obj, pyb_flash_writeblocks); static uint32_t storage_get_block_size(void) { return 512; } static uint32_t storage_get_block_count(void) { return FLASH_PART1_START_BLOCK + FLASH_PART1_NUM_BLOCKS; } STATIC mp_obj_t pyb_flash_ioctl(mp_obj_t self, mp_obj_t cmd_in, mp_obj_t arg_in) { mp_int_t cmd = mp_obj_get_int(cmd_in); switch (cmd) { case BP_IOCTL_INIT: return MP_OBJ_NEW_SMALL_INT(0); case BP_IOCTL_DEINIT: return MP_OBJ_NEW_SMALL_INT(0); // TODO properly case BP_IOCTL_SYNC: return MP_OBJ_NEW_SMALL_INT(0); case BP_IOCTL_SEC_COUNT: return MP_OBJ_NEW_SMALL_INT(storage_get_block_count()); case BP_IOCTL_SEC_SIZE: return MP_OBJ_NEW_SMALL_INT(storage_get_block_size()); default: return mp_const_none; } } STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl); STATIC const mp_rom_map_elem_t pyb_flash_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&pyb_flash_readblocks_obj) }, { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&pyb_flash_writeblocks_obj) }, { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&pyb_flash_ioctl_obj) }, }; STATIC MP_DEFINE_CONST_DICT(pyb_flash_locals_dict, pyb_flash_locals_dict_table); const mp_obj_type_t pyb_flash_type = { { &mp_type_type }, .name = MP_QSTR_Flash, .make_new = pyb_flash_make_new, .locals_dict = (mp_obj_dict_t*)&pyb_flash_locals_dict, }; void pyb_flash_init_vfs(fs_user_mount_t *vfs) { vfs->base.type = &mp_fat_vfs_type; vfs->flags |= FSUSER_NATIVE | FSUSER_HAVE_IOCTL; vfs->fatfs.drv = vfs; vfs->fatfs.part = 1; // flash filesystem lives on first partition vfs->readblocks[0] = MP_OBJ_FROM_PTR(&pyb_flash_readblocks_obj); vfs->readblocks[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj); vfs->readblocks[2] = MP_OBJ_FROM_PTR(sector_read); // native version vfs->writeblocks[0] = MP_OBJ_FROM_PTR(&pyb_flash_writeblocks_obj); vfs->writeblocks[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj); vfs->writeblocks[2] = MP_OBJ_FROM_PTR(sector_write); // native version vfs->u.ioctl[0] = MP_OBJ_FROM_PTR(&pyb_flash_ioctl_obj); vfs->u.ioctl[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj); }
32.635638
166
0.673947
[ "object" ]
c804b9a3ddab3c6aef18f49bf56f612abbba5db2
1,752
h
C
ble-config.h
armPelionEdge/workflows-with-secure-device-access-client
bf03d069032a15e3b0e3af6abd7496740f376ca1
[ "Apache-2.0" ]
null
null
null
ble-config.h
armPelionEdge/workflows-with-secure-device-access-client
bf03d069032a15e3b0e3af6abd7496740f376ca1
[ "Apache-2.0" ]
null
null
null
ble-config.h
armPelionEdge/workflows-with-secure-device-access-client
bf03d069032a15e3b0e3af6abd7496740f376ca1
[ "Apache-2.0" ]
null
null
null
/* * ---------------------------------------------------------------------------- * Copyright 2020 ARM Ltd. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ---------------------------------------------------------------------------- */ #ifndef __BLE_CONFIG_UUID__ #define __BLE_CONFIG_UUID__ #include <stdint.h> #define LONG_UUID_LENGTH 16 /*** * Define BLE packet Length that will transmit in each transition, should be '8' Less than MTU. * Device Local Name to advertise in BLE * Manufacturer Name * Model Number * Hardware Revision * Software Revision */ #define BLE_PACKET_SIZE 0 #define Device_Local_Name #define MANUFACTURER_NAME #define MODEL_NUM #define HARDWARE_REVISION #define SOFTWARE_REVISION #define MOUNT_POINT const uint8_t ServiceBaseUUID[LONG_UUID_LENGTH] = {0}; const uint16_t ServiceShortUUID = 0x0000; const uint16_t CharacteristicShortUUID = 0x0000; const uint8_t ServiceUUID[LONG_UUID_LENGTH] = {0}; const uint8_t CharacteristicUUID[LONG_UUID_LENGTH] = {0}; #if BLE_PACKET_SIZE == 0 #error "Fill the configurations with the details like UUID, Name, BLE_PACKET_SIZE etc!" #endif #endif
31.854545
95
0.666096
[ "model" ]
c807c53b215f42e4a86481227b6b362c2cbb6c40
1,559
h
C
src/sandbox/base/Transform.h
OpenSpace-VisLink/sandbox
cb8a42facc3afe73794e2e4405aab13531ccbcb2
[ "MIT" ]
null
null
null
src/sandbox/base/Transform.h
OpenSpace-VisLink/sandbox
cb8a42facc3afe73794e2e4405aab13531ccbcb2
[ "MIT" ]
null
null
null
src/sandbox/base/Transform.h
OpenSpace-VisLink/sandbox
cb8a42facc3afe73794e2e4405aab13531ccbcb2
[ "MIT" ]
1
2020-12-01T18:17:58.000Z
2020-12-01T18:17:58.000Z
#ifndef SANDBOX_BASE_TRANSFORM_H_ #define SANDBOX_BASE_TRANSFORM_H_ #include "glm/glm.hpp" #include "sandbox/graphics/RenderObject.h" #include <iostream> namespace sandbox { class TransformState : public StateContainerItem { public: TransformState() { calculateTransform = false; transform.set(glm::mat4(1.0f)); } virtual ~TransformState() {} StateContainerItemStack<glm::mat4>& getTransform() { return transform; } static TransformState& get(const GraphicsContext& context) { return context.getRenderState()->getItem<TransformState>(); } bool calculateTransform; private: StateContainerItemStack<glm::mat4> transform; }; class Transform : public RenderObject { public: Transform(); Transform(const glm::mat4& transform); virtual ~Transform(); const glm::mat4& getTransform() const { return transform; } void setTransform(const glm::mat4& transform) { this->transform = transform; getEntity().incrementVersion(); } glm::vec3 getLocation() const; virtual void startRender(const GraphicsContext& context) { TransformState& state = TransformState::get(context); if (state.calculateTransform) { state.getTransform().push(state.getTransform().get()*transform); //std::cout << "begin Transform " << std::endl; } } virtual void finishRender(const GraphicsContext& context) { TransformState& state = TransformState::get(context); if (state.calculateTransform) { TransformState::get(context).getTransform().pop(); //std::cout << "end Transform " << std::endl; } } private: glm::mat4 transform; }; } #endif
24.746032
123
0.735087
[ "transform" ]
c80c7055fe0914a7d420d58c199d7597e823849a
4,245
h
C
zircon/system/ulib/fs/include/fs/paged_vnode.h
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
zircon/system/ulib/fs/include/fs/paged_vnode.h
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
zircon/system/ulib/fs/include/fs/paged_vnode.h
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FS_PAGED_VNODE_H_ #define FS_PAGED_VNODE_H_ #include <lib/async/cpp/wait.h> #include <fs/locking.h> #include <fs/vnode.h> namespace fs { class PagedVfs; // A Vnode that supports paged I/O. // // To implement, derive from this class and: // - Implement Vnode::GetVmo(). // - Use PagedVnode::EnsureCreateVmo() to create the data mapping. This will create it in such a // way that it's registered with the paging system for callbacks. // - Do vmo().create_child() to clone the VMO backing this node. // - Set the rights on the cloned VMO with the rights passed to GetVmo(). // - Populate the GetVmo() out parameter with the child VMO. // - Implement VmoRead() to fill the VMO data when requested. class PagedVnode : public Vnode { public: // Called by the paging system in response to a kernel request to fill data into this node's VMO. // // - On success, calls vfs()->SupplyPages() with the created data range. // - On failure, calls vfs()->ReportPagerError() with the error information. // // The success or failure cases can happen synchronously (from within this call stack) or // asynchronously in the future. Failure to report success or failure will hang the requesting // process. // // Note that offset + length will be page-aligned so can extend beyond the end of the file. virtual void VmoRead(uint64_t offset, uint64_t length) = 0; protected: friend fbl::RefPtr<PagedVnode>; explicit PagedVnode(PagedVfs* vfs); ~PagedVnode() override; // This will be null if the Vfs has shut down. Since Vnodes are refcounted, it's possible for them // to outlive their associated Vfs. Always null check before using. If there is no Vfs associated // with this object, all operations are expected to fail. PagedVfs* paged_vfs() FS_TA_REQUIRES(mutex_) { // Since we were constructed with a PagedVfs, we know it's safe to up-cast back to that. return static_cast<PagedVfs*>(vfs()); } // This will be a null handle if there is no VMO associated with this vnode. zx::vmo& vmo() FS_TA_REQUIRES(mutex_) { return vmo_; } // Populates the vmo() if necessary. Does nothing if it already exists. Access the created vmo // with this class' vmo() getter. // // When a mapping is requested, the derived class should call this function and then create a // clone of this VMO with the desired flags. This class registers an observer for when the clone // count drops to 0 to clean up the VMO. This means that if the caller doesn't create a clone the // VMO will leak if it's registered as handling paging requests on the Vfs (which will keep this // object alive). zx::status<> EnsureCreateVmo(uint64_t size) FS_TA_REQUIRES(mutex_); // Implementors of this class can override this function to response to the event that there // are no more clones of the vmo_. The default implementation frees the vmo_. virtual void OnNoClones() FS_TA_REQUIRES(mutex_); private: // Callback handler for the "no clones" message. Due to kernel message delivery race conditions // there might actually be clones. This checks and calls OnNoClones() when needed. void OnNoClonesMessage(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) FS_TA_EXCLUDES(mutex_); // Starts the clone_watcher_ to observe the case of no vmo_ clones. The WaitMethod is called only // once per "watch" call so this needs to be re-called after triggering. // // The vmo_ and paged_vfs() must exist. void WatchForZeroVmoClones() FS_TA_REQUIRES(mutex_); // The root VMO that paging happens out of for this vnode. VMOs that map the data into user // processes will be children of this VMO. zx::vmo vmo_ FS_TA_GUARDED(mutex_); // Watches any clones of "vmo_" provided to clients. Observes the ZX_VMO_ZERO_CHILDREN signal. // See WatchForZeroChildren(). async::WaitMethod<PagedVnode, &PagedVnode::OnNoClonesMessage> clone_watcher_ FS_TA_GUARDED(mutex_); }; } // namespace fs #endif // FS_PAGED_VNODE_H_
43.316327
100
0.728622
[ "object" ]
c80df15330e57262737a590b47369bdb2861cdd3
55,841
c
C
lib/ykpiv.c
gcbw/yubico-piv-tool
55040742c9f6993b856ad4aa1b6d70ae5877a5dd
[ "BSD-2-Clause" ]
1
2020-09-29T13:10:37.000Z
2020-09-29T13:10:37.000Z
lib/ykpiv.c
gcbw/yubico-piv-tool
55040742c9f6993b856ad4aa1b6d70ae5877a5dd
[ "BSD-2-Clause" ]
null
null
null
lib/ykpiv.c
gcbw/yubico-piv-tool
55040742c9f6993b856ad4aa1b6d70ae5877a5dd
[ "BSD-2-Clause" ]
null
null
null
/* * 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. * */ /** @file */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <ctype.h> #include "internal.h" #include "ykpiv.h" /** * DISABLE_PIN_CACHE - disable in-RAM cache of PIN * * By default, the PIN is cached in RAM when provided to \p ykpiv_verify() or * changed with \p ykpiv_change_pin(). If the USB connection is lost between * calls, the device will be re-authenticated on the next call using the cached * PIN. The PIN is cleared with a call to \p ykpiv_done(). * * The PIN cache prevents problems with long-running applications losing their * authentication in some cases, such as when a laptop sleeps. * * The cache can be disabled by setting this define to 1 if it is not desired * to store the PIN in RAM. * */ #ifndef DISABLE_PIN_CACHE #define DISABLE_PIN_CACHE 0 #endif /** * ENABLE_APPLICATION_RESELECT - re-select application for all public API calls * * If this is enabled, every public call (prefixed with \r ykpiv_) will check * that the PIV application is currently selected, or re-select it if it is * not. * * Auto re-selection allows a long-running PIV application to cooperate on * a system that may simultaneously use the non-PIV applications of connected * devices. * * This is \b DANGEROUS - with this enabled, slots with the policy * \p YKPIV_PINPOLICY_ALWAYS will not be accessible. * */ #ifndef ENABLE_APPLICATION_RESELECTION #define ENABLE_APPLICATION_RESELECTION 0 #endif /** * ENABLE_IMPLICIT_TRANSACTIONS - call SCardBeginTransaction for all public API calls * * If this is enabled, every public call (prefixed with \r ykpiv_) will call * SCardBeginTransaction on entry and SCardEndTransaction on exit. * * For applications that do not do their own transaction management, like the piv tool * itself, retaining the default setting of enabled can allow other applications and * threads to make calls to CCID that can interfere with multi-block data sent to the * card via SCardTransmitData. */ #ifndef ENABLE_IMPLICIT_TRANSACTIONS #define ENABLE_IMPLICIT_TRANSACTIONS 1 #endif /** * Platform specific definitions */ #ifdef _MSC_VER #define strncasecmp _strnicmp #endif #define YKPIV_MGM_DEFAULT "\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08" static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len); static ykpiv_rc _ykpiv_get_serial(ykpiv_state *state, uint32_t *p_serial, bool force); static ykpiv_rc _ykpiv_get_version(ykpiv_state *state, ykpiv_version_t *p_version); static unsigned const char aid[] = { 0xa0, 0x00, 0x00, 0x03, 0x08 }; static void* _default_alloc(void *data, size_t cb) { (void)data; return calloc(cb, 1); } static void * _default_realloc(void *data, void *p, size_t cb) { (void)data; return realloc(p, cb); } static void _default_free(void *data, void *p) { (void)data; free(p); } ykpiv_allocator _default_allocator = { .pfn_alloc = _default_alloc, .pfn_realloc = _default_realloc, .pfn_free = _default_free, .alloc_data = 0 }; /* Memory helper functions */ void* _ykpiv_alloc(ykpiv_state *state, size_t size) { if (!state || !(state->allocator.pfn_alloc)) return NULL; return state->allocator.pfn_alloc(state->allocator.alloc_data, size); } void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size) { if (!state || !(state->allocator.pfn_realloc)) return NULL; return state->allocator.pfn_realloc(state->allocator.alloc_data, address, size); } void _ykpiv_free(ykpiv_state *state, void *data) { if (!data || !state || (!(state->allocator.pfn_free))) return; state->allocator.pfn_free(state->allocator.alloc_data, data); } static void dump_hex(const unsigned char *buf, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) { fprintf(stderr, "%02x ", buf[i]); } } unsigned int _ykpiv_set_length(unsigned char *buffer, size_t length) { if(length < 0x80) { *buffer++ = (unsigned char)length; return 1; } else if(length < 0x100) { *buffer++ = 0x81; *buffer++ = (unsigned char)length; return 2; } else { *buffer++ = 0x82; *buffer++ = (length >> 8) & 0xff; *buffer++ = (unsigned char)length & 0xff; return 3; } } unsigned int _ykpiv_get_length(const unsigned char *buffer, size_t *len) { if(buffer[0] < 0x81) { *len = buffer[0]; return 1; } else if((*buffer & 0x7f) == 1) { *len = buffer[1]; return 2; } else if((*buffer & 0x7f) == 2) { size_t tmp = buffer[1]; *len = (tmp << 8) + buffer[2]; return 3; } return 0; } bool _ykpiv_has_valid_length(const unsigned char* buffer, size_t len) { if ((buffer[0] < 0x81) && (len > 0)) { return true; } else if (((*buffer & 0x7f) == 1) && (len > 1)) { return true; } else if (((*buffer & 0x7f) == 2) && (len > 2)) { return true; } return false; } static unsigned char *set_object(int object_id, unsigned char *buffer) { *buffer++ = 0x5c; if(object_id == YKPIV_OBJ_DISCOVERY) { *buffer++ = 1; *buffer++ = YKPIV_OBJ_DISCOVERY; } else if(object_id > 0xffff && object_id <= 0xffffff) { *buffer++ = 3; *buffer++ = (object_id >> 16) & 0xff; *buffer++ = (object_id >> 8) & 0xff; *buffer++ = object_id & 0xff; } return buffer; } ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator) { ykpiv_state *s; if (NULL == state) { return YKPIV_GENERIC_ERROR; } if (NULL == allocator || !allocator->pfn_alloc || !allocator->pfn_realloc || !allocator->pfn_free) { return YKPIV_MEMORY_ERROR; } s = allocator->pfn_alloc(allocator->alloc_data, sizeof(ykpiv_state)); if (NULL == s) { return YKPIV_MEMORY_ERROR; } memset(s, 0, sizeof(ykpiv_state)); s->pin = NULL; s->allocator = *allocator; s->verbose = verbose; s->context = (SCARDCONTEXT)-1; *state = s; return YKPIV_OK; } ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { return ykpiv_init_with_allocator(state, verbose, &_default_allocator); } static ykpiv_rc _ykpiv_done(ykpiv_state *state, bool disconnect) { if (disconnect) ykpiv_disconnect(state); _cache_pin(state, NULL, 0); _ykpiv_free(state, state); return YKPIV_OK; } ykpiv_rc ykpiv_done_with_external_card(ykpiv_state *state) { return _ykpiv_done(state, false); } ykpiv_rc ykpiv_done(ykpiv_state *state) { return _ykpiv_done(state, true); } ykpiv_rc ykpiv_disconnect(ykpiv_state *state) { if(state->card) { SCardDisconnect(state->card, SCARD_RESET_CARD); state->card = 0; } if(SCardIsValidContext(state->context) == SCARD_S_SUCCESS) { SCardReleaseContext(state->context); state->context = (SCARDCONTEXT)-1; } return YKPIV_OK; } ykpiv_rc _ykpiv_select_application(ykpiv_state *state) { APDU apdu; unsigned char data[0xff]; uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res = YKPIV_OK; memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SELECT_APPLICATION; apdu.st.p1 = 0x04; apdu.st.lc = sizeof(aid); memcpy(apdu.st.data, aid, sizeof(aid)); if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { if(state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } return res; } else if(sw != SW_SUCCESS) { if(state->verbose) { fprintf(stderr, "Failed selecting application: %04x\n", sw); } return YKPIV_GENERIC_ERROR; } /* now that the PIV application is selected, retrieve the version * and serial number. Previously the NEO/YK4 required switching * to the yk applet to retrieve the serial, YK5 implements this * as a PIV applet command. Unfortunately, this change requires * that we retrieve the version number first, so that get_serial * can determine how to get the serial number, which for the NEO/Yk4 * will result in another selection of the PIV applet. */ res = _ykpiv_get_version(state, NULL); if (res != YKPIV_OK) { if (state->verbose) { fprintf(stderr, "Failed to retrieve version: '%s'\n", ykpiv_strerror(res)); } } res = _ykpiv_get_serial(state, NULL, false); if (res != YKPIV_OK) { if (state->verbose) { fprintf(stderr, "Failed to retrieve serial number: '%s'\n", ykpiv_strerror(res)); } res = YKPIV_OK; } return res; } ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) { ykpiv_rc res = YKPIV_OK; #if ENABLE_APPLICATION_RESELECTION if (NULL == state) { return YKPIV_GENERIC_ERROR; } res = ykpiv_verify(state, NULL, 0); if ((YKPIV_OK != res) && (YKPIV_WRONG_PIN != res)) { res = _ykpiv_select_application(state); } else { res = YKPIV_OK; } return res; #else (void)state; return res; #endif } static ykpiv_rc _ykpiv_connect(ykpiv_state *state, uintptr_t context, uintptr_t card) { ykpiv_rc res = YKPIV_OK; if (NULL == state) { return YKPIV_GENERIC_ERROR; } // if the context has changed, and the new context is not valid, return an error if ((context != state->context) && (SCARD_S_SUCCESS != SCardIsValidContext(context))) { return YKPIV_PCSC_ERROR; } // if card handle has changed, determine if handle is valid (less efficient, but complete) if ((card != state->card)) { char reader[CB_BUF_MAX]; pcsc_word reader_len = sizeof(reader); uint8_t atr[CB_ATR_MAX]; pcsc_word atr_len = sizeof(atr); // Cannot set the reader len to NULL. Confirmed in OSX 10.10, so we have to retrieve it even though we don't need it. if (SCARD_S_SUCCESS != SCardStatus(card, reader, &reader_len, NULL, NULL, atr, &atr_len)) { return YKPIV_PCSC_ERROR; } state->isNEO = (((sizeof(YKPIV_ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(YKPIV_ATR_NEO_R3, atr, atr_len))); } state->context = context; state->card = card; /* ** Do not select the applet here, as we need to accommodate commands that are ** sensitive to re-select (custom apdu/auth). All commands that can handle explicit ** selection already check the applet state and select accordingly anyway. ** ykpiv_verify_select is supplied for those who want to select explicitly. ** ** The applet _is_ selected by ykpiv_connect(), but is not selected when bypassing ** it with ykpiv_connect_with_external_card(). */ return res; } ykpiv_rc ykpiv_connect_with_external_card(ykpiv_state *state, uintptr_t context, uintptr_t card) { return _ykpiv_connect(state, context, card); } ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { pcsc_word active_protocol; char reader_buf[2048]; size_t num_readers = sizeof(reader_buf); long rc; char *reader_ptr; SCARDHANDLE card = (SCARDHANDLE)-1; ykpiv_rc ret = ykpiv_list_readers(state, reader_buf, &num_readers); if(ret != YKPIV_OK) { return ret; } for(reader_ptr = reader_buf; *reader_ptr != '\0'; reader_ptr += strlen(reader_ptr) + 1) { if(wanted) { char *ptr = reader_ptr; bool found = false; do { if(strlen(ptr) < strlen(wanted)) { break; } if(strncasecmp(ptr, wanted, strlen(wanted)) == 0) { found = true; break; } } while(*ptr++); if(found == false) { if(state->verbose) { fprintf(stderr, "skipping reader '%s' since it doesn't match '%s'.\n", reader_ptr, wanted); } continue; } } if(state->verbose) { fprintf(stderr, "trying to connect to reader '%s'.\n", reader_ptr); } rc = SCardConnect(state->context, reader_ptr, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T1, &card, &active_protocol); if(rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf(stderr, "SCardConnect failed, rc=%08lx\n", rc); } continue; } // at this point, card should not equal state->card, to allow _ykpiv_connect() to determine device type if (YKPIV_OK == _ykpiv_connect(state, state->context, card)) { /* * Select applet. This is done here instead of in _ykpiv_connect() because * you may not want to select the applet when connecting to a card handle that * was supplied by an external library. */ if (YKPIV_OK != (ret = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; #if ENABLE_APPLICATION_RESELECTION ret = _ykpiv_ensure_application_selected(state); #else ret = _ykpiv_select_application(state); #endif _ykpiv_end_transaction(state); return ret; } } if(*reader_ptr == '\0') { if(state->verbose) { fprintf(stderr, "error: no usable reader found.\n"); } SCardReleaseContext(state->context); state->context = (SCARDCONTEXT)-1; return YKPIV_PCSC_ERROR; } return YKPIV_GENERIC_ERROR; } static ykpiv_rc reconnect(ykpiv_state *state) { pcsc_word active_protocol = 0; long rc; ykpiv_rc res; int tries; if(state->verbose) { fprintf(stderr, "trying to reconnect to current reader.\n"); } rc = SCardReconnect(state->card, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T1, SCARD_RESET_CARD, &active_protocol); if(rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf(stderr, "SCardReconnect failed, rc=%08lx\n", rc); } return YKPIV_PCSC_ERROR; } if ((res = _ykpiv_select_application(state)) != YKPIV_OK) { return res; } if (state->pin) { return ykpiv_verify(state, state->pin, &tries); } return YKPIV_OK; } ykpiv_rc ykpiv_list_readers(ykpiv_state *state, char *readers, size_t *len) { pcsc_word num_readers = 0; long rc; if(SCardIsValidContext(state->context) != SCARD_S_SUCCESS) { rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &state->context); if (rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf (stderr, "error: SCardEstablishContext failed, rc=%08lx\n", rc); } return YKPIV_PCSC_ERROR; } } rc = SCardListReaders(state->context, NULL, NULL, &num_readers); if (rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf (stderr, "error: SCardListReaders failed, rc=%08lx\n", rc); } SCardReleaseContext(state->context); state->context = (SCARDCONTEXT)-1; return YKPIV_PCSC_ERROR; } if (num_readers > *len) { num_readers = (pcsc_word)*len; } else if (num_readers < *len) { *len = (size_t)num_readers; } rc = SCardListReaders(state->context, NULL, readers, &num_readers); if (rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf (stderr, "error: SCardListReaders failed, rc=%08lx\n", rc); } SCardReleaseContext(state->context); state->context = (SCARDCONTEXT)-1; return YKPIV_PCSC_ERROR; } *len = num_readers; return YKPIV_OK; } ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state) { #if ENABLE_IMPLICIT_TRANSACTIONS long rc; rc = SCardBeginTransaction(state->card); if((long)((unsigned long)rc & 0xFFFFFFFF) == SCARD_W_RESET_CARD) { ykpiv_rc res = YKPIV_OK; if((res = reconnect(state)) != YKPIV_OK) { return res; } rc = SCardBeginTransaction(state->card); } if(rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf(stderr, "error: Failed to begin pcsc transaction, rc=%08lx\n", rc); } return YKPIV_PCSC_ERROR; } #endif /* ENABLE_IMPLICIT_TRANSACTIONS */ return YKPIV_OK; } ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state) { #if ENABLE_IMPLICIT_TRANSACTIONS long rc = SCardEndTransaction(state->card, SCARD_LEAVE_CARD); if(rc != SCARD_S_SUCCESS && state->verbose) { fprintf(stderr, "error: Failed to end pcsc transaction, rc=%08lx\n", rc); return YKPIV_PCSC_ERROR; } #endif /* ENABLE_IMPLICIT_TRANSACTIONS */ return YKPIV_OK; } ykpiv_rc _ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, const unsigned char *in_data, long in_len, unsigned char *out_data, unsigned long *out_len, int *sw) { const unsigned char *in_ptr = in_data; unsigned long max_out = *out_len; ykpiv_rc res; *out_len = 0; do { size_t this_size = 0xff; unsigned char data[261]; uint32_t recv_len = sizeof(data); APDU apdu; memset(apdu.raw, 0, sizeof(apdu.raw)); memcpy(apdu.raw, templ, 4); if(in_ptr + 0xff < in_data + in_len) { apdu.st.cla = 0x10; } else { this_size = (size_t)((in_data + in_len) - in_ptr); } if(state->verbose > 2) { fprintf(stderr, "Going to send %lu bytes in this go.\n", (unsigned long)this_size); } apdu.st.lc = (unsigned char)this_size; memcpy(apdu.st.data, in_ptr, this_size); res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { goto Cleanup; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { goto Cleanup; } if(*out_len + recv_len - 2 > max_out) { if(state->verbose) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.\n", *out_len + recv_len - 2, max_out); } res = YKPIV_SIZE_ERROR; goto Cleanup; } if(out_data) { memcpy(out_data, data, recv_len - 2); out_data += recv_len - 2; *out_len += recv_len - 2; } in_ptr += this_size; } while(in_ptr < in_data + in_len); while(*sw >> 8 == 0x61) { APDU apdu; unsigned char data[261]; uint32_t recv_len = sizeof(data); if(state->verbose > 2) { fprintf(stderr, "The card indicates there is %d bytes more data for us.\n", *sw & 0xff); } memset(apdu.raw, 0, sizeof(apdu.raw)); apdu.st.ins = YKPIV_INS_GET_RESPONSE_APDU; res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { goto Cleanup; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { goto Cleanup; } if(*out_len + recv_len - 2 > max_out) { if(state->verbose) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.", *out_len + recv_len - 2, max_out); } res = YKPIV_SIZE_ERROR; goto Cleanup; } if(out_data) { memcpy(out_data, data, recv_len - 2); out_data += recv_len - 2; *out_len += recv_len - 2; } } Cleanup: return res; } ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, const unsigned char *in_data, long in_len, unsigned char *out_data, unsigned long *out_len, int *sw) { ykpiv_rc res; if ((res = _ykpiv_begin_transaction(state)) != YKPIV_OK) { *out_len = 0; return YKPIV_PCSC_ERROR; } res = _ykpiv_transfer_data(state, templ, in_data, in_len, out_data, out_len, sw); _ykpiv_end_transaction(state); return res; } ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, unsigned char *data, uint32_t *recv_len, int *sw) { long rc; unsigned int send_len = (unsigned int)apdu->st.lc + 5; pcsc_word tmp_len = *recv_len; if(state->verbose > 1) { fprintf(stderr, "> "); dump_hex(apdu->raw, send_len); fprintf(stderr, "\n"); } rc = SCardTransmit(state->card, SCARD_PCI_T1, apdu->raw, send_len, NULL, data, &tmp_len); if(rc != SCARD_S_SUCCESS) { if(state->verbose) { fprintf (stderr, "error: SCardTransmit failed, rc=%08lx\n", rc); } return YKPIV_PCSC_ERROR; } *recv_len = (uint32_t)tmp_len; if(state->verbose > 1) { fprintf(stderr, "< "); dump_hex(data, *recv_len); fprintf(stderr, "\n"); } if(*recv_len >= 2) { *sw = (data[*recv_len - 2] << 8) | data[*recv_len - 1]; } else { *sw = 0; } return YKPIV_OK; } ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { APDU apdu; unsigned char data[261]; unsigned char challenge[8]; uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; des_rc drc = DES_OK; des_key* mgm_key = NULL; size_t out_len = 0; if (NULL == state) return YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; if (NULL == key) { /* use the derived mgm key to authenticate, if it hasn't been derived, use default */ key = (unsigned const char*)YKPIV_MGM_DEFAULT; } /* set up our key */ if (DES_OK != des_import_key(DES_TYPE_3DES, key, CB_MGM_KEY, &mgm_key)) { res = YKPIV_ALGORITHM_ERROR; goto Cleanup; } /* get a challenge from the card */ { memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_AUTHENTICATE; apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ apdu.st.lc = 0x04; apdu.st.data[0] = 0x7c; apdu.st.data[1] = 0x02; apdu.st.data[2] = 0x80; if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } else if (sw != SW_SUCCESS) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } memcpy(challenge, data + 4, 8); } /* send a response to the cards challenge and a challenge of our own. */ { unsigned char *dataptr = apdu.st.data; unsigned char response[8]; out_len = sizeof(response); drc = des_decrypt(mgm_key, challenge, sizeof(challenge), response, &out_len); if (drc != DES_OK) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } recv_len = sizeof(data); memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_AUTHENTICATE; apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ *dataptr++ = 0x7c; *dataptr++ = 20; /* 2 + 8 + 2 +8 */ *dataptr++ = 0x80; *dataptr++ = 8; memcpy(dataptr, response, 8); dataptr += 8; *dataptr++ = 0x81; *dataptr++ = 8; if (PRNG_GENERAL_ERROR == _ykpiv_prng_generate(dataptr, 8)) { if (state->verbose) { fprintf(stderr, "Failed getting randomness for authentication.\n"); } res = YKPIV_RANDOMNESS_ERROR; goto Cleanup; } memcpy(challenge, dataptr, 8); dataptr += 8; apdu.st.lc = (unsigned char)(dataptr - apdu.st.data); if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } else if (sw != SW_SUCCESS) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } } /* compare the response from the card with our challenge */ { unsigned char response[8]; out_len = sizeof(response); drc = des_encrypt(mgm_key, challenge, sizeof(challenge), response, &out_len); if (drc != DES_OK) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } if (memcmp(response, data + 4, 8) == 0) { res = YKPIV_OK; } else { res = YKPIV_AUTHENTICATION_ERROR; } } Cleanup: if (mgm_key) { des_destroy_key(mgm_key); } _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_set_mgmkey(ykpiv_state *state, const unsigned char *new_key) { return ykpiv_set_mgmkey2(state, new_key, 0); } ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, const unsigned char touch) { APDU apdu; unsigned char data[261]; uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; if (yk_des_is_weak_key(new_key, DES_LEN_3DES)) { if (state->verbose) { fprintf(stderr, "Won't set new key '"); dump_hex(new_key, DES_LEN_3DES); fprintf(stderr, "' since it's weak (with odd parity).\n"); } res = YKPIV_KEY_ERROR; goto Cleanup; } memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SET_MGMKEY; apdu.st.p1 = 0xff; if (touch == 0) { apdu.st.p2 = 0xff; } else if (touch == 1) { apdu.st.p2 = 0xfe; } else { res = YKPIV_GENERIC_ERROR; goto Cleanup; } apdu.st.lc = DES_LEN_3DES + 3; apdu.st.data[0] = YKPIV_ALGO_3DES; apdu.st.data[1] = YKPIV_KEY_CARDMGM; apdu.st.data[2] = DES_LEN_3DES; memcpy(apdu.st.data + 3, new_key, DES_LEN_3DES); if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } else if (sw == SW_SUCCESS) { goto Cleanup; } res = YKPIV_GENERIC_ERROR; Cleanup: yc_memzero(&apdu, sizeof(APDU)); _ykpiv_end_transaction(state); return res; } static char hex_translate[] = "0123456789abcdef"; ykpiv_rc ykpiv_hex_decode(const char *hex_in, size_t in_len, unsigned char *hex_out, size_t *out_len) { size_t i; bool first = true; if(*out_len < in_len / 2) { return YKPIV_SIZE_ERROR; } else if(in_len % 2 != 0) { return YKPIV_SIZE_ERROR; } *out_len = in_len / 2; for(i = 0; i < in_len; i++) { char *ind_ptr = strchr(hex_translate, tolower(*hex_in++)); int index = 0; if(ind_ptr) { index = (int)(ind_ptr - hex_translate); } else { return YKPIV_PARSE_ERROR; } if(first) { *hex_out = index << 4; } else { *hex_out++ |= index; } first = !first; } return YKPIV_OK; } static ykpiv_rc _general_authenticate(ykpiv_state *state, const unsigned char *sign_in, size_t in_len, unsigned char *out, size_t *out_len, unsigned char algorithm, unsigned char key, bool decipher) { unsigned char indata[1024]; unsigned char *dataptr = indata; unsigned char data[1024]; unsigned char templ[] = {0, YKPIV_INS_AUTHENTICATE, algorithm, key}; unsigned long recv_len = sizeof(data); size_t key_len = 0; int sw = 0; size_t bytes; size_t len = 0; ykpiv_rc res; switch(algorithm) { case YKPIV_ALGO_RSA1024: key_len = 128; // fall through case YKPIV_ALGO_RSA2048: if(key_len == 0) { key_len = 256; } if(in_len != key_len) { return YKPIV_SIZE_ERROR; } break; case YKPIV_ALGO_ECCP256: key_len = 32; // fall through case YKPIV_ALGO_ECCP384: if(key_len == 0) { key_len = 48; } if(!decipher && in_len > key_len) { return YKPIV_SIZE_ERROR; } else if(decipher && in_len != (key_len * 2) + 1) { return YKPIV_SIZE_ERROR; } break; default: return YKPIV_ALGORITHM_ERROR; } if(in_len < 0x80) { bytes = 1; } else if(in_len < 0xff) { bytes = 2; } else { bytes = 3; } *dataptr++ = 0x7c; dataptr += _ykpiv_set_length(dataptr, in_len + bytes + 3); *dataptr++ = 0x82; *dataptr++ = 0x00; *dataptr++ = YKPIV_IS_EC(algorithm) && decipher ? 0x85 : 0x81; dataptr += _ykpiv_set_length(dataptr, in_len); memcpy(dataptr, sign_in, (size_t)in_len); dataptr += in_len; if((res = ykpiv_transfer_data(state, templ, indata, (long)(dataptr - indata), data, &recv_len, &sw)) != YKPIV_OK) { if(state->verbose) { fprintf(stderr, "Sign command failed to communicate.\n"); } return res; } else if(sw != SW_SUCCESS) { if(state->verbose) { fprintf(stderr, "Failed sign command with code %x.\n", sw); } if (sw == SW_ERR_SECURITY_STATUS) return YKPIV_AUTHENTICATION_ERROR; else return YKPIV_GENERIC_ERROR; } /* skip the first 7c tag */ if(data[0] != 0x7c) { if(state->verbose) { fprintf(stderr, "Failed parsing signature reply.\n"); } return YKPIV_PARSE_ERROR; } dataptr = data + 1; dataptr += _ykpiv_get_length(dataptr, &len); /* skip the 82 tag */ if(*dataptr != 0x82) { if(state->verbose) { fprintf(stderr, "Failed parsing signature reply.\n"); } return YKPIV_PARSE_ERROR; } dataptr++; dataptr += _ykpiv_get_length(dataptr, &len); if(len > *out_len) { if(state->verbose) { fprintf(stderr, "Wrong size on output buffer.\n"); } return YKPIV_SIZE_ERROR; } *out_len = len; memcpy(out, dataptr, len); return YKPIV_OK; } ykpiv_rc ykpiv_sign_data(ykpiv_state *state, const unsigned char *raw_in, size_t in_len, unsigned char *sign_out, size_t *out_len, unsigned char algorithm, unsigned char key) { ykpiv_rc res = YKPIV_OK; if (NULL == state) return YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; /* don't attempt to reselect in crypt operations to avoid problems with PIN_ALWAYS */ /*if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup;*/ res = _general_authenticate(state, raw_in, in_len, sign_out, out_len, algorithm, key, false); /* Cleanup: */ _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_decipher_data(ykpiv_state *state, const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len, unsigned char algorithm, unsigned char key) { ykpiv_rc res = YKPIV_OK; if (NULL == state) return YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; /* don't attempt to reselect in crypt operations to avoid problems with PIN_ALWAYS */ /*if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup;*/ res = _general_authenticate(state, in, in_len, out, out_len, algorithm, key, true); /* Cleanup: */ _ykpiv_end_transaction(state); return res; } static ykpiv_rc _ykpiv_get_version(ykpiv_state *state, ykpiv_version_t *p_version) { APDU apdu; unsigned char data[261]; uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; if (!state) { return YKPIV_ARGUMENT_ERROR; } /* get version from state if already from device */ if (state->ver.major || state->ver.minor || state->ver.patch) { if (p_version) { memcpy(p_version, &(state->ver), sizeof(ykpiv_version_t)); } return YKPIV_OK; } /* get version from device */ memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_GET_VERSION; if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; } else if(sw == SW_SUCCESS) { /* check that we received enough data for the verson number */ if (recv_len < 3) { return YKPIV_SIZE_ERROR; } state->ver.major = data[0]; state->ver.minor = data[1]; state->ver.patch = data[2]; if (p_version) { memcpy(p_version, &(state->ver), sizeof(ykpiv_version_t)); } } else { res = YKPIV_GENERIC_ERROR; } return res; } ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { ykpiv_rc res; int result = 0; ykpiv_version_t ver = {0}; if ((res = _ykpiv_begin_transaction(state)) < YKPIV_OK) return YKPIV_PCSC_ERROR; if ((res = _ykpiv_ensure_application_selected(state)) < YKPIV_OK) goto Cleanup; if ((res = _ykpiv_get_version(state, &ver)) >= YKPIV_OK) { result = snprintf(version, len, "%d.%d.%d", ver.major, ver.minor, ver.patch); if(result < 0) { res = YKPIV_SIZE_ERROR; } } Cleanup: _ykpiv_end_transaction(state); return res; } /* caller must make sure that this is wrapped in a transaction for synchronized operation */ static ykpiv_rc _ykpiv_get_serial(ykpiv_state *state, uint32_t *p_serial, bool f_force) { ykpiv_rc res = YKPIV_OK; APDU apdu; const uint8_t yk_applet[] = { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01 }; unsigned char data[0xff]; uint32_t recv_len = sizeof(data); int sw; uint8_t *p_temp = NULL; if (!state) { return YKPIV_ARGUMENT_ERROR; } if (!f_force && (state->serial != 0)) { if (p_serial) *p_serial = state->serial; return YKPIV_OK; } if (state->ver.major < 5) { /* get serial from neo/yk4 devices using the otp applet */ uint8_t temp[0xff]; recv_len = sizeof(temp); memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SELECT_APPLICATION; apdu.st.p1 = 0x04; apdu.st.lc = sizeof(yk_applet); memcpy(apdu.st.data, yk_applet, sizeof(yk_applet)); if ((res = _send_data(state, &apdu, temp, &recv_len, &sw)) < YKPIV_OK) { if (state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } goto Cleanup; } else if (sw != SW_SUCCESS) { if (state->verbose) { fprintf(stderr, "Failed selecting yk application: %04x\n", sw); } res = YKPIV_GENERIC_ERROR; goto Cleanup; } recv_len = sizeof(data); memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = 0x01; apdu.st.p1 = 0x10; apdu.st.lc = 0x00; if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) < YKPIV_OK) { if (state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } goto Cleanup; } else if (sw != SW_SUCCESS) { if (state->verbose) { fprintf(stderr, "Failed retrieving serial number: %04x\n", sw); } res = YKPIV_GENERIC_ERROR; goto Cleanup; } recv_len = sizeof(temp); memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SELECT_APPLICATION; apdu.st.p1 = 0x04; apdu.st.lc = (unsigned char)sizeof(aid); memcpy(apdu.st.data, aid, sizeof(aid)); if((res = _send_data(state, &apdu, temp, &recv_len, &sw)) < YKPIV_OK) { if(state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } return res; } else if(sw != SW_SUCCESS) { if(state->verbose) { fprintf(stderr, "Failed selecting application: %04x\n", sw); } return YKPIV_GENERIC_ERROR; } } else { /* get serial from yk5 and later devices using the f8 command */ memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_GET_SERIAL; if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { if(state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } return res; } else if(sw != SW_SUCCESS) { if(state->verbose) { fprintf(stderr, "Failed retrieving serial number: %04x\n", sw); } return YKPIV_GENERIC_ERROR; } } /* check that we received enough data for the serial number */ if (recv_len < 4) { return YKPIV_SIZE_ERROR; } p_temp = (uint8_t*)(&state->serial); *p_temp++ = data[3]; *p_temp++ = data[2]; *p_temp++ = data[1]; *p_temp++ = data[0]; if (p_serial) *p_serial = state->serial; Cleanup: return res; } ykpiv_rc ykpiv_get_serial(ykpiv_state *state, uint32_t *p_serial) { ykpiv_rc res = YKPIV_OK; if ((res = _ykpiv_begin_transaction(state)) != YKPIV_OK) return YKPIV_PCSC_ERROR; if ((res = _ykpiv_ensure_application_selected(state)) != YKPIV_OK) goto Cleanup; res = _ykpiv_get_serial(state, p_serial, false); Cleanup: _ykpiv_end_transaction(state); return res; } static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { #if DISABLE_PIN_CACHE // Some embedded applications of this library may not want to keep the PIN // data in RAM for security reasons. return YKPIV_OK; #else if (!state) return YKPIV_ARGUMENT_ERROR; if (pin && state->pin == pin) { return YKPIV_OK; } if (state->pin) { yc_memzero(state->pin, strnlen(state->pin, CB_PIN_MAX)); _ykpiv_free(state, state->pin); state->pin = NULL; } if (pin && len > 0) { state->pin = _ykpiv_alloc(state, len * sizeof(char) + 1); if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } memcpy(state->pin, pin, len); state->pin[len] = 0; } return YKPIV_OK; #endif } static ykpiv_rc _verify(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries) { APDU apdu; unsigned char data[261]; uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; if (pin_len > CB_PIN_MAX) { return YKPIV_SIZE_ERROR; } memset(apdu.raw, 0, sizeof(apdu.raw)); apdu.st.ins = YKPIV_INS_VERIFY; apdu.st.p1 = 0x00; apdu.st.p2 = 0x80; apdu.st.lc = pin ? 0x08 : 0; if (pin) { memcpy(apdu.st.data, pin, pin_len); if (pin_len < CB_PIN_MAX) { memset(apdu.st.data + pin_len, 0xff, CB_PIN_MAX - pin_len); } } res = _send_data(state, &apdu, data, &recv_len, &sw); yc_memzero(&apdu, sizeof(apdu)); if (res != YKPIV_OK) { return res; } else if (sw == SW_SUCCESS) { if (pin && pin_len) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. _cache_pin(state, pin, pin_len); } if (tries) *tries = (sw & 0xf); return YKPIV_OK; } else if ((sw >> 8) == 0x63) { if (tries) *tries = (sw & 0xf); return YKPIV_WRONG_PIN; } else if (sw == SW_ERR_AUTH_BLOCKED) { if (tries) *tries = 0; return YKPIV_WRONG_PIN; } else { return YKPIV_GENERIC_ERROR; } } ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { return ykpiv_verify_select(state, pin, pin ? strlen(pin) : 0, tries, false); } ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select) { ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (force_select) { if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; } res = _verify(state, pin, pin_len, tries); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int *tries) { ykpiv_rc res; ykpiv_rc ykrc; if (NULL == state || NULL == tries) { return YKPIV_ARGUMENT_ERROR; } // Force a re-select to unverify, because once verified the spec dictates that // subsequent verify calls will return a "verification not needed" instead of // the number of tries left... res = _ykpiv_select_application(state); if (res != YKPIV_OK) return res; ykrc = ykpiv_verify(state, NULL, tries); // WRONG_PIN is expected on successful query. return ykrc == YKPIV_WRONG_PIN ? YKPIV_OK : ykrc; } ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries) { ykpiv_rc res = YKPIV_OK; unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, 0, 0}; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); int sw = 0; // Special case: if either retry count is 0, it's a successful no-op if (pin_tries == 0 || puk_tries == 0) { return YKPIV_OK; } if (pin_tries > 0xff || puk_tries > 0xff || pin_tries < 1 || puk_tries < 1) { return YKPIV_RANGE_ERROR; } templ[2] = (unsigned char)pin_tries; templ[3] = (unsigned char)puk_tries; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); if (YKPIV_OK == res) { if (SW_SUCCESS == sw) { // success, fall through } else if (sw == SW_ERR_AUTH_BLOCKED) { res = YKPIV_AUTHENTICATION_ERROR; } else if (sw == SW_ERR_SECURITY_STATUS) { res = YKPIV_AUTHENTICATION_ERROR; } else { res = YKPIV_GENERIC_ERROR; } } Cleanup: _ykpiv_end_transaction(state); return res; } static ykpiv_rc _ykpiv_change_pin(ykpiv_state *state, int action, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { int sw; unsigned char templ[] = {0, YKPIV_INS_CHANGE_REFERENCE, 0, 0x80}; unsigned char indata[0x10]; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); ykpiv_rc res; if (current_pin_len > CB_PIN_MAX) { return YKPIV_SIZE_ERROR; } if (new_pin_len > CB_PIN_MAX) { return YKPIV_SIZE_ERROR; } if(action == CHREF_ACT_UNBLOCK_PIN) { templ[1] = YKPIV_INS_RESET_RETRY; } else if(action == CHREF_ACT_CHANGE_PUK) { templ[3] = 0x81; } memcpy(indata, current_pin, current_pin_len); if(current_pin_len < CB_PIN_MAX) { memset(indata + current_pin_len, 0xff, CB_PIN_MAX - current_pin_len); } memcpy(indata + CB_PIN_MAX, new_pin, new_pin_len); if(new_pin_len < CB_PIN_MAX) { memset(indata + CB_PIN_MAX + new_pin_len, 0xff, CB_PIN_MAX - new_pin_len); } res = ykpiv_transfer_data(state, templ, indata, sizeof(indata), data, &recv_len, &sw); yc_memzero(indata, sizeof(indata)); if(res != YKPIV_OK) { return res; } else if(sw != SW_SUCCESS) { if((sw >> 8) == 0x63) { if (tries) *tries = sw & 0xf; return YKPIV_WRONG_PIN; } else if(sw == SW_ERR_AUTH_BLOCKED) { return YKPIV_PIN_LOCKED; } else { if(state->verbose) { fprintf(stderr, "Failed changing pin, token response code: %x.\n", sw); } return YKPIV_GENERIC_ERROR; } } return YKPIV_OK; } ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { ykpiv_rc res = YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _ykpiv_change_pin(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); if (res == YKPIV_OK && new_pin != NULL) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. _cache_pin(state, new_pin, new_pin_len); } Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_change_puk(ykpiv_state *state, const char * current_puk, size_t current_puk_len, const char * new_puk, size_t new_puk_len, int *tries) { ykpiv_rc res = YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _ykpiv_change_pin(state, CHREF_ACT_CHANGE_PUK, current_puk, current_puk_len, new_puk, new_puk_len, tries); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_unblock_pin(ykpiv_state *state, const char * puk, size_t puk_len, const char * new_pin, size_t new_pin_len, int *tries) { ykpiv_rc res = YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _ykpiv_change_pin(state, CHREF_ACT_UNBLOCK_PIN, puk, puk_len, new_pin, new_pin_len, tries); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, unsigned char *data, unsigned long *len) { ykpiv_rc res; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _ykpiv_fetch_object(state, object_id, data, len); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc _ykpiv_fetch_object(ykpiv_state *state, int object_id, unsigned char *data, unsigned long *len) { int sw; unsigned char indata[5]; unsigned char *inptr = indata; unsigned char templ[] = {0, YKPIV_INS_GET_DATA, 0x3f, 0xff}; ykpiv_rc res; inptr = set_object(object_id, inptr); if(inptr == NULL) { return YKPIV_INVALID_OBJECT; } if((res = ykpiv_transfer_data(state, templ, indata, (long)(inptr - indata), data, len, &sw)) != YKPIV_OK) { return res; } if(sw == SW_SUCCESS) { size_t outlen = 0; unsigned int offs = 0; if ((*len < 2) || !_ykpiv_has_valid_length(data + 1, *len - 1)) { return YKPIV_SIZE_ERROR; } offs = _ykpiv_get_length(data + 1, &outlen); if(offs == 0) { return YKPIV_SIZE_ERROR; } if(outlen + offs + 1 != *len) { if(state->verbose) { fprintf(stderr, "Invalid length indicated in object, total objlen is %lu, indicated length is %lu.", *len, (unsigned long)outlen); } return YKPIV_SIZE_ERROR; } memmove(data, data + 1 + offs, outlen); *len = (unsigned long)outlen; return YKPIV_OK; } else { return YKPIV_GENERIC_ERROR; } } ykpiv_rc ykpiv_save_object(ykpiv_state *state, int object_id, unsigned char *indata, size_t len) { ykpiv_rc res; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _ykpiv_save_object(state, object_id, indata, len); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc _ykpiv_save_object( ykpiv_state *state, int object_id, unsigned char *indata, size_t len) { unsigned char data[CB_BUF_MAX]; unsigned char *dataptr = data; unsigned char templ[] = {0, YKPIV_INS_PUT_DATA, 0x3f, 0xff}; int sw; ykpiv_rc res; unsigned long outlen = 0; if(len > sizeof(data) - 9) { return YKPIV_SIZE_ERROR; } dataptr = set_object(object_id, dataptr); if(dataptr == NULL) { return YKPIV_INVALID_OBJECT; } *dataptr++ = 0x53; dataptr += _ykpiv_set_length(dataptr, len); memcpy(dataptr, indata, len); dataptr += len; if((res = _ykpiv_transfer_data(state, templ, data, (long)(dataptr - data), NULL, &outlen, &sw)) != YKPIV_OK) { return res; } if(SW_SUCCESS == sw) { return YKPIV_OK; } else if (SW_ERR_SECURITY_STATUS == sw) { return YKPIV_AUTHENTICATION_ERROR; } else { return YKPIV_GENERIC_ERROR; } } ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, unsigned char algorithm, const unsigned char *p, size_t p_len, const unsigned char *q, size_t q_len, const unsigned char *dp, size_t dp_len, const unsigned char *dq, size_t dq_len, const unsigned char *qinv, size_t qinv_len, const unsigned char *ec_data, unsigned char ec_data_len, const unsigned char pin_policy, const unsigned char touch_policy) { unsigned char key_data[1024]; unsigned char *in_ptr = key_data; unsigned char templ[] = {0, YKPIV_INS_IMPORT_KEY, algorithm, key}; unsigned char data[256]; unsigned long recv_len = sizeof(data); unsigned elem_len; int sw; const unsigned char *params[5]; size_t lens[5]; size_t padding; unsigned char n_params; int i; int param_tag; ykpiv_rc res; if (state == NULL) return YKPIV_GENERIC_ERROR; if (key == YKPIV_KEY_CARDMGM || key < YKPIV_KEY_RETIRED1 || (key > YKPIV_KEY_RETIRED20 && key < YKPIV_KEY_AUTHENTICATION) || (key > YKPIV_KEY_CARDAUTH && key != YKPIV_KEY_ATTESTATION)) { return YKPIV_KEY_ERROR; } if (pin_policy != YKPIV_PINPOLICY_DEFAULT && pin_policy != YKPIV_PINPOLICY_NEVER && pin_policy != YKPIV_PINPOLICY_ONCE && pin_policy != YKPIV_PINPOLICY_ALWAYS) return YKPIV_GENERIC_ERROR; if (touch_policy != YKPIV_TOUCHPOLICY_DEFAULT && touch_policy != YKPIV_TOUCHPOLICY_NEVER && touch_policy != YKPIV_TOUCHPOLICY_ALWAYS && touch_policy != YKPIV_TOUCHPOLICY_CACHED) return YKPIV_GENERIC_ERROR; if (algorithm == YKPIV_ALGO_RSA1024 || algorithm == YKPIV_ALGO_RSA2048) { if (p_len + q_len + dp_len + dq_len + qinv_len >= sizeof(key_data)) { return YKPIV_SIZE_ERROR; } if (algorithm == YKPIV_ALGO_RSA1024) elem_len = 64; if (algorithm == YKPIV_ALGO_RSA2048) elem_len = 128; if (p == NULL || q == NULL || dp == NULL || dq == NULL || qinv == NULL) return YKPIV_GENERIC_ERROR; params[0] = p; lens[0] = p_len; params[1] = q; lens[1] = q_len; params[2] = dp; lens[2] = dp_len; params[3] = dq; lens[3] = dq_len; params[4] = qinv; lens[4] = qinv_len; param_tag = 0x01; n_params = 5; } else if (algorithm == YKPIV_ALGO_ECCP256 || algorithm == YKPIV_ALGO_ECCP384) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" if ((size_t)ec_data_len >= sizeof(key_data)) { /* This can never be true, but check to be explicit. */ return YKPIV_SIZE_ERROR; } #pragma GCC diagnostic pop if (algorithm == YKPIV_ALGO_ECCP256) elem_len = 32; if (algorithm == YKPIV_ALGO_ECCP384) elem_len = 48; if (ec_data == NULL) return YKPIV_GENERIC_ERROR; params[0] = ec_data; lens[0] = ec_data_len; param_tag = 0x06; n_params = 1; } else return YKPIV_ALGORITHM_ERROR; for (i = 0; i < n_params; i++) { size_t remaining; *in_ptr++ = param_tag + i; in_ptr += _ykpiv_set_length(in_ptr, elem_len); padding = elem_len - lens[i]; remaining = (uintptr_t)key_data + sizeof(key_data) - (uintptr_t)in_ptr; if (padding > remaining) { res = YKPIV_ALGORITHM_ERROR; goto Cleanup; } memset(in_ptr, 0, padding); in_ptr += padding; memcpy(in_ptr, params[i], lens[i]); in_ptr += lens[i]; } if (pin_policy != YKPIV_PINPOLICY_DEFAULT) { *in_ptr++ = YKPIV_PINPOLICY_TAG; *in_ptr++ = 0x01; *in_ptr++ = pin_policy; } if (touch_policy != YKPIV_TOUCHPOLICY_DEFAULT) { *in_ptr++ = YKPIV_TOUCHPOLICY_TAG; *in_ptr++ = 0x01; *in_ptr++ = touch_policy; } if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; if ((res = ykpiv_transfer_data(state, templ, key_data, (long)(in_ptr - key_data), data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } if (SW_SUCCESS != sw) { res = YKPIV_GENERIC_ERROR; if (sw == SW_ERR_SECURITY_STATUS) { res = YKPIV_AUTHENTICATION_ERROR; } goto Cleanup; } Cleanup: yc_memzero(key_data, sizeof(key_data)); _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char *data, size_t *data_len) { ykpiv_rc res; unsigned char templ[] = {0, YKPIV_INS_ATTEST, key, 0}; int sw; unsigned long ul_data_len; if (state == NULL || data == NULL || data_len == NULL) { return YKPIV_ARGUMENT_ERROR; } ul_data_len = (unsigned long)*data_len; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; if ((res = ykpiv_transfer_data(state, templ, NULL, 0, data, &ul_data_len, &sw)) != YKPIV_OK) { goto Cleanup; } if (SW_SUCCESS != sw) { res = YKPIV_GENERIC_ERROR; if (SW_ERR_NOT_SUPPORTED == sw) { res = YKPIV_NOT_SUPPORTED; } goto Cleanup; } if (data[0] != 0x30) { res = YKPIV_GENERIC_ERROR; goto Cleanup; } *data_len = (size_t)ul_data_len; Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_auth_getchallenge(ykpiv_state *state, uint8_t *challenge, const size_t challenge_len) { ykpiv_rc res = YKPIV_OK; APDU apdu = { 0 }; unsigned char data[261] = { 0 }; uint32_t recv_len = sizeof(data); int sw = 0; if (NULL == state) return YKPIV_GENERIC_ERROR; if (NULL == challenge) return YKPIV_GENERIC_ERROR; if (8 != challenge_len) return YKPIV_SIZE_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; /* get a challenge from the card */ memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_AUTHENTICATE; apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ apdu.st.lc = 0x04; apdu.st.data[0] = 0x7c; apdu.st.data[1] = 0x02; apdu.st.data[2] = 0x81; //0x80; if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } else if (sw != SW_SUCCESS) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } memcpy(challenge, data + 4, 8); Cleanup: _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_auth_verifyresponse(ykpiv_state *state, uint8_t *response, const size_t response_len) { ykpiv_rc res = YKPIV_OK; APDU apdu = { 0 }; unsigned char data[261] = { 0 }; uint32_t recv_len = sizeof(data); int sw = 0; unsigned char *dataptr = apdu.st.data; if (NULL == state) return YKPIV_GENERIC_ERROR; if (NULL == response) return YKPIV_GENERIC_ERROR; if (8 != response_len) return YKPIV_SIZE_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; /* note: do not select the applet here, as it resets the challenge state */ /* send the response to the card and a challenge of our own. */ recv_len = sizeof(data); memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_AUTHENTICATE; apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ *dataptr++ = 0x7c; *dataptr++ = 0x0a; /* 2 + 8 */ *dataptr++ = 0x82; *dataptr++ = 8; memcpy(dataptr, response, response_len); dataptr += 8; apdu.st.lc = (unsigned char)(dataptr - apdu.st.data); if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { goto Cleanup; } else if (sw != SW_SUCCESS) { res = YKPIV_AUTHENTICATION_ERROR; goto Cleanup; } Cleanup: yc_memzero(&apdu, sizeof(apdu)); _ykpiv_end_transaction(state); return res; } static const uint8_t MGMT_AID[] = { 0xa0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17 }; /* deauthenticates the user pin and mgm key */ ykpiv_rc ykpiv_auth_deauthenticate(ykpiv_state *state) { ykpiv_rc res = YKPIV_OK; APDU apdu; unsigned char data[0xff]; uint32_t recv_len = sizeof(data); int sw; if (!state) { return YKPIV_ARGUMENT_ERROR; } /* this function does not use ykpiv_transfer_data because it selects a different app */ if ((res = _ykpiv_begin_transaction(state)) < YKPIV_OK) return res; memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SELECT_APPLICATION; apdu.st.p1 = 0x04; apdu.st.lc = sizeof(MGMT_AID); memcpy(apdu.st.data, MGMT_AID, sizeof(MGMT_AID)); if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) < YKPIV_OK) { if (state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } goto Cleanup; } else if (sw != SW_SUCCESS) { if (state->verbose) { fprintf(stderr, "Failed selecting mgmt application: %04x\n", sw); } res = YKPIV_GENERIC_ERROR; goto Cleanup; } Cleanup: _ykpiv_end_transaction(state); return res; }
28.888257
171
0.661557
[ "object" ]
c80ebf36ca33264d8d69c8079b691b81f1482767
3,656
h
C
AI_Engine_Development/Design_Tutorials/02-super_sampling_rate_fir/MultiKernel/aie/graph.h
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
1
2022-03-09T06:15:43.000Z
2022-03-09T06:15:43.000Z
AI_Engine_Development/Design_Tutorials/02-super_sampling_rate_fir/MultiKernel/aie/graph.h
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
null
null
null
AI_Engine_Development/Design_Tutorials/02-super_sampling_rate_fir/MultiKernel/aie/graph.h
jlamperez/Vitis-Tutorials
9a5b611caabb5656bbb2879116e032227b164bfd
[ "Apache-2.0" ]
null
null
null
/* * (c) Copyright 2021 Xilinx, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma once #include <adf.h> #include "system_settings.h" #include "aie_kernels.h" std::vector<cint16> taps = std::vector<cint16>({ { -82, -253},{ 0, -204},{ 11, -35},{ -198, 273}, { -642, 467},{ -1026, 333},{ -927, 0},{ -226, -73}, { 643, 467},{ 984, 1355},{ 550, 1691},{ 0, 647}, { 538, -1656},{ 2860, -3936},{ 6313, -4587},{ 9113, -2961}, { 9582, 0},{ 7421, 2411},{ 3936, 2860},{ 1023, 1409}, { -200, -615},{ 0, -1778},{ 517, -1592},{ 467, -643}, { -192, 140},{ -882, 287},{ -1079, 0},{ -755, -245}, { -273, -198},{ 22, 30},{ 63, 194},{ 0, 266} }); std::vector<cint16> taps_aie(taps.rbegin(),taps.rend()); #define GetPhase(Start,Step) {\ taps_aie[Start],taps_aie[Start+Step],taps_aie[Start+2*Step],taps_aie[Start+3*Step],\ taps_aie[Start+4*Step],taps_aie[Start+5*Step],taps_aie[Start+6*Step],taps_aie[Start+7*Step]} std::vector<cint16> taps4_0 = std::vector<cint16>(GetPhase(0,1)); std::vector<cint16> taps4_1 = std::vector<cint16>(GetPhase(8,1)); std::vector<cint16> taps4_2 = std::vector<cint16>(GetPhase(16,1)); std::vector<cint16> taps4_3 = std::vector<cint16>(GetPhase(24,1)); const int SHIFT = 0; // to analyze the output generated by impulses at the input //const int SHIFT = 15; // for realistic input samples using namespace adf; class FIRGraph_4Kernels: public adf::graph { private: kernel k[4]; public: input_port in[4]; output_port out; FIRGraph_4Kernels() { k[0] = kernel::create_object<SingleStream::FIR_MultiKernel_cout<NUM_SAMPLES,SHIFT>>(taps4_0); k[1] = kernel::create_object<SingleStream::FIR_MultiKernel_cincout<NUM_SAMPLES,SHIFT>>(taps4_1); k[2] = kernel::create_object<SingleStream::FIR_MultiKernel_cincout<NUM_SAMPLES,SHIFT>>(taps4_2); k[3] = kernel::create_object<SingleStream::FIR_MultiKernel_cin<NUM_SAMPLES,SHIFT>>(taps4_3); const int NChunks = 4; for(int i=0;i<NChunks;i++) { runtime<ratio>(k[i]) = 0.9; source(k[i]) = "aie_kernels/FirSingleStream.cpp"; headers(k[i]) = {"aie_kernels/FirSingleStream.h"}; } // Constraints: location of the first kernel in the cascade location<kernel>(k[0]) = tile(25,0); // Discard first elements of the stream, depending on position in the cascade initialization_function(k[0]) = "SingleStream::FIRinit<0>"; initialization_function(k[1]) = "SingleStream::FIRinit<8>"; initialization_function(k[2]) = "SingleStream::FIRinit<16>"; initialization_function(k[3]) = "SingleStream::FIRinit<24>"; // Cascade Connections and output connection for(int i=0;i<NChunks-1;i++) connect<cascade> (k[i].out[0],k[i+1].in[1]); connect<stream> (k[NChunks-1].out[0],out); // Input Streams connections for(int i=0;i<NChunks;i++) connect<stream>(in[i],k[i].in[0]); }; }; class TopGraph: public adf::graph { public: FIRGraph_4Kernels G1; input_port in[4]; output_port out; TopGraph() { for(int i=0;i<4;i++) connect<> (in[i],G1.in[i]); connect<> (G1.out,out); } };
29.723577
98
0.655908
[ "vector" ]
c813eab616535924b2c6b113f779df88858bddbb
2,542
h
C
openbabel-2.4.1/src/charges/qtpie.h
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
1
2017-09-16T07:36:29.000Z
2017-09-16T07:36:29.000Z
openbabel-2.4.1/src/charges/qtpie.h
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
openbabel-2.4.1/src/charges/qtpie.h
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
/********************************************************************** qtpie.h - A OBChargeModel to handle QTPIE charges Copyright (C) 2010 by Jiahao Chen <jiahao@mit.edu> This file is part of the Open Babel project. For more information, see <http://openbabel.org/> 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 version 2 of the License. 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. ***********************************************************************/ #ifndef __QTPIE__H__ #define __QTPIE__H__ #include <openbabel/chargemodel.h> #include <openbabel/mol.h> #include <math.h> #ifdef HAVE_EIGEN #include <Eigen/LU> #include <Eigen/SVD> #define pi 3.1415926 #define sqr(x) ((x)*(x)) #define cube(x) ((x)*(x)*(x)) //// conversion factor from electron volt to Hartree const double eV = 3.67493245e-2; /// conversion factor from Angstrom to bohr const double Angstrom = 1./0.529177249; using namespace Eigen; /// Determines threshold value of Coulomb interaction beyond which the classical 1/R expression /// will be used instead of an integral over the Gaussian orbitals /// This is a pre-screening cutoff. const double CoulombThreshold = 1.e-9; const double OverlapThreshold = 1.e-9; namespace OpenBabel { class QTPIECharges : public OBChargeModel { public: QTPIECharges(void) : OBChargeModel("fake ID", false){}; QTPIECharges(const char* ID) : OBChargeModel(ID, false){}; const char* Description(){ return "Assign QTPIE (charge transfer, polarization and equilibration) partial charges (Chen and Martinez, 2007)"; } /// \return whether partial charges were successfully assigned to this molecule bool ComputeCharges(OBMol &mol); double DipoleScalingFactor() { return 4.041; } // fit from regression private: Vector3d GetParameters(unsigned int Z, int Q); bool solver(MatrixXd A,VectorXd b, VectorXd &x, const double NormThreshold = 1.e-6); double CoulombInt(double a, double b, double R); double OverlapInt(double a, double b, double R); MatrixXd Hardness; ///The hardness matrix VectorXd Electronegativity, Voltage, Charge; double ChemicalPotential; std::vector< Vector3d > _parameters; void ParseParamFile(); }; }; //namespace OpenBabel #endif //HAVE_EIGEN #endif //__QTPIE_H__
31.775
145
0.713218
[ "vector" ]
c8144fe58979b458ec5a3cd0748720d90a8e55e4
19,719
h
C
src/vw/InterestPoint/Matcher.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
318
2015-01-02T16:37:34.000Z
2022-03-17T07:12:20.000Z
src/vw/InterestPoint/Matcher.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
39
2015-07-30T22:22:42.000Z
2021-03-23T16:11:55.000Z
src/vw/InterestPoint/Matcher.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
135
2015-01-19T00:57:20.000Z
2022-03-18T13:51:40.000Z
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is 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. // __END_LICENSE__ /// \file Matcher.h /// /// Classes and functions for matching image interest points. /// #ifndef _INTERESTPOINT_MATCHER_H_ #define _INTERESTPOINT_MATCHER_H_ #include <algorithm> #include <vw/Core/Log.h> #include <vw/InterestPoint/Descriptor.h> #include <vw/InterestPoint/InterestData.h> #include <vector> #include <boost/foreach.hpp> #ifdef VW_HAVE_PKG_FLANN #include <vw/Math/FLANNTree.h> #else //#include <vw/Math/KDTree.h> #error the FLANN library is now required! #endif namespace vw { namespace ip { //====================================================================== // Interest Point distance metrics /// Interest point metrics must be of form: /// /// float operator() (const InterestPoint& ip1, const InterestPoint &ip2, float maxdist = DBL_MAX) /// /// --> This one is for interoperability with our FLANNTRee class which does all our heavy-duty matching. /// static const math::FLANN_DistType flann_type=FLANN_DistType; /// L2 Norm: returns Euclidian distance squared between pair of /// interest point descriptors. Optional argument "maxdist" to /// provide early termination of computation if result will exceed maxdist. struct L2NormMetric { float operator() (InterestPoint const& ip1, InterestPoint const& ip2, float maxdist = std::numeric_limits<float>::max()) const; static const math::FLANN_DistType flann_type = math::FLANN_DistType_L2; }; /// Hamming distance for binary descriptors struct HammingMetric { float operator() (InterestPoint const& ip1, InterestPoint const& ip2, float maxdist = std::numeric_limits<float>::max()) const; static const math::FLANN_DistType flann_type = math::FLANN_DistType_Hamming; }; /// KL distance (relative entropy) between interest point /// descriptors. Optional argument "maxdist" to provide early /// termination of computation if result will exceed maxdist. struct RelativeEntropyMetric { float operator() (InterestPoint const& ip1, InterestPoint const& ip2, float maxdist = std::numeric_limits<float>::max()) const; static const math::FLANN_DistType flann_type = math::FLANN_DistType_Unsupported; }; //====================================================================== template <class ListT> inline void sort_interest_points(ListT const& ip1, ListT const& ip2, std::vector<ip::InterestPoint> & ip1_sorted, std::vector<ip::InterestPoint> & ip2_sorted); /// Interest Point Match contraints functors to return a list of /// allowed match candidates to an interest point. /// /// Must have be of form: bool operator()( const InterestPoint& /// baseline_ip, const InterestPoint& test_ip); returning true /// or false depending on whether the test_ip is satisfies the /// constraints relative to basline_ip.. /// /// To use bimatch, must also include the inverse function: bool /// inverse ()( const InterestPoint& baseline_ip, const /// InterestPoint& test_ip) returning true or false under the /// inverse constraint mapping. /// /// This default matching constraint functor providing NO /// constraints on putative matches. class NullConstraint { public: bool operator()(InterestPoint const& /*baseline_ip*/, InterestPoint const& /*test_ip*/) const { return true; } bool inverse(InterestPoint const& /*baseline_ip*/, InterestPoint const& /*test_ip*/) const { return true; } }; /// Constraint on interest point orientation and scale differences. class ScaleOrientationConstraint { public: double scale_ratio_min; double scale_ratio_max; double ori_diff_min; double ori_diff_max; ScaleOrientationConstraint(double srmin = 0.9, double srmax = 1.1, double odmin = -0.1, double odmax = 0.1) : scale_ratio_min(srmin), scale_ratio_max(srmax), ori_diff_min(odmin), ori_diff_max(odmax) {} bool operator()(InterestPoint const& baseline_ip, InterestPoint const& test_ip) const; bool inverse(InterestPoint const& baseline_ip, InterestPoint const& test_ip) const { return this->operator()(test_ip, baseline_ip); } }; /// Constraint on interest point location differences. class PositionConstraint { public: double min_x; double max_x; double min_y; double max_y; PositionConstraint(double _min_x = -10.0, double _max_x = 10.0, double _min_y = -10.0, double _max_y = 10.0) : min_x(_min_x), max_x(_max_x), min_y(_min_y), max_y(_max_y) {} bool operator()(InterestPoint const& baseline_ip, InterestPoint const& test_ip) const; bool inverse(InterestPoint const& baseline_ip, InterestPoint const& test_ip) const { return this->operator()(test_ip, baseline_ip); } }; // --------------------------------------------------------------------------- // Interest Point Matcher // --------------------------------------------------------------------------- /// Interest point matcher class template < class MetricT, class ConstraintT > class InterestPointMatcher { ConstraintT m_constraint; MetricT m_distance_metric; double m_threshold; bool m_bidirectional; // Helper function to help reduce conditionals in the event of // NullConstraint. (Which is common). template <class InConstraintT> typename boost::disable_if<boost::is_same<InConstraintT,NullConstraint>, bool>::type check_constraint( InterestPoint const& ip1, InterestPoint const& ip2 ) const; template <class InConstraintT> typename boost::enable_if<boost::is_same<InConstraintT,NullConstraint>, bool>::type check_constraint( InterestPoint const& ip1, InterestPoint const& ip2 ) const { return true; } public: InterestPointMatcher(double threshold = 0.5, MetricT metric = MetricT(), ConstraintT constraint = ConstraintT(), bool bidirectional = false) : m_constraint(constraint), m_distance_metric(metric), m_threshold(threshold), m_bidirectional(bidirectional) { } /// Given two lists of interest points, this write to index_list /// the corresponding matching index in ip2. index_list is the /// same length as ip1. index_list will be filled with max value /// of size_t in the event that a match was not found. template <class ListT, class IndexListT > void operator()( ListT const& ip1, ListT const& ip2, IndexListT& index_list, const ProgressCallback &progress_callback = ProgressCallback::dummy_instance() ) const; /// Given two lists of interest points, this routine returns the two lists /// of matching interest points based on the Metric and Constraints provided by the user. template <class ListT, class MatchListT> void operator()( ListT const& ip1, ListT const& ip2, MatchListT& matched_ip1, MatchListT& matched_ip2, const ProgressCallback &progress_callback = ProgressCallback::dummy_instance() ) const; }; /// A even more basic interest point matcher that doesn't rely on /// KDTree as it sometimes produces incorrect results template < class MetricT, class ConstraintT > class InterestPointMatcherSimple { ConstraintT m_constraint; MetricT m_distance_metric; double m_threshold; public: InterestPointMatcherSimple(double threshold = 0.5, MetricT metric = MetricT(), ConstraintT constraint = ConstraintT()) : m_constraint(constraint), m_distance_metric(metric), m_threshold(threshold) { } /// Given two lists of interest points, this routine returns the two lists /// of matching interest points based on the Metric and Constraints provided by the user. template <class ListT, class MatchListT> void operator()( ListT const& ip1, ListT const& ip2, MatchListT& matched_ip1, MatchListT& matched_ip2, const ProgressCallback &progress_callback = ProgressCallback::dummy_instance() ) const; }; ////////////////////////////////////////////////////////////////////////////// // Convenience Typedefs typedef InterestPointMatcher< L2NormMetric, NullConstraint > DefaultMatcher; typedef InterestPointMatcher< L2NormMetric, ScaleOrientationConstraint > ConstraintedMatcher; /// Matching doesn't constraint a point to being matched to only one /// other point. Here's a way to remove duplicates and have only pairwise points. void remove_duplicates(std::vector<InterestPoint>& ip1, std::vector<InterestPoint>& ip2); /// The name of the match file. std::string match_filename(std::string const& out_prefix, std::string const& input_file1, std::string const& input_file2); /// The name of an IP file. std::string ip_filename(std::string const& out_prefix, std::string const& input_file); //========================================================================== // Fuction Definitions // TODO: Move to a .tcc file! template <class ListT> inline void sort_interest_points(ListT const& ip1, ListT const& ip2, std::vector<ip::InterestPoint> & ip1_sorted, std::vector<ip::InterestPoint> & ip2_sorted){ // The interest points may be in random order due to the fact that // they are obtained using multiple threads. Must sort them to // restore a unique order for the matcher to give a unique result. ip1_sorted.reserve( ip1.size() ); ip1_sorted.clear(); ip2_sorted.reserve( ip2.size() ); ip2_sorted.clear(); BOOST_FOREACH( ip::InterestPoint const& ip, ip1 ) ip1_sorted.push_back(ip); BOOST_FOREACH( ip::InterestPoint const& ip, ip2 ) ip2_sorted.push_back(ip); std::sort(ip1_sorted.begin(), ip1_sorted.end(), InterestPointLessThan); std::sort(ip2_sorted.begin(), ip2_sorted.end(), InterestPointLessThan); } //--------------------------------------------------------------------------- // InterestPointMatcher // Helper function to help reduce conditionals in the event of // NullConstraint. (Which is common). template <class MetricT, class ConstraintT> template <class InConstraintT> typename boost::disable_if<boost::is_same<InConstraintT,NullConstraint>, bool>::type InterestPointMatcher<MetricT, ConstraintT>:: check_constraint( InterestPoint const& ip1, InterestPoint const& ip2 ) const { if (m_bidirectional) { if (m_constraint(ip2, ip1) && m_constraint(ip1, ip2)) return true; } else { if (m_constraint(ip1, ip2)) return true; } return false; } // Given two lists of interest points, this write to index_list // the corresponding matching index in ip2. index_list is the // same length as ip1. index_list will be filled with max value // of size_t in the event that a match was not found. template <class MetricT, class ConstraintT> template <class ListT, class IndexListT > void InterestPointMatcher<MetricT, ConstraintT>::operator()( ListT const& ip1, ListT const& ip2, IndexListT& index_list, const ProgressCallback &progress_callback) const { Timer total_time("Total elapsed time", DebugMessage, "interest_point"); size_t ip1_size = ip1.size(), ip2_size = ip2.size(); index_list.clear(); if (!ip1_size || !ip2_size) { vw_out(InfoMessage,"interest_point") << "KD-Tree: no points to match, exiting\n"; progress_callback.report_finished(); return; } float inc_amt = 1.0f/float(ip1_size); // Set up FLANNTree objects of all the different types we may need. math::FLANNTree<float > kd_float; math::FLANNTree<unsigned char> kd_uchar; Matrix<float > ip2_matrix_float; Matrix<unsigned char> ip2_matrix_uchar; // Pack the IP descriptors into a matrix and feed it to the chosen FLANNTree object const bool use_uchar_FLANN = (MetricT::flann_type == math::FLANN_DistType_Hamming); if (use_uchar_FLANN) { ip_list_to_matrix(ip2, ip2_matrix_uchar); kd_uchar.load_match_data( ip2_matrix_uchar, MetricT::flann_type ); }else { ip_list_to_matrix(ip2, ip2_matrix_float); kd_float.load_match_data( ip2_matrix_float, MetricT::flann_type ); } vw_out(InfoMessage,"interest_point") << "FLANN-Tree created. Searching...\n"; const size_t KNN = 2; // Find this many matches Vector<int > indices(KNN); Vector<double> distances(KNN); progress_callback.report_progress(0); BOOST_FOREACH( InterestPoint ip, ip1 ) { if (progress_callback.abort_requested()) vw_throw( Aborted() << "Aborted by ProgressCallback" ); progress_callback.report_incremental_progress(inc_amt); size_t num_matches_found = 0; if (use_uchar_FLANN) { // Convert the descriptor to unsigned chars, then call FLANN vw::Vector<unsigned char> uchar_descriptor(ip.descriptor.size()); for (size_t i=0; i<ip.descriptor.size(); ++i) uchar_descriptor[i] = static_cast<unsigned char>(ip.descriptor[i]); num_matches_found = kd_uchar.knn_search( uchar_descriptor, indices, distances, KNN ); } else // Use float num_matches_found = kd_float.knn_search( ip.descriptor, indices, distances, KNN ); //vw_out() << "KNN matches "<< num_matches_found <<": indices = " << indices << ", distances = " << distances << std::endl; if (num_matches_found < KNN) { // If we did not get two nearest neighbors, return no match for this point. vw_out() << "Bad descriptor = " << ip.descriptor << std::endl; index_list.push_back( (size_t)(-1) ); // Last value of size_t } else { // Copy the two nearest matches std::vector<InterestPoint> nearest_records(KNN); typename ListT::const_iterator iterator = ip2.begin(); std::advance( iterator, indices[0] ); nearest_records[0] = *iterator; iterator = ip2.begin(); std::advance( iterator, indices[1] ); nearest_records[1] = *iterator; // Check the user constraint on the record if ( check_constraint<ConstraintT>( nearest_records[0], ip ) ) { double dist0 = m_distance_metric(nearest_records[0], ip); double dist1 = m_distance_metric(nearest_records[1], ip); // As a final check, make sure the nearest record is significantly closer than the next one. if (dist0 < m_threshold * dist1) { index_list.push_back( indices[0] ); } else { index_list.push_back( (size_t)(-1) ); // Last value of size_t } } // End check constraint } // End both valid case } } // End InterestPointMatcher::operator() // Given two lists of interest points, this routine returns the two lists // of matching interest points based on the Metric and Constraints // provided by the user. template <class MetricT, class ConstraintT> template <class ListT, class MatchListT> void InterestPointMatcher<MetricT, ConstraintT>::operator()( ListT const& ip1, ListT const& ip2, MatchListT& matched_ip1, MatchListT& matched_ip2, const ProgressCallback &progress_callback) const { // Clear output lists matched_ip1.clear(); matched_ip2.clear(); // Redirect to the other version of this function, getting the results in an index list. std::list<size_t> index_list; this->operator()(ip1, ip2, index_list, progress_callback); // Now convert from the index output to the pairs output // Loop through ip1 and index_list std::list<size_t>::const_iterator index_list_iter = index_list.begin(); BOOST_FOREACH( InterestPoint ip, ip1 ) { // Get and check the match index typename ListT::const_iterator ip2_iter = ip2.begin(); size_t list_position = *index_list_iter; if (list_position < ip2.size()) { // Skip points without a match // Get the ip2 that corresponds to the current ip1 and store the point pair std::advance( ip2_iter, list_position); matched_ip1.push_back(ip); matched_ip2.push_back(*ip2_iter); } ++index_list_iter; } // End loop through ip1 } //----------------------------------------------------------- // InterestPointMatcherSimple // Given two lists of interest points, this routine returns the two lists // of matching interest points based on the Metric and Constraints // provided by the user. template <class MetricT, class ConstraintT> template <class ListT, class MatchListT> void InterestPointMatcherSimple<MetricT, ConstraintT>::operator()( ListT const& ip1, ListT const& ip2, MatchListT& matched_ip1, MatchListT& matched_ip2, const ProgressCallback &progress_callback) const { Timer total_time("Total elapsed time", DebugMessage, "interest_point"); matched_ip1.clear(); matched_ip2.clear(); if (!ip1.size() || !ip2.size()) { vw_out(InfoMessage,"interest_point") << "No points to match, exiting\n"; progress_callback.report_finished(); return; } float inc_amt = 1.0f / float(ip1.size()); progress_callback.report_progress(0); std::vector<int> match_index( ip1.size() ); // Loop through one vector of IPs for (size_t i = 0; i < ip1.size(); i++ ) { if (progress_callback.abort_requested()) vw_throw( Aborted() << "Aborted by ProgressCallback" ); progress_callback.report_incremental_progress(inc_amt); double first_pick = 1e100, second_pick = 1e100; match_index[i] = -1; // Comparing ip1_sorted's feature against all of ip2_sorted's for (size_t j = 0; j < ip2.size(); j++ ) { if ( ip1[i].polarity != ip2[j].polarity ) continue; // Use the selected distance metric to measure the distance between the points double distance = m_distance_metric( ip1[i], ip2[j] ); if ( distance < first_pick ) { match_index[i] = j; second_pick = first_pick; first_pick = distance; } else if ( distance < second_pick ) { second_pick = distance; } } //vw_out() << "Best 2 distances: " << first_pick <<", " << second_pick <<"\n"; // Checking to see if the match is strong enough if ( first_pick > m_threshold * second_pick ) match_index[i] = -1; } // End double loop through IPs progress_callback.report_finished(); // Building matched_ip1 & matched_ip2 for (size_t i = 0; i < ip1.size(); i++ ) { if ( match_index[i] != -1 ) { matched_ip1.push_back( ip1[i] ); matched_ip2.push_back( ip2[match_index[i]] ); } } } }} // namespace vw::ip #endif // _INTEREST_POINT_MATCHER_H_
39.836364
144
0.65977
[ "object", "vector" ]
c81bd69bab911c4ef82523fcdd577bd559df1532
931
h
C
src/engine/cwd.h
MaxSac/build
482c25f3a26171073c7e6c59f0427f2259a63fec
[ "BSL-1.0" ]
1
2020-04-28T15:15:28.000Z
2020-04-28T15:15:28.000Z
src/engine/cwd.h
MaxSac/build
482c25f3a26171073c7e6c59f0427f2259a63fec
[ "BSL-1.0" ]
2
2017-05-23T08:01:11.000Z
2019-09-06T20:49:05.000Z
src/engine/cwd.h
MaxSac/build
482c25f3a26171073c7e6c59f0427f2259a63fec
[ "BSL-1.0" ]
8
2015-11-03T14:12:19.000Z
2020-09-22T19:20:54.000Z
/* * Copyright 2002. Vladimir Prus * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /* * cwd.h - manages the current working folder information */ #ifndef CWD_H #define CWD_H #include "config.h" #include "object.h" #include <string> /* cwd() - returns the current working folder */ OBJECT * cwd( void ); namespace b2 { const std::string & cwd_str(); } /* cwd_init() - initialize the cwd module functionality * * The current working folder can not change in Boost Jam so this function * gets the current working folder information from the OS and stores it * internally. * * Expected to be called at program startup before the program's current * working folder has been changed */ void cwd_init( void ); /* cwd_done() - cleans up the cwd module functionality */ void cwd_done( void ); #endif
21.651163
76
0.711063
[ "object" ]
c81bf4da06726a46a5ddf991dcfa8961717d929c
1,793
c
C
src/yorn.c
dave18/CastleQuest_Amiga
20d88d594ccd51888ab5b66c71eaa46797e28086
[ "Info-ZIP" ]
null
null
null
src/yorn.c
dave18/CastleQuest_Amiga
20d88d594ccd51888ab5b66c71eaa46797e28086
[ "Info-ZIP" ]
null
null
null
src/yorn.c
dave18/CastleQuest_Amiga
20d88d594ccd51888ab5b66c71eaa46797e28086
[ "Info-ZIP" ]
null
null
null
/* yorn.f -- translated by f2c (version 19940615). You must link the resulting object file with the libraries: f2c.lib math=standard (in that order) */ #include "f2c.h" /* Table of constant values */ extern struct { long cierr; long ciunit; long ciend; char *cifmt; long cirec; } outstring; extern void printstring(); static integer c__1 = 1; /* Subroutine */ int yorn_(ii) integer *ii; { /* Initialized data */ static struct { char e_1[4]; integer e_2; } equiv_7 = { {'Y', ' ', ' ', ' '}, 0 }; #define y (*(integer *)&equiv_7) static struct { char e_1[4]; integer e_2; } equiv_8 = { {'N', ' ', ' ', ' '}, 0 }; #define n (*(integer *)&equiv_8) /* Format strings */ static char fmt_2000[] = "(\002 \002)"; static char fmt_1001[] = "(a1)"; static char fmt_2001[] = "(\0020 Please answer YES or NO !\002)"; /* System generated locals */ integer i__1; /* Builtin functions */ integer s_wsfe(), e_wsfe(), s_rsfe(), do_fio(), e_rsfe(); /* Local variables */ static integer ans; /* Fortran I/O blocks */ static cilist io___3 = { 0, 6, 0, fmt_2000, 0 }; static cilist io___4 = { 1, 5, 1, fmt_1001, 0 }; static cilist io___6 = { 0, 6, 0, fmt_2001, 0 }; L10: s_wsfe(&io___3); e_wsfe(); i__1 = s_rsfe(&io___4); if (i__1 != 0) { goto L30; } i__1 = do_fio(&c__1, (char *)&ans, (ftnlen)sizeof(integer)); if (i__1 != 0) { goto L30; } i__1 = e_rsfe(); if (i__1 != 0) { goto L30; } *ii = 1; if (ans == y) { goto L100; } if (ans != n) { goto L30; } *ii = 0; goto L100; L30: //s_wsfe(&io___6); //e_wsfe(); printstring(&io___6); goto L10; L100: return 0; } /* yorn_ */ #undef n #undef y
17.240385
70
0.546012
[ "object" ]
c81cd35ce7b5bfa32f512761f864f8bcfe4a2098
3,700
h
C
dreal/solver/formula_evaluator.h
soonho-tri/dreal4
e774d1496001e826c82dccee45094dd694089bee
[ "Apache-2.0" ]
null
null
null
dreal/solver/formula_evaluator.h
soonho-tri/dreal4
e774d1496001e826c82dccee45094dd694089bee
[ "Apache-2.0" ]
1
2018-01-19T16:11:44.000Z
2018-01-19T16:11:44.000Z
dreal/solver/formula_evaluator.h
soonho-tri/dreal4
e774d1496001e826c82dccee45094dd694089bee
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <ostream> #include <vector> #include "dreal/symbolic/symbolic.h" #include "dreal/util/box.h" #include "dreal/util/logging.h" namespace dreal { /// Represents the evaluation result of a constraint given a box. class FormulaEvaluationResult { public: enum class Type { VALID, ///< Any point in the box satisfies the constraint. UNSAT, ///< There is no point in the box satisfying the constraint. UNKNOWN, ///< It is unknown. It may indicate that there is a /// point in the box satisfying the constraint. }; /// Constructs an FormulaEvaluationResult with @p type and @p evaluation. FormulaEvaluationResult(Type type, const Box::Interval& evaluation); /// Returns the type of this result. Type type() const; /// Returns the interval evaluation of this result. const Box::Interval& evaluation() const; private: Type type_; // Given e₁ rop e₂, it keeps the result of the interval evaluation of (e₁ - // e₂) over a box. Box::Interval evaluation_; }; std::ostream& operator<<(std::ostream& os, FormulaEvaluationResult::Type type); std::ostream& operator<<(std::ostream& os, const FormulaEvaluationResult& result); // Forward declaration. class FormulaEvaluatorCell; /// Class to evaluate a symbolic formula with a box. class FormulaEvaluator { public: // No default constructor. FormulaEvaluator() = delete; /// Default copy constructor. FormulaEvaluator(const FormulaEvaluator&) = default; /// Default move constructor. FormulaEvaluator(FormulaEvaluator&&) = default; /// Default copy assign operator. FormulaEvaluator& operator=(const FormulaEvaluator&) = default; /// Default move assign operator. FormulaEvaluator& operator=(FormulaEvaluator&&) = default; /// Default destruction ~FormulaEvaluator() = default; /// Evaluates the constraint/formula with @p box. FormulaEvaluationResult operator()(const Box& box) const; /// Returns the occurred variables in the formula. const Variables& variables() const; const Formula& formula() const; /// Returns true if the based formula is a simple relational formula which is /// in form of `constant relop variable`. bool is_simple_relational() const; /// Returns true if the based formula is a not-equal formula which is /// in form of `e1 != e2` or `!(e1 == e2)`. bool is_neq() const; private: // Constructs an FormulaEvaluator from `ptr`. explicit FormulaEvaluator(std::shared_ptr<FormulaEvaluatorCell> ptr); std::shared_ptr<FormulaEvaluatorCell> ptr_; friend std::ostream& operator<<(std::ostream& os, const FormulaEvaluator& evaluator); friend FormulaEvaluator make_relational_formula_evaluator(const Formula& f); friend FormulaEvaluator make_forall_formula_evaluator(const Formula& f, double epsilon, double delta, int number_of_jobs); }; /// Creates FormulaEvaluator for a relational formula @p f using @p variables. FormulaEvaluator make_relational_formula_evaluator(const Formula& f); /// Creates FormulaEvaluator for a universally quantified formula @p f /// using @p variables, @p epsilon, @p delta, and @p number_of_jobs. FormulaEvaluator make_forall_formula_evaluator(const Formula& f, double epsilon, double delta, int number_of_jobs); std::ostream& operator<<(std::ostream& os, const FormulaEvaluator& evaluator); } // namespace dreal
32.743363
80
0.671892
[ "vector" ]
c82500b11b7cc241ba65e8ed3861fb742c1f1987
77,070
c
C
src/sys/dev/usb/wlan/if_rsu.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/dev/usb/wlan/if_rsu.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/dev/usb/wlan/if_rsu.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
/* $OpenBSD: if_rsu.c,v 1.17 2013/04/15 09:23:01 mglocker Exp $ */ /*- * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_rsu.c 298818 2016-04-29 22:14:11Z avos $"); /* * Driver for Realtek RTL8188SU/RTL8191SU/RTL8192SU. * * TODO: * o h/w crypto * o hostap / ibss / mesh * o sensible RSSI levels * o power-save operation */ #include "opt_wlan.h" #include <sys/param.h> #include <sys/endian.h> #include <sys/sockio.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <sys/kernel.h> #include <sys/socket.h> #include <sys/systm.h> #include <sys/conf.h> #include <sys/bus.h> #include <sys/rman.h> #include <sys/firmware.h> #include <sys/module.h> #include <machine/bus.h> #include <machine/resource.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_var.h> #include <net/if_arp.h> #include <net/if_dl.h> #include <net/if_media.h> #include <net/if_types.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/in_var.h> #include <netinet/if_ether.h> #include <netinet/ip.h> #include <net80211/ieee80211_var.h> #include <net80211/ieee80211_regdomain.h> #include <net80211/ieee80211_radiotap.h> #include <dev/usb/usb.h> #include <dev/usb/usbdi.h> #include "usbdevs.h" #define USB_DEBUG_VAR rsu_debug #include <dev/usb/usb_debug.h> #include <dev/usb/wlan/if_rsureg.h> #ifdef USB_DEBUG static int rsu_debug = 0; SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu"); SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0, "Debug level"); #define RSU_DPRINTF(_sc, _flg, ...) \ do \ if (((_flg) == (RSU_DEBUG_ANY)) || (rsu_debug & (_flg))) \ device_printf((_sc)->sc_dev, __VA_ARGS__); \ while (0) #else #define RSU_DPRINTF(_sc, _flg, ...) #endif static int rsu_enable_11n = 1; TUNABLE_INT("hw.usb.rsu.enable_11n", &rsu_enable_11n); #define RSU_DEBUG_ANY 0xffffffff #define RSU_DEBUG_TX 0x00000001 #define RSU_DEBUG_RX 0x00000002 #define RSU_DEBUG_RESET 0x00000004 #define RSU_DEBUG_CALIB 0x00000008 #define RSU_DEBUG_STATE 0x00000010 #define RSU_DEBUG_SCAN 0x00000020 #define RSU_DEBUG_FWCMD 0x00000040 #define RSU_DEBUG_TXDONE 0x00000080 #define RSU_DEBUG_FW 0x00000100 #define RSU_DEBUG_FWDBG 0x00000200 #define RSU_DEBUG_AMPDU 0x00000400 static const STRUCT_USB_HOST_ID rsu_devs[] = { #define RSU_HT_NOT_SUPPORTED 0 #define RSU_HT_SUPPORTED 1 #define RSU_DEV_HT(v,p) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \ RSU_HT_SUPPORTED) } #define RSU_DEV(v,p) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \ RSU_HT_NOT_SUPPORTED) } RSU_DEV(ASUS, RTL8192SU), RSU_DEV(AZUREWAVE, RTL8192SU_4), RSU_DEV_HT(ACCTON, RTL8192SU), RSU_DEV_HT(ASUS, USBN10), RSU_DEV_HT(AZUREWAVE, RTL8192SU_1), RSU_DEV_HT(AZUREWAVE, RTL8192SU_2), RSU_DEV_HT(AZUREWAVE, RTL8192SU_3), RSU_DEV_HT(AZUREWAVE, RTL8192SU_5), RSU_DEV_HT(BELKIN, RTL8192SU_1), RSU_DEV_HT(BELKIN, RTL8192SU_2), RSU_DEV_HT(BELKIN, RTL8192SU_3), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_1), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_2), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_3), RSU_DEV_HT(COREGA, RTL8192SU), RSU_DEV_HT(DLINK2, DWA131A1), RSU_DEV_HT(DLINK2, RTL8192SU_1), RSU_DEV_HT(DLINK2, RTL8192SU_2), RSU_DEV_HT(EDIMAX, RTL8192SU_1), RSU_DEV_HT(EDIMAX, RTL8192SU_2), RSU_DEV_HT(EDIMAX, EW7622UMN), RSU_DEV_HT(GUILLEMOT, HWGUN54), RSU_DEV_HT(GUILLEMOT, HWNUM300), RSU_DEV_HT(HAWKING, RTL8192SU_1), RSU_DEV_HT(HAWKING, RTL8192SU_2), RSU_DEV_HT(PLANEX2, GWUSNANO), RSU_DEV_HT(REALTEK, RTL8171), RSU_DEV_HT(REALTEK, RTL8172), RSU_DEV_HT(REALTEK, RTL8173), RSU_DEV_HT(REALTEK, RTL8174), RSU_DEV_HT(REALTEK, RTL8192SU), RSU_DEV_HT(REALTEK, RTL8712), RSU_DEV_HT(REALTEK, RTL8713), RSU_DEV_HT(SENAO, RTL8192SU_1), RSU_DEV_HT(SENAO, RTL8192SU_2), RSU_DEV_HT(SITECOMEU, WL349V1), RSU_DEV_HT(SITECOMEU, WL353), RSU_DEV_HT(SWEEX2, LW154), RSU_DEV_HT(TRENDNET, TEW646UBH), #undef RSU_DEV_HT #undef RSU_DEV }; static device_probe_t rsu_match; static device_attach_t rsu_attach; static device_detach_t rsu_detach; static usb_callback_t rsu_bulk_tx_callback_be_bk; static usb_callback_t rsu_bulk_tx_callback_vi_vo; static usb_callback_t rsu_bulk_tx_callback_h2c; static usb_callback_t rsu_bulk_rx_callback; static usb_error_t rsu_do_request(struct rsu_softc *, struct usb_device_request *, void *); static struct ieee80211vap * rsu_vap_create(struct ieee80211com *, const char name[], int, enum ieee80211_opmode, int, const uint8_t bssid[], const uint8_t mac[]); static void rsu_vap_delete(struct ieee80211vap *); static void rsu_scan_start(struct ieee80211com *); static void rsu_scan_end(struct ieee80211com *); static void rsu_set_channel(struct ieee80211com *); static void rsu_update_mcast(struct ieee80211com *); static int rsu_alloc_rx_list(struct rsu_softc *); static void rsu_free_rx_list(struct rsu_softc *); static int rsu_alloc_tx_list(struct rsu_softc *); static void rsu_free_tx_list(struct rsu_softc *); static void rsu_free_list(struct rsu_softc *, struct rsu_data [], int); static struct rsu_data *_rsu_getbuf(struct rsu_softc *); static struct rsu_data *rsu_getbuf(struct rsu_softc *); static void rsu_freebuf(struct rsu_softc *, struct rsu_data *); static int rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *, int); static void rsu_write_1(struct rsu_softc *, uint16_t, uint8_t); static void rsu_write_2(struct rsu_softc *, uint16_t, uint16_t); static void rsu_write_4(struct rsu_softc *, uint16_t, uint32_t); static int rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *, int); static uint8_t rsu_read_1(struct rsu_softc *, uint16_t); static uint16_t rsu_read_2(struct rsu_softc *, uint16_t); static uint32_t rsu_read_4(struct rsu_softc *, uint16_t); static int rsu_fw_iocmd(struct rsu_softc *, uint32_t); static uint8_t rsu_efuse_read_1(struct rsu_softc *, uint16_t); static int rsu_read_rom(struct rsu_softc *); static int rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int); static void rsu_calib_task(void *, int); static void rsu_tx_task(void *, int); static int rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int); #ifdef notyet static void rsu_set_key(struct rsu_softc *, const struct ieee80211_key *); static void rsu_delete_key(struct rsu_softc *, const struct ieee80211_key *); #endif static int rsu_site_survey(struct rsu_softc *, struct ieee80211vap *); static int rsu_join_bss(struct rsu_softc *, struct ieee80211_node *); static int rsu_disconnect(struct rsu_softc *); static int rsu_hwrssi_to_rssi(struct rsu_softc *, int hw_rssi); static void rsu_event_survey(struct rsu_softc *, uint8_t *, int); static void rsu_event_join_bss(struct rsu_softc *, uint8_t *, int); static void rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int); static void rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int); #if 0 static int8_t rsu_get_rssi(struct rsu_softc *, int, void *); #endif static struct mbuf * rsu_rx_frame(struct rsu_softc *, uint8_t *, int); static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int); static struct mbuf * rsu_rxeof(struct usb_xfer *, struct rsu_data *); static void rsu_txeof(struct usb_xfer *, struct rsu_data *); static int rsu_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void rsu_init(struct rsu_softc *); static int rsu_tx_start(struct rsu_softc *, struct ieee80211_node *, struct mbuf *, struct rsu_data *); static int rsu_transmit(struct ieee80211com *, struct mbuf *); static void rsu_start(struct rsu_softc *); static void _rsu_start(struct rsu_softc *); static void rsu_parent(struct ieee80211com *); static void rsu_stop(struct rsu_softc *); static void rsu_ms_delay(struct rsu_softc *, int); static device_method_t rsu_methods[] = { DEVMETHOD(device_probe, rsu_match), DEVMETHOD(device_attach, rsu_attach), DEVMETHOD(device_detach, rsu_detach), DEVMETHOD_END }; static driver_t rsu_driver = { .name = "rsu", .methods = rsu_methods, .size = sizeof(struct rsu_softc) }; static devclass_t rsu_devclass; DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0); MODULE_DEPEND(rsu, wlan, 1, 1, 1); MODULE_DEPEND(rsu, usb, 1, 1, 1); MODULE_DEPEND(rsu, firmware, 1, 1, 1); MODULE_VERSION(rsu, 1); USB_PNP_HOST_INFO(rsu_devs); static uint8_t rsu_wme_ac_xfer_map[4] = { [WME_AC_BE] = RSU_BULK_TX_BE_BK, [WME_AC_BK] = RSU_BULK_TX_BE_BK, [WME_AC_VI] = RSU_BULK_TX_VI_VO, [WME_AC_VO] = RSU_BULK_TX_VI_VO, }; /* XXX hard-coded */ #define RSU_H2C_ENDPOINT 3 static const struct usb_config rsu_config[RSU_N_TRANSFER] = { [RSU_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = RSU_RXBUFSZ, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .callback = rsu_bulk_rx_callback }, [RSU_BULK_TX_BE_BK] = { .type = UE_BULK, .endpoint = 0x06, .direction = UE_DIR_OUT, .bufsize = RSU_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = rsu_bulk_tx_callback_be_bk, .timeout = RSU_TX_TIMEOUT }, [RSU_BULK_TX_VI_VO] = { .type = UE_BULK, .endpoint = 0x04, .direction = UE_DIR_OUT, .bufsize = RSU_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = rsu_bulk_tx_callback_vi_vo, .timeout = RSU_TX_TIMEOUT }, [RSU_BULK_TX_H2C] = { .type = UE_BULK, .endpoint = 0x0d, .direction = UE_DIR_OUT, .bufsize = RSU_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .short_xfer_ok = 1 }, .callback = rsu_bulk_tx_callback_h2c, .timeout = RSU_TX_TIMEOUT }, }; static int rsu_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST || uaa->info.bIfaceIndex != 0 || uaa->info.bConfigIndex != 0) return (ENXIO); return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa)); } static int rsu_send_mgmt(struct ieee80211_node *ni, int type, int arg) { return (ENOTSUP); } static void rsu_update_chw(struct ieee80211com *ic) { } /* * notification from net80211 that it'd like to do A-MPDU on the given TID. * * Note: this actually hangs traffic at the present moment, so don't use it. * The firmware debug does indiciate it's sending and establishing a TX AMPDU * session, but then no traffic flows. */ static int rsu_ampdu_enable(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap) { #if 0 struct rsu_softc *sc = ni->ni_ic->ic_softc; struct r92s_add_ba_req req; /* Don't enable if it's requested or running */ if (IEEE80211_AMPDU_REQUESTED(tap)) return (0); if (IEEE80211_AMPDU_RUNNING(tap)) return (0); /* We've decided to send addba; so send it */ req.tid = htole32(tap->txa_tid); /* Attempt net80211 state */ if (ieee80211_ampdu_tx_request_ext(ni, tap->txa_tid) != 1) return (0); /* Send the firmware command */ RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: establishing AMPDU TX for TID %d\n", __func__, tap->txa_tid); RSU_LOCK(sc); if (rsu_fw_cmd(sc, R92S_CMD_ADDBA_REQ, &req, sizeof(req)) != 1) { RSU_UNLOCK(sc); /* Mark failure */ (void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 0); return (0); } RSU_UNLOCK(sc); /* Mark success; we don't get any further notifications */ (void) ieee80211_ampdu_tx_request_active_ext(ni, tap->txa_tid, 1); #endif /* Return 0, we're driving this ourselves */ return (0); } static int rsu_wme_update(struct ieee80211com *ic) { /* Firmware handles this; not our problem */ return (0); } static int rsu_attach(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); struct rsu_softc *sc = device_get_softc(self); struct ieee80211com *ic = &sc->sc_ic; int error; uint8_t bands[IEEE80211_MODE_BYTES]; uint8_t iface_index; struct usb_interface *iface; const char *rft; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; if (rsu_enable_11n) sc->sc_ht = !! (USB_GET_DRIVER_INFO(uaa) & RSU_HT_SUPPORTED); /* Get number of endpoints */ iface = usbd_get_iface(sc->sc_udev, 0); sc->sc_nendpoints = iface->idesc->bNumEndpoints; /* Endpoints are hard-coded for now, so enforce 4-endpoint only */ if (sc->sc_nendpoints != 4) { device_printf(sc->sc_dev, "the driver currently only supports 4-endpoint devices\n"); return (ENXIO); } mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK, MTX_DEF); TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0, rsu_calib_task, sc); TASK_INIT(&sc->tx_task, 0, rsu_tx_task, sc); mbufq_init(&sc->sc_snd, ifqmaxlen); /* Allocate Tx/Rx buffers. */ error = rsu_alloc_rx_list(sc); if (error != 0) { device_printf(sc->sc_dev, "could not allocate Rx buffers\n"); goto fail_usb; } error = rsu_alloc_tx_list(sc); if (error != 0) { device_printf(sc->sc_dev, "could not allocate Tx buffers\n"); rsu_free_rx_list(sc); goto fail_usb; } iface_index = 0; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "could not allocate USB transfers, err=%s\n", usbd_errstr(error)); goto fail_usb; } RSU_LOCK(sc); /* Read chip revision. */ sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT); if (sc->cut != 3) sc->cut = (sc->cut >> 1) + 1; error = rsu_read_rom(sc); RSU_UNLOCK(sc); if (error != 0) { device_printf(self, "could not read ROM\n"); goto fail_rom; } /* Figure out TX/RX streams */ switch (sc->rom[84]) { case 0x0: sc->sc_rftype = RTL8712_RFCONFIG_1T1R; sc->sc_nrxstream = 1; sc->sc_ntxstream = 1; rft = "1T1R"; break; case 0x1: sc->sc_rftype = RTL8712_RFCONFIG_1T2R; sc->sc_nrxstream = 2; sc->sc_ntxstream = 1; rft = "1T2R"; break; case 0x2: sc->sc_rftype = RTL8712_RFCONFIG_2T2R; sc->sc_nrxstream = 2; sc->sc_ntxstream = 2; rft = "2T2R"; break; default: device_printf(sc->sc_dev, "%s: unknown board type (rfconfig=0x%02x)\n", __func__, sc->rom[84]); goto fail_rom; } IEEE80211_ADDR_COPY(ic->ic_macaddr, &sc->rom[0x12]); device_printf(self, "MAC/BB RTL8712 cut %d %s\n", sc->cut, rft); ic->ic_softc = sc; ic->ic_name = device_get_nameunit(self); ic->ic_phytype = IEEE80211_T_OFDM; /* Not only, but not used. */ ic->ic_opmode = IEEE80211_M_STA; /* Default to BSS mode. */ /* Set device capabilities. */ ic->ic_caps = IEEE80211_C_STA | /* station mode */ #if 0 IEEE80211_C_BGSCAN | /* Background scan. */ #endif IEEE80211_C_SHPREAMBLE | /* Short preamble supported. */ IEEE80211_C_WME | /* WME/QoS */ IEEE80211_C_SHSLOT | /* Short slot time supported. */ IEEE80211_C_WPA; /* WPA/RSN. */ /* Check if HT support is present. */ if (sc->sc_ht) { device_printf(sc->sc_dev, "%s: enabling 11n\n", __func__); /* Enable basic HT */ ic->ic_htcaps = IEEE80211_HTC_HT | #if 0 IEEE80211_HTC_AMPDU | #endif IEEE80211_HTC_AMSDU | IEEE80211_HTCAP_MAXAMSDU_3839 | IEEE80211_HTCAP_SMPS_OFF; ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40; /* set number of spatial streams */ ic->ic_txstream = sc->sc_ntxstream; ic->ic_rxstream = sc->sc_nrxstream; } /* Set supported .11b and .11g rates. */ memset(bands, 0, sizeof(bands)); setbit(bands, IEEE80211_MODE_11B); setbit(bands, IEEE80211_MODE_11G); if (sc->sc_ht) setbit(bands, IEEE80211_MODE_11NG); ieee80211_init_channels(ic, NULL, bands); ieee80211_ifattach(ic); ic->ic_raw_xmit = rsu_raw_xmit; ic->ic_scan_start = rsu_scan_start; ic->ic_scan_end = rsu_scan_end; ic->ic_set_channel = rsu_set_channel; ic->ic_vap_create = rsu_vap_create; ic->ic_vap_delete = rsu_vap_delete; ic->ic_update_mcast = rsu_update_mcast; ic->ic_parent = rsu_parent; ic->ic_transmit = rsu_transmit; ic->ic_send_mgmt = rsu_send_mgmt; ic->ic_update_chw = rsu_update_chw; ic->ic_ampdu_enable = rsu_ampdu_enable; ic->ic_wme.wme_update = rsu_wme_update; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), RSU_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); fail_rom: usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER); fail_usb: mtx_destroy(&sc->sc_mtx); return (ENXIO); } static int rsu_detach(device_t self) { struct rsu_softc *sc = device_get_softc(self); struct ieee80211com *ic = &sc->sc_ic; RSU_LOCK(sc); rsu_stop(sc); RSU_UNLOCK(sc); usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER); /* * Free buffers /before/ we detach from net80211, else node * references to destroyed vaps will lead to a panic. */ /* Free Tx/Rx buffers. */ RSU_LOCK(sc); rsu_free_tx_list(sc); rsu_free_rx_list(sc); RSU_UNLOCK(sc); /* Frames are freed; detach from net80211 */ ieee80211_ifdetach(ic); taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task); taskqueue_drain(taskqueue_thread, &sc->tx_task); mtx_destroy(&sc->sc_mtx); return (0); } static usb_error_t rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; RSU_ASSERT_LOCKED(sc); while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0 || err == USB_ERR_NOT_CONFIGURED) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); rsu_ms_delay(sc, 10); } return (err); } static struct ieee80211vap * rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct rsu_vap *uvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return (NULL); uvp = malloc(sizeof(struct rsu_vap), M_80211_VAP, M_WAITOK | M_ZERO); vap = &uvp->vap; if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid) != 0) { /* out of memory */ free(uvp, M_80211_VAP); return (NULL); } /* override state transition machine */ uvp->newstate = vap->iv_newstate; vap->iv_newstate = rsu_newstate; /* Limits from the r92su driver */ vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16; vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_32K; /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status, mac); ic->ic_opmode = opmode; return (vap); } static void rsu_vap_delete(struct ieee80211vap *vap) { struct rsu_vap *uvp = RSU_VAP(vap); ieee80211_vap_detach(vap); free(uvp, M_80211_VAP); } static void rsu_scan_start(struct ieee80211com *ic) { struct rsu_softc *sc = ic->ic_softc; int error; /* Scanning is done by the firmware. */ RSU_LOCK(sc); /* XXX TODO: force awake if in in network-sleep? */ error = rsu_site_survey(sc, TAILQ_FIRST(&ic->ic_vaps)); RSU_UNLOCK(sc); if (error != 0) device_printf(sc->sc_dev, "could not send site survey command\n"); } static void rsu_scan_end(struct ieee80211com *ic) { /* Nothing to do here. */ } static void rsu_set_channel(struct ieee80211com *ic __unused) { /* We are unable to switch channels, yet. */ } static void rsu_update_mcast(struct ieee80211com *ic) { /* XXX do nothing? */ } static int rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[], int ndata, int maxsz) { int i, error; for (i = 0; i < ndata; i++) { struct rsu_data *dp = &data[i]; dp->sc = sc; dp->m = NULL; dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT); if (dp->buf == NULL) { device_printf(sc->sc_dev, "could not allocate buffer\n"); error = ENOMEM; goto fail; } dp->ni = NULL; } return (0); fail: rsu_free_list(sc, data, ndata); return (error); } static int rsu_alloc_rx_list(struct rsu_softc *sc) { int error, i; error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT, RSU_RXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_rx_active); STAILQ_INIT(&sc->sc_rx_inactive); for (i = 0; i < RSU_RX_LIST_COUNT; i++) STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next); return (0); } static int rsu_alloc_tx_list(struct rsu_softc *sc) { int error, i; error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT, RSU_TXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_tx_inactive); for (i = 0; i != RSU_N_TRANSFER; i++) { STAILQ_INIT(&sc->sc_tx_active[i]); STAILQ_INIT(&sc->sc_tx_pending[i]); } for (i = 0; i < RSU_TX_LIST_COUNT; i++) { STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next); } return (0); } static void rsu_free_tx_list(struct rsu_softc *sc) { int i; /* prevent further allocations from TX list(s) */ STAILQ_INIT(&sc->sc_tx_inactive); for (i = 0; i != RSU_N_TRANSFER; i++) { STAILQ_INIT(&sc->sc_tx_active[i]); STAILQ_INIT(&sc->sc_tx_pending[i]); } rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT); } static void rsu_free_rx_list(struct rsu_softc *sc) { /* prevent further allocations from RX list(s) */ STAILQ_INIT(&sc->sc_rx_inactive); STAILQ_INIT(&sc->sc_rx_active); rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT); } static void rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata) { int i; for (i = 0; i < ndata; i++) { struct rsu_data *dp = &data[i]; if (dp->buf != NULL) { free(dp->buf, M_USBDEV); dp->buf = NULL; } if (dp->ni != NULL) { ieee80211_free_node(dp->ni); dp->ni = NULL; } } } static struct rsu_data * _rsu_getbuf(struct rsu_softc *sc) { struct rsu_data *bf; bf = STAILQ_FIRST(&sc->sc_tx_inactive); if (bf != NULL) STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next); else bf = NULL; return (bf); } static struct rsu_data * rsu_getbuf(struct rsu_softc *sc) { struct rsu_data *bf; RSU_ASSERT_LOCKED(sc); bf = _rsu_getbuf(sc); if (bf == NULL) { RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: no buffers\n", __func__); } return (bf); } static void rsu_freebuf(struct rsu_softc *sc, struct rsu_data *bf) { RSU_ASSERT_LOCKED(sc); STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next); } static int rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = R92S_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (rsu_do_request(sc, &req, buf)); } static void rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val) { rsu_write_region_1(sc, addr, &val, 1); } static void rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val) { val = htole16(val); rsu_write_region_1(sc, addr, (uint8_t *)&val, 2); } static void rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val) { val = htole32(val); rsu_write_region_1(sc, addr, (uint8_t *)&val, 4); } static int rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = R92S_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (rsu_do_request(sc, &req, buf)); } static uint8_t rsu_read_1(struct rsu_softc *sc, uint16_t addr) { uint8_t val; if (rsu_read_region_1(sc, addr, &val, 1) != 0) return (0xff); return (val); } static uint16_t rsu_read_2(struct rsu_softc *sc, uint16_t addr) { uint16_t val; if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0) return (0xffff); return (le16toh(val)); } static uint32_t rsu_read_4(struct rsu_softc *sc, uint16_t addr) { uint32_t val; if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0) return (0xffffffff); return (le32toh(val)); } static int rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd) { int ntries; rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd); rsu_ms_delay(sc, 1); for (ntries = 0; ntries < 50; ntries++) { if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0) return (0); rsu_ms_delay(sc, 1); } return (ETIMEDOUT); } static uint8_t rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr) { uint32_t reg; int ntries; reg = rsu_read_4(sc, R92S_EFUSE_CTRL); reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr); reg &= ~R92S_EFUSE_CTRL_VALID; rsu_write_4(sc, R92S_EFUSE_CTRL, reg); /* Wait for read operation to complete. */ for (ntries = 0; ntries < 100; ntries++) { reg = rsu_read_4(sc, R92S_EFUSE_CTRL); if (reg & R92S_EFUSE_CTRL_VALID) return (MS(reg, R92S_EFUSE_CTRL_DATA)); rsu_ms_delay(sc, 1); } device_printf(sc->sc_dev, "could not read efuse byte at address 0x%x\n", addr); return (0xff); } static int rsu_read_rom(struct rsu_softc *sc) { uint8_t *rom = sc->rom; uint16_t addr = 0; uint32_t reg; uint8_t off, msk; int i; /* Make sure that ROM type is eFuse and that autoload succeeded. */ reg = rsu_read_1(sc, R92S_EE_9346CR); if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN) return (EIO); /* Turn on 2.5V to prevent eFuse leakage. */ reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3); rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80); rsu_ms_delay(sc, 1); rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80); /* Read full ROM image. */ memset(&sc->rom, 0xff, sizeof(sc->rom)); while (addr < 512) { reg = rsu_efuse_read_1(sc, addr); if (reg == 0xff) break; addr++; off = reg >> 4; msk = reg & 0xf; for (i = 0; i < 4; i++) { if (msk & (1 << i)) continue; rom[off * 8 + i * 2 + 0] = rsu_efuse_read_1(sc, addr); addr++; rom[off * 8 + i * 2 + 1] = rsu_efuse_read_1(sc, addr); addr++; } } #ifdef USB_DEBUG if (rsu_debug >= 5) { /* Dump ROM content. */ printf("\n"); for (i = 0; i < sizeof(sc->rom); i++) printf("%02x:", rom[i]); printf("\n"); } #endif return (0); } static int rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len) { const uint8_t which = RSU_H2C_ENDPOINT; struct rsu_data *data; struct r92s_tx_desc *txd; struct r92s_fw_cmd_hdr *cmd; int cmdsz; int xferlen; RSU_ASSERT_LOCKED(sc); data = rsu_getbuf(sc); if (data == NULL) return (ENOMEM); /* Blank the entire payload, just to be safe */ memset(data->buf, '\0', RSU_TXBUFSZ); /* Round-up command length to a multiple of 8 bytes. */ /* XXX TODO: is this required? */ cmdsz = (len + 7) & ~7; xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz; KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__)); memset(data->buf, 0, xferlen); /* Setup Tx descriptor. */ txd = (struct r92s_tx_desc *)data->buf; txd->txdw0 = htole32( SM(R92S_TXDW0_OFFSET, sizeof(*txd)) | SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) | R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG); txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C)); /* Setup command header. */ cmd = (struct r92s_fw_cmd_hdr *)&txd[1]; cmd->len = htole16(cmdsz); cmd->code = code; cmd->seq = sc->cmd_seq; sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f; /* Copy command payload. */ memcpy(&cmd[1], buf, len); RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FWCMD, "%s: Tx cmd code=0x%x len=0x%x\n", __func__, code, cmdsz); data->buflen = xferlen; STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); usbd_transfer_start(sc->sc_xfer[which]); return (0); } /* ARGSUSED */ static void rsu_calib_task(void *arg, int pending __unused) { struct rsu_softc *sc = arg; #ifdef notyet uint32_t reg; #endif RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: running calibration task\n", __func__); RSU_LOCK(sc); #ifdef notyet /* Read WPS PBC status. */ rsu_write_1(sc, R92S_MAC_PINMUX_CTRL, R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG)); rsu_write_1(sc, R92S_GPIO_IO_SEL, rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS); reg = rsu_read_1(sc, R92S_GPIO_CTRL); if (reg != 0xff && (reg & R92S_GPIO_WPS)) DPRINTF(("WPS PBC is pushed\n")); #endif /* Read current signal level. */ if (rsu_fw_iocmd(sc, 0xf4000001) == 0) { sc->sc_currssi = rsu_read_4(sc, R92S_IOCMD_DATA); RSU_DPRINTF(sc, RSU_DEBUG_CALIB, "%s: RSSI=%d (%d)\n", __func__, sc->sc_currssi, rsu_hwrssi_to_rssi(sc, sc->sc_currssi)); } if (sc->sc_calibrating) taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz); RSU_UNLOCK(sc); } static void rsu_tx_task(void *arg, int pending __unused) { struct rsu_softc *sc = arg; RSU_LOCK(sc); _rsu_start(sc); RSU_UNLOCK(sc); } #define RSU_PWR_UNKNOWN 0x0 #define RSU_PWR_ACTIVE 0x1 #define RSU_PWR_OFF 0x2 #define RSU_PWR_SLEEP 0x3 /* * Set the current power state. * * The rtlwifi code doesn't do this so aggressively; it * waits for an idle period after association with * no traffic before doing this. * * For now - it's on in all states except RUN, and * in RUN it'll transition to allow sleep. */ struct r92s_pwr_cmd { uint8_t mode; uint8_t smart_ps; uint8_t bcn_pass_time; }; static int rsu_set_fw_power_state(struct rsu_softc *sc, int state) { struct r92s_set_pwr_mode cmd; //struct r92s_pwr_cmd cmd; int error; RSU_ASSERT_LOCKED(sc); /* only change state if required */ if (sc->sc_curpwrstate == state) return (0); memset(&cmd, 0, sizeof(cmd)); switch (state) { case RSU_PWR_ACTIVE: /* Force the hardware awake */ rsu_write_1(sc, R92S_USB_HRPWM, R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON); cmd.mode = R92S_PS_MODE_ACTIVE; break; case RSU_PWR_SLEEP: cmd.mode = R92S_PS_MODE_DTIM; /* XXX configurable? */ cmd.smart_ps = 1; /* XXX 2 if doing p2p */ cmd.bcn_pass_time = 5; /* in 100mS usb.c, linux/rtlwifi */ break; case RSU_PWR_OFF: cmd.mode = R92S_PS_MODE_RADIOOFF; break; default: device_printf(sc->sc_dev, "%s: unknown ps mode (%d)\n", __func__, state); return (ENXIO); } RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting ps mode to %d (mode %d)\n", __func__, state, cmd.mode); error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd)); if (error == 0) sc->sc_curpwrstate = state; return (error); } static int rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct rsu_vap *uvp = RSU_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct rsu_softc *sc = ic->ic_softc; struct ieee80211_node *ni; struct ieee80211_rateset *rs; enum ieee80211_state ostate; int error, startcal = 0; ostate = vap->iv_state; RSU_DPRINTF(sc, RSU_DEBUG_STATE, "%s: %s -> %s\n", __func__, ieee80211_state_name[ostate], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); if (ostate == IEEE80211_S_RUN) { RSU_LOCK(sc); /* Stop calibration. */ sc->sc_calibrating = 0; RSU_UNLOCK(sc); taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task); taskqueue_drain(taskqueue_thread, &sc->tx_task); /* Disassociate from our current BSS. */ RSU_LOCK(sc); rsu_disconnect(sc); } else RSU_LOCK(sc); switch (nstate) { case IEEE80211_S_INIT: (void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE); break; case IEEE80211_S_AUTH: ni = ieee80211_ref_node(vap->iv_bss); (void) rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE); error = rsu_join_bss(sc, ni); ieee80211_free_node(ni); if (error != 0) { device_printf(sc->sc_dev, "could not send join command\n"); } break; case IEEE80211_S_RUN: ni = ieee80211_ref_node(vap->iv_bss); rs = &ni->ni_rates; /* Indicate highest supported rate. */ ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1]; (void) rsu_set_fw_power_state(sc, RSU_PWR_SLEEP); ieee80211_free_node(ni); startcal = 1; break; default: break; } sc->sc_calibrating = 1; /* Start periodic calibration. */ taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz); RSU_UNLOCK(sc); IEEE80211_LOCK(ic); return (uvp->newstate(vap, nstate, arg)); } #ifdef notyet static void rsu_set_key(struct rsu_softc *sc, const struct ieee80211_key *k) { struct r92s_fw_cmd_set_key key; memset(&key, 0, sizeof(key)); /* Map net80211 cipher to HW crypto algorithm. */ switch (k->wk_cipher->ic_cipher) { case IEEE80211_CIPHER_WEP: if (k->wk_keylen < 8) key.algo = R92S_KEY_ALGO_WEP40; else key.algo = R92S_KEY_ALGO_WEP104; break; case IEEE80211_CIPHER_TKIP: key.algo = R92S_KEY_ALGO_TKIP; break; case IEEE80211_CIPHER_AES_CCM: key.algo = R92S_KEY_ALGO_AES; break; default: return; } key.id = k->wk_keyix; key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0; memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key))); (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key)); } static void rsu_delete_key(struct rsu_softc *sc, const struct ieee80211_key *k) { struct r92s_fw_cmd_set_key key; memset(&key, 0, sizeof(key)); key.id = k->wk_keyix; (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key)); } #endif static int rsu_site_survey(struct rsu_softc *sc, struct ieee80211vap *vap) { struct r92s_fw_cmd_sitesurvey cmd; struct ieee80211com *ic = &sc->sc_ic; int r; RSU_ASSERT_LOCKED(sc); memset(&cmd, 0, sizeof(cmd)); if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->sc_scan_pass == 1) cmd.active = htole32(1); cmd.limit = htole32(48); if (sc->sc_scan_pass == 1 && vap->iv_des_nssid > 0) { /* Do a directed scan for second pass. */ cmd.ssidlen = htole32(vap->iv_des_ssid[0].len); memcpy(cmd.ssid, vap->iv_des_ssid[0].ssid, vap->iv_des_ssid[0].len); } DPRINTF("sending site survey command, pass=%d\n", sc->sc_scan_pass); r = rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd)); if (r == 0) { sc->sc_scanning = 1; } return (r); } static int rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = ni->ni_vap; struct ndis_wlan_bssid_ex *bss; struct ndis_802_11_fixed_ies *fixed; struct r92s_fw_cmd_auth auth; uint8_t buf[sizeof(*bss) + 128] __aligned(4); uint8_t *frm; uint8_t opmode; int error; int cnt; char *msg = "rsujoin"; RSU_ASSERT_LOCKED(sc); /* * Until net80211 scanning doesn't automatically finish * before we tell it to, let's just wait until any pending * scan is done. * * XXX TODO: yes, this releases and re-acquires the lock. * We should re-verify the state whenever we re-attempt this! */ cnt = 0; while (sc->sc_scanning && cnt < 10) { device_printf(sc->sc_dev, "%s: still scanning! (attempt %d)\n", __func__, cnt); msleep(msg, &sc->sc_mtx, 0, msg, hz / 2); cnt++; } /* Let the FW decide the opmode based on the capinfo field. */ opmode = NDIS802_11AUTOUNKNOWN; RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting operating mode to %d\n", __func__, opmode); error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode)); if (error != 0) return (error); memset(&auth, 0, sizeof(auth)); if (vap->iv_flags & IEEE80211_F_WPA) { auth.mode = R92S_AUTHMODE_WPA; auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X); } else auth.mode = R92S_AUTHMODE_OPEN; RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting auth mode to %d\n", __func__, auth.mode); error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth)); if (error != 0) return (error); memset(buf, 0, sizeof(buf)); bss = (struct ndis_wlan_bssid_ex *)buf; IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid); bss->ssid.ssidlen = htole32(ni->ni_esslen); memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen); if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA)) bss->privacy = htole32(1); bss->rssi = htole32(ni->ni_avgrssi); if (ic->ic_curmode == IEEE80211_MODE_11B) bss->networktype = htole32(NDIS802_11DS); else bss->networktype = htole32(NDIS802_11OFDM24); bss->config.len = htole32(sizeof(bss->config)); bss->config.bintval = htole32(ni->ni_intval); bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan)); bss->inframode = htole32(NDIS802_11INFRASTRUCTURE); /* XXX verify how this is supposed to look! */ memcpy(bss->supprates, ni->ni_rates.rs_rates, ni->ni_rates.rs_nrates); /* Write the fixed fields of the beacon frame. */ fixed = (struct ndis_802_11_fixed_ies *)&bss[1]; memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8); fixed->bintval = htole16(ni->ni_intval); fixed->capabilities = htole16(ni->ni_capinfo); /* Write IEs to be included in the association request. */ frm = (uint8_t *)&fixed[1]; frm = ieee80211_add_rsn(frm, vap); frm = ieee80211_add_wpa(frm, vap); frm = ieee80211_add_qos(frm, ni); if ((ic->ic_flags & IEEE80211_F_WME) && (ni->ni_ies.wme_ie != NULL)) frm = ieee80211_add_wme_info(frm, &ic->ic_wme); if (ni->ni_flags & IEEE80211_NODE_HT) { frm = ieee80211_add_htcap(frm, ni); frm = ieee80211_add_htinfo(frm, ni); } bss->ieslen = htole32(frm - (uint8_t *)fixed); bss->len = htole32(((frm - buf) + 3) & ~3); RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_FWCMD, "%s: sending join bss command to %s chan %d\n", __func__, ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig)); return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf))); } static int rsu_disconnect(struct rsu_softc *sc) { uint32_t zero = 0; /* :-) */ /* Disassociate from our current BSS. */ RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD, "%s: sending disconnect command\n", __func__); return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero))); } /* * Map the hardware provided RSSI value to a signal level. * For the most part it's just something we divide by and cap * so it doesn't overflow the representation by net80211. */ static int rsu_hwrssi_to_rssi(struct rsu_softc *sc, int hw_rssi) { int v; if (hw_rssi == 0) return (0); v = hw_rssi >> 4; if (v > 80) v = 80; return (v); } static void rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211_frame *wh; struct ndis_wlan_bssid_ex *bss; struct ieee80211_rx_stats rxs; struct mbuf *m; int pktlen; if (__predict_false(len < sizeof(*bss))) return; bss = (struct ndis_wlan_bssid_ex *)buf; if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen))) return; RSU_DPRINTF(sc, RSU_DEBUG_SCAN, "%s: found BSS %s: len=%d chan=%d inframode=%d " "networktype=%d privacy=%d, RSSI=%d\n", __func__, ether_sprintf(bss->macaddr), le32toh(bss->len), le32toh(bss->config.dsconfig), le32toh(bss->inframode), le32toh(bss->networktype), le32toh(bss->privacy), le32toh(bss->rssi)); /* Build a fake beacon frame to let net80211 do all the parsing. */ /* XXX TODO: just call the new scan API methods! */ pktlen = sizeof(*wh) + le32toh(bss->ieslen); if (__predict_false(pktlen > MCLBYTES)) return; m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m == NULL)) return; wh = mtod(m, struct ieee80211_frame *); wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_BEACON; wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; USETW(wh->i_dur, 0); IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr); IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr); IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr); *(uint16_t *)wh->i_seq = 0; memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen)); /* Finalize mbuf. */ m->m_pkthdr.len = m->m_len = pktlen; /* Set channel flags for input path */ bzero(&rxs, sizeof(rxs)); rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ; rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI; rxs.c_ieee = le32toh(bss->config.dsconfig); rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ); /* This is a number from 0..100; so let's just divide it down a bit */ rxs.rssi = le32toh(bss->rssi) / 2; rxs.nf = -96; /* XXX avoid a LOR */ RSU_UNLOCK(sc); ieee80211_input_mimo_all(ic, m, &rxs); RSU_LOCK(sc); } static void rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ieee80211_node *ni = vap->iv_bss; struct r92s_event_join_bss *rsp; uint32_t tmp; int res; if (__predict_false(len < sizeof(*rsp))) return; rsp = (struct r92s_event_join_bss *)buf; res = (int)le32toh(rsp->join_res); RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD, "%s: Rx join BSS event len=%d res=%d\n", __func__, len, res); /* * XXX Don't do this; there's likely a better way to tell * the caller we failed. */ if (res <= 0) { RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); return; } tmp = le32toh(rsp->associd); if (tmp >= vap->iv_max_aid) { DPRINTF("Assoc ID overflow\n"); tmp = 1; } RSU_DPRINTF(sc, RSU_DEBUG_STATE | RSU_DEBUG_FWCMD, "%s: associated with %s associd=%d\n", __func__, ether_sprintf(rsp->bss.macaddr), tmp); /* XXX is this required? What's the top two bits for again? */ ni->ni_associd = tmp | 0xc000; RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_RUN, IEEE80211_FC0_SUBTYPE_ASSOC_RESP); RSU_LOCK(sc); } static void rsu_event_addba_req_report(struct rsu_softc *sc, uint8_t *buf, int len) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct r92s_add_ba_event *ba = (void *) buf; struct ieee80211_node *ni; if (len < sizeof(*ba)) { device_printf(sc->sc_dev, "%s: short read (%d)\n", __func__, len); return; } if (vap == NULL) return; RSU_DPRINTF(sc, RSU_DEBUG_AMPDU, "%s: mac=%s, tid=%d, ssn=%d\n", __func__, ether_sprintf(ba->mac_addr), (int) ba->tid, (int) le16toh(ba->ssn)); /* XXX do node lookup; this is STA specific */ ni = ieee80211_ref_node(vap->iv_bss); ieee80211_ampdu_rx_start_ext(ni, ba->tid, le16toh(ba->ssn) >> 4, 32); ieee80211_free_node(ni); } static void rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD, "%s: Rx event code=%d len=%d\n", __func__, code, len); switch (code) { case R92S_EVT_SURVEY: rsu_event_survey(sc, buf, len); break; case R92S_EVT_SURVEY_DONE: RSU_DPRINTF(sc, RSU_DEBUG_SCAN, "%s: site survey pass %d done, found %d BSS\n", __func__, sc->sc_scan_pass, le32toh(*(uint32_t *)buf)); sc->sc_scanning = 0; if (vap->iv_state != IEEE80211_S_SCAN) break; /* Ignore if not scanning. */ /* * XXX TODO: This needs to be done without a transition to * the SCAN state again. Grr. */ if (sc->sc_scan_pass == 0 && vap->iv_des_nssid != 0) { /* Schedule a directed scan for hidden APs. */ /* XXX bad! */ sc->sc_scan_pass = 1; RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); break; } sc->sc_scan_pass = 0; break; case R92S_EVT_JOIN_BSS: if (vap->iv_state == IEEE80211_S_AUTH) rsu_event_join_bss(sc, buf, len); break; case R92S_EVT_DEL_STA: RSU_DPRINTF(sc, RSU_DEBUG_FWCMD | RSU_DEBUG_STATE, "%s: disassociated from %s\n", __func__, ether_sprintf(buf)); if (vap->iv_state == IEEE80211_S_RUN && IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) { RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); } break; case R92S_EVT_WPS_PBC: RSU_DPRINTF(sc, RSU_DEBUG_RX | RSU_DEBUG_FWCMD, "%s: WPS PBC pushed.\n", __func__); break; case R92S_EVT_FWDBG: buf[60] = '\0'; RSU_DPRINTF(sc, RSU_DEBUG_FWDBG, "FWDBG: %s\n", (char *)buf); break; case R92S_EVT_ADDBA_REQ_REPORT: rsu_event_addba_req_report(sc, buf, len); break; default: device_printf(sc->sc_dev, "%s: unhandled code (%d)\n", __func__, code); break; } } static void rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len) { struct r92s_fw_cmd_hdr *cmd; int cmdsz; RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx events len=%d\n", __func__, len); /* Skip Rx status. */ buf += sizeof(struct r92s_rx_stat); len -= sizeof(struct r92s_rx_stat); /* Process all events. */ for (;;) { /* Check that command header fits. */ if (__predict_false(len < sizeof(*cmd))) break; cmd = (struct r92s_fw_cmd_hdr *)buf; /* Check that command payload fits. */ cmdsz = le16toh(cmd->len); if (__predict_false(len < sizeof(*cmd) + cmdsz)) break; /* Process firmware event. */ rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz); if (!(cmd->seq & R92S_FW_CMD_MORE)) break; buf += sizeof(*cmd) + cmdsz; len -= sizeof(*cmd) + cmdsz; } } #if 0 static int8_t rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt) { static const int8_t cckoff[] = { 14, -2, -20, -40 }; struct r92s_rx_phystat *phy; struct r92s_rx_cck *cck; uint8_t rpt; int8_t rssi; if (rate <= 3) { cck = (struct r92s_rx_cck *)physt; rpt = (cck->agc_rpt >> 6) & 0x3; rssi = cck->agc_rpt & 0x3e; rssi = cckoff[rpt] - rssi; } else { /* OFDM/HT. */ phy = (struct r92s_rx_phystat *)physt; rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106; } return (rssi); } #endif static struct mbuf * rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211_frame *wh; struct r92s_rx_stat *stat; uint32_t rxdw0, rxdw3; struct mbuf *m; uint8_t rate; int infosz; stat = (struct r92s_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); rxdw3 = le32toh(stat->rxdw3); if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) { counter_u64_add(ic->ic_ierrors, 1); return NULL; } if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) { counter_u64_add(ic->ic_ierrors, 1); return NULL; } rate = MS(rxdw3, R92S_RXDW3_RATE); infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8; #if 0 /* Get RSSI from PHY status descriptor if present. */ if (infosz != 0) *rssi = rsu_get_rssi(sc, rate, &stat[1]); else *rssi = 0; #endif RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx frame len=%d rate=%d infosz=%d\n", __func__, pktlen, rate, infosz); m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m == NULL)) { counter_u64_add(ic->ic_ierrors, 1); return NULL; } /* Hardware does Rx TCP checksum offload. */ if (rxdw3 & R92S_RXDW3_TCPCHKVALID) { if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT)) m->m_pkthdr.csum_flags |= CSUM_DATA_VALID; } wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz); memcpy(mtod(m, uint8_t *), wh, pktlen); m->m_pkthdr.len = m->m_len = pktlen; if (ieee80211_radiotap_active(ic)) { struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap; /* Map HW rate index to 802.11 rate. */ tap->wr_flags = 2; if (!(rxdw3 & R92S_RXDW3_HTC)) { switch (rate) { /* CCK. */ case 0: tap->wr_rate = 2; break; case 1: tap->wr_rate = 4; break; case 2: tap->wr_rate = 11; break; case 3: tap->wr_rate = 22; break; /* OFDM. */ case 4: tap->wr_rate = 12; break; case 5: tap->wr_rate = 18; break; case 6: tap->wr_rate = 24; break; case 7: tap->wr_rate = 36; break; case 8: tap->wr_rate = 48; break; case 9: tap->wr_rate = 72; break; case 10: tap->wr_rate = 96; break; case 11: tap->wr_rate = 108; break; } } else if (rate >= 12) { /* MCS0~15. */ /* Bit 7 set means HT MCS instead of rate. */ tap->wr_rate = 0x80 | (rate - 12); } #if 0 tap->wr_dbm_antsignal = *rssi; #endif /* XXX not nice */ tap->wr_dbm_antsignal = rsu_hwrssi_to_rssi(sc, sc->sc_currssi); tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags); } return (m); } static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len) { struct r92s_rx_stat *stat; uint32_t rxdw0; int totlen, pktlen, infosz, npkts; struct mbuf *m, *m0 = NULL, *prevm = NULL; /* Get the number of encapsulated frames. */ stat = (struct r92s_rx_stat *)buf; npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT); RSU_DPRINTF(sc, RSU_DEBUG_RX, "%s: Rx %d frames in one chunk\n", __func__, npkts); /* Process all of them. */ while (npkts-- > 0) { if (__predict_false(len < sizeof(*stat))) break; stat = (struct r92s_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN); if (__predict_false(pktlen == 0)) break; infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8; /* Make sure everything fits in xfer. */ totlen = sizeof(*stat) + infosz + pktlen; if (__predict_false(totlen > len)) break; /* Process 802.11 frame. */ m = rsu_rx_frame(sc, buf, pktlen); if (m0 == NULL) m0 = m; if (prevm == NULL) prevm = m; else { prevm->m_next = m; prevm = m; } /* Next chunk is 128-byte aligned. */ totlen = (totlen + 127) & ~127; buf += totlen; len -= totlen; } return (m0); } static struct mbuf * rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data) { struct rsu_softc *sc = data->sc; struct ieee80211com *ic = &sc->sc_ic; struct r92s_rx_stat *stat; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); if (__predict_false(len < sizeof(*stat))) { DPRINTF("xfer too short %d\n", len); counter_u64_add(ic->ic_ierrors, 1); return (NULL); } /* Determine if it is a firmware C2H event or an 802.11 frame. */ stat = (struct r92s_rx_stat *)data->buf; if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) { rsu_rx_multi_event(sc, data->buf, len); /* No packets to process. */ return (NULL); } else return (rsu_rx_multi_frame(sc, data->buf, len)); } static void rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct rsu_softc *sc = usbd_xfer_softc(xfer); struct ieee80211com *ic = &sc->sc_ic; struct ieee80211_frame *wh; struct ieee80211_node *ni; struct mbuf *m = NULL, *next; struct rsu_data *data; RSU_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_rx_active); if (data == NULL) goto tr_setup; STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); m = rsu_rxeof(xfer, data); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: /* * XXX TODO: if we have an mbuf list, but then * we hit data == NULL, what now? */ data = STAILQ_FIRST(&sc->sc_rx_inactive); if (data == NULL) { KASSERT(m == NULL, ("mbuf isn't NULL")); return; } STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next); STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * To avoid LOR we should unlock our private mutex here to call * ieee80211_input() because here is at the end of a USB * callback and safe to unlock. */ RSU_UNLOCK(sc); while (m != NULL) { int rssi; /* Cheat and get the last calibrated RSSI */ rssi = rsu_hwrssi_to_rssi(sc, sc->sc_currssi); next = m->m_next; m->m_next = NULL; wh = mtod(m, struct ieee80211_frame *); ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh); if (ni != NULL) { if (ni->ni_flags & IEEE80211_NODE_HT) m->m_flags |= M_AMPDU; (void)ieee80211_input(ni, m, rssi, -96); ieee80211_free_node(ni); } else (void)ieee80211_input_all(ic, m, rssi, -96); m = next; } RSU_LOCK(sc); break; default: /* needs it to the inactive queue due to a error. */ data = STAILQ_FIRST(&sc->sc_rx_active); if (data != NULL) { STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); } if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); counter_u64_add(ic->ic_ierrors, 1); goto tr_setup; } break; } } static void rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data) { #ifdef USB_DEBUG struct rsu_softc *sc = usbd_xfer_softc(xfer); #endif RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: called; data=%p\n", __func__, data); if (data->m) { /* XXX status? */ ieee80211_tx_complete(data->ni, data->m, 0); data->m = NULL; data->ni = NULL; } } static void rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error, uint8_t which) { struct rsu_softc *sc = usbd_xfer_softc(xfer); struct ieee80211com *ic = &sc->sc_ic; struct rsu_data *data; RSU_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_tx_active[which]); if (data == NULL) goto tr_setup; RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: transfer done %p\n", __func__, data); STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next); rsu_txeof(xfer, data); rsu_freebuf(sc, data); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->sc_tx_pending[which]); if (data == NULL) { RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: empty pending queue sc %p\n", __func__, sc); return; } STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next); STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen); RSU_DPRINTF(sc, RSU_DEBUG_TXDONE, "%s: submitting transfer %p\n", __func__, data); usbd_transfer_submit(xfer); break; default: data = STAILQ_FIRST(&sc->sc_tx_active[which]); if (data != NULL) { STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next); rsu_txeof(xfer, data); rsu_freebuf(sc, data); } counter_u64_add(ic->ic_oerrors, 1); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } /* * XXX TODO: if the queue is low, flush out FF TX frames. * Remember to unlock the driver for now; net80211 doesn't * defer it for us. */ } static void rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error) { struct rsu_softc *sc = usbd_xfer_softc(xfer); rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK); /* This kicks the TX taskqueue */ rsu_start(sc); } static void rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error) { struct rsu_softc *sc = usbd_xfer_softc(xfer); rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO); /* This kicks the TX taskqueue */ rsu_start(sc); } static void rsu_bulk_tx_callback_h2c(struct usb_xfer *xfer, usb_error_t error) { struct rsu_softc *sc = usbd_xfer_softc(xfer); rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_H2C); /* This kicks the TX taskqueue */ rsu_start(sc); } /* * Transmit the given frame. * * This doesn't free the node or mbuf upon failure. */ static int rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni, struct mbuf *m0, struct rsu_data *data) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211_frame *wh; struct ieee80211_key *k = NULL; struct r92s_tx_desc *txd; uint8_t type; int prio = 0; uint8_t which; int hasqos; int xferlen; int qid; RSU_ASSERT_LOCKED(sc); wh = mtod(m0, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: data=%p, m=%p\n", __func__, data, m0); if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { device_printf(sc->sc_dev, "ieee80211_crypto_encap returns NULL.\n"); /* XXX we don't expect the fragmented frames */ return (ENOBUFS); } wh = mtod(m0, struct ieee80211_frame *); } /* If we have QoS then use it */ /* XXX TODO: mbuf WME/PRI versus TID? */ if (IEEE80211_QOS_HAS_SEQ(wh)) { /* Has QoS */ prio = M_WME_GETAC(m0); which = rsu_wme_ac_xfer_map[prio]; hasqos = 1; } else { /* Non-QoS TID */ /* XXX TODO: tid=0 for non-qos TID? */ which = rsu_wme_ac_xfer_map[WME_AC_BE]; hasqos = 0; prio = 0; } qid = rsu_ac2qid[prio]; #if 0 switch (type) { case IEEE80211_FC0_TYPE_CTL: case IEEE80211_FC0_TYPE_MGT: which = rsu_wme_ac_xfer_map[WME_AC_VO]; break; default: which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)]; break; } hasqos = 0; #endif RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: pri=%d, which=%d, hasqos=%d\n", __func__, prio, which, hasqos); /* Fill Tx descriptor. */ txd = (struct r92s_tx_desc *)data->buf; memset(txd, 0, sizeof(*txd)); txd->txdw0 |= htole32( SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) | SM(R92S_TXDW0_OFFSET, sizeof(*txd)) | R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG); txd->txdw1 |= htole32( SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, qid)); if (!hasqos) txd->txdw1 |= htole32(R92S_TXDW1_NONQOS); #ifdef notyet if (k != NULL) { switch (k->wk_cipher->ic_cipher) { case IEEE80211_CIPHER_WEP: cipher = R92S_TXDW1_CIPHER_WEP; break; case IEEE80211_CIPHER_TKIP: cipher = R92S_TXDW1_CIPHER_TKIP; break; case IEEE80211_CIPHER_AES_CCM: cipher = R92S_TXDW1_CIPHER_AES; break; default: cipher = R92S_TXDW1_CIPHER_NONE; } txd->txdw1 |= htole32( SM(R92S_TXDW1_CIPHER, cipher) | SM(R92S_TXDW1_KEYIDX, k->k_id)); } #endif /* XXX todo: set AGGEN bit if appropriate? */ txd->txdw2 |= htole32(R92S_TXDW2_BK); if (IEEE80211_IS_MULTICAST(wh->i_addr1)) txd->txdw2 |= htole32(R92S_TXDW2_BMCAST); /* * Firmware will use and increment the sequence number for the * specified priority. */ txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, prio)); if (ieee80211_radiotap_active_vap(vap)) { struct rsu_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags); ieee80211_radiotap_tx(vap, m0); } xferlen = sizeof(*txd) + m0->m_pkthdr.len; m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]); data->buflen = xferlen; data->ni = ni; data->m = m0; STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); /* start transfer, if any */ usbd_transfer_start(sc->sc_xfer[which]); return (0); } static int rsu_transmit(struct ieee80211com *ic, struct mbuf *m) { struct rsu_softc *sc = ic->ic_softc; int error; RSU_LOCK(sc); if (!sc->sc_running) { RSU_UNLOCK(sc); return (ENXIO); } /* * XXX TODO: ensure that we treat 'm' as a list of frames * to transmit! */ error = mbufq_enqueue(&sc->sc_snd, m); if (error) { RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: mbufq_enable: failed (%d)\n", __func__, error); RSU_UNLOCK(sc); return (error); } RSU_UNLOCK(sc); /* This kicks the TX taskqueue */ rsu_start(sc); return (0); } static void rsu_drain_mbufq(struct rsu_softc *sc) { struct mbuf *m; struct ieee80211_node *ni; RSU_ASSERT_LOCKED(sc); while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) { ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; m->m_pkthdr.rcvif = NULL; ieee80211_free_node(ni); m_freem(m); } } static void _rsu_start(struct rsu_softc *sc) { struct ieee80211_node *ni; struct rsu_data *bf; struct mbuf *m; RSU_ASSERT_LOCKED(sc); while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) { bf = rsu_getbuf(sc); if (bf == NULL) { RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: failed to get buffer\n", __func__); mbufq_prepend(&sc->sc_snd, m); break; } ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; m->m_pkthdr.rcvif = NULL; if (rsu_tx_start(sc, ni, m, bf) != 0) { RSU_DPRINTF(sc, RSU_DEBUG_TX, "%s: failed to transmit\n", __func__); if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS, 1); rsu_freebuf(sc, bf); ieee80211_free_node(ni); m_freem(m); break; } } } static void rsu_start(struct rsu_softc *sc) { taskqueue_enqueue(taskqueue_thread, &sc->tx_task); } static void rsu_parent(struct ieee80211com *ic) { struct rsu_softc *sc = ic->ic_softc; int startall = 0; RSU_LOCK(sc); if (ic->ic_nrunning > 0) { if (!sc->sc_running) { rsu_init(sc); startall = 1; } } else if (sc->sc_running) rsu_stop(sc); RSU_UNLOCK(sc); if (startall) ieee80211_start_all(ic); } /* * Power on sequence for A-cut adapters. */ static void rsu_power_on_acut(struct rsu_softc *sc) { uint32_t reg; rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53); rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57); /* Enable AFE macro block's bandgap and Mbias. */ rsu_write_1(sc, R92S_AFE_MISC, rsu_read_1(sc, R92S_AFE_MISC) | R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN); /* Enable LDOA15 block. */ rsu_write_1(sc, R92S_LDOA15_CTRL, rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN); rsu_write_1(sc, R92S_SPS1_CTRL, rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN); rsu_ms_delay(sc, 2000); /* Enable switch regulator block. */ rsu_write_1(sc, R92S_SPS1_CTRL, rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN); rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90); /* Enable AFE clock. */ rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1, rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04); /* Enable AFE PLL macro block. */ rsu_write_1(sc, R92S_AFE_PLL_CTRL, rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11); /* Attach AFE PLL to MACTOP/BB. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL, rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11); /* Switch to 40MHz clock instead of 80MHz. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL); /* Enable MAC clock. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) | R92S_MAC_CLK_EN | R92S_SYS_CLK_EN); rsu_write_1(sc, R92S_PMC_FSM, 0x02); /* Enable digital core and IOREG R/W. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80); /* Switch the control path to firmware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL; rsu_write_2(sc, R92S_SYS_CLKR, reg); rsu_write_2(sc, R92S_CR, 0x37fc); /* Fix USB RX FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); rsu_write_1(sc, 0x00ab, rsu_read_1(sc, 0x00ab) | 0xc0); rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL); } /* * Power on sequence for B-cut and C-cut adapters. */ static void rsu_power_on_bcut(struct rsu_softc *sc) { uint32_t reg; int ntries; /* Prevent eFuse leakage. */ rsu_write_1(sc, 0x37, 0xb0); rsu_ms_delay(sc, 10); rsu_write_1(sc, 0x37, 0x30); /* Switch the control path to hardware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); if (reg & R92S_FWHW_SEL) { rsu_write_2(sc, R92S_SYS_CLKR, reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL)); } rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c); rsu_ms_delay(sc, 1); rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53); rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57); reg = rsu_read_1(sc, R92S_AFE_MISC); rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN); rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN); /* Enable PLL. */ rsu_write_1(sc, R92S_LDOA15_CTRL, rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN); rsu_write_1(sc, R92S_LDOV12D_CTRL, rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20); /* Support 64KB IMEM. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97); /* Enable AFE clock. */ rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1, rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04); /* Enable AFE PLL macro block. */ reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11); rsu_ms_delay(sc, 1); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51); rsu_ms_delay(sc, 1); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11); rsu_ms_delay(sc, 1); /* Attach AFE PLL to MACTOP/BB. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL, rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11); /* Switch to 40MHz clock. */ rsu_write_1(sc, R92S_SYS_CLKR, 0x00); /* Disable CPU clock and 80MHz SSC. */ rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0); /* Enable MAC clock. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) | R92S_MAC_CLK_EN | R92S_SYS_CLK_EN); rsu_write_1(sc, R92S_PMC_FSM, 0x02); /* Enable digital core and IOREG R/W. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80); /* Switch the control path to firmware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL; rsu_write_2(sc, R92S_SYS_CLKR, reg); rsu_write_2(sc, R92S_CR, 0x37fc); /* Fix USB RX FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL); rsu_write_1(sc, 0xfe1c, 0x80); /* Make sure TxDMA is ready to download firmware. */ for (ntries = 0; ntries < 20; ntries++) { reg = rsu_read_1(sc, R92S_TCR); if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) == (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) break; rsu_ms_delay(sc, 1); } if (ntries == 20) { RSU_DPRINTF(sc, RSU_DEBUG_RESET | RSU_DEBUG_TX, "%s: TxDMA is not ready\n", __func__); /* Reset TxDMA. */ reg = rsu_read_1(sc, R92S_CR); rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN); rsu_ms_delay(sc, 1); rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN); } } static void rsu_power_off(struct rsu_softc *sc) { /* Turn RF off. */ rsu_write_1(sc, R92S_RF_CTRL, 0x00); rsu_ms_delay(sc, 5); /* Turn MAC off. */ /* Switch control path. */ rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38); /* Reset MACTOP. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70); rsu_write_1(sc, R92S_PMC_FSM, 0x06); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8); /* Disable AFE PLL. */ rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00); /* Disable A15V. */ rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54); /* Disable eFuse 1.2V. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50); rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24); /* Enable AFE macro block's bandgap and Mbias. */ rsu_write_1(sc, R92S_AFE_MISC, 0x30); /* Disable 1.6V LDO. */ rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56); rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43); /* Firmware - tell it to switch things off */ (void) rsu_set_fw_power_state(sc, RSU_PWR_OFF); } static int rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len) { const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO]; struct rsu_data *data; struct r92s_tx_desc *txd; int mlen; while (len > 0) { data = rsu_getbuf(sc); if (data == NULL) return (ENOMEM); txd = (struct r92s_tx_desc *)data->buf; memset(txd, 0, sizeof(*txd)); if (len <= RSU_TXBUFSZ - sizeof(*txd)) { /* Last chunk. */ txd->txdw0 |= htole32(R92S_TXDW0_LINIP); mlen = len; } else mlen = RSU_TXBUFSZ - sizeof(*txd); txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen)); memcpy(&txd[1], buf, mlen); data->buflen = sizeof(*txd) + mlen; RSU_DPRINTF(sc, RSU_DEBUG_TX | RSU_DEBUG_FW | RSU_DEBUG_RESET, "%s: starting transfer %p\n", __func__, data); STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); buf += mlen; len -= mlen; } usbd_transfer_start(sc->sc_xfer[which]); return (0); } static int rsu_load_firmware(struct rsu_softc *sc) { const struct r92s_fw_hdr *hdr; struct r92s_fw_priv *dmem; struct ieee80211com *ic = &sc->sc_ic; const uint8_t *imem, *emem; int imemsz, ememsz; const struct firmware *fw; size_t size; uint32_t reg; int ntries, error; if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) { RSU_DPRINTF(sc, RSU_DEBUG_ANY, "%s: Firmware already loaded\n", __func__); return (0); } RSU_UNLOCK(sc); /* Read firmware image from the filesystem. */ if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) { device_printf(sc->sc_dev, "%s: failed load firmware of file rsu-rtl8712fw\n", __func__); RSU_LOCK(sc); return (ENXIO); } RSU_LOCK(sc); size = fw->datasize; if (size < sizeof(*hdr)) { device_printf(sc->sc_dev, "firmware too short\n"); error = EINVAL; goto fail; } hdr = (const struct r92s_fw_hdr *)fw->data; if (hdr->signature != htole16(0x8712) && hdr->signature != htole16(0x8192)) { device_printf(sc->sc_dev, "invalid firmware signature 0x%x\n", le16toh(hdr->signature)); error = EINVAL; goto fail; } DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version), hdr->month, hdr->day, hdr->hour, hdr->minute); /* Make sure that driver and firmware are in sync. */ if (hdr->privsz != htole32(sizeof(*dmem))) { device_printf(sc->sc_dev, "unsupported firmware image\n"); error = EINVAL; goto fail; } /* Get FW sections sizes. */ imemsz = le32toh(hdr->imemsz); ememsz = le32toh(hdr->sramsz); /* Check that all FW sections fit in image. */ if (size < sizeof(*hdr) + imemsz + ememsz) { device_printf(sc->sc_dev, "firmware too short\n"); error = EINVAL; goto fail; } imem = (const uint8_t *)&hdr[1]; emem = imem + imemsz; /* Load IMEM section. */ error = rsu_fw_loadsection(sc, imem, imemsz); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "IMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries != 50; ntries++) { rsu_ms_delay(sc, 10); reg = rsu_read_1(sc, R92S_TCR); if (reg & R92S_TCR_IMEM_CODE_DONE) break; } if (ntries == 50) { device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n"); error = ETIMEDOUT; goto fail; } /* Load EMEM section. */ error = rsu_fw_loadsection(sc, emem, ememsz); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "EMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries != 50; ntries++) { rsu_ms_delay(sc, 10); reg = rsu_read_2(sc, R92S_TCR); if (reg & R92S_TCR_EMEM_CODE_DONE) break; } if (ntries == 50) { device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n"); error = ETIMEDOUT; goto fail; } /* Enable CPU. */ rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL); if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) { device_printf(sc->sc_dev, "could not enable system clock\n"); error = EIO; goto fail; } rsu_write_2(sc, R92S_SYS_FUNC_EN, rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN); if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) { device_printf(sc->sc_dev, "could not enable microcontroller\n"); error = EIO; goto fail; } /* Wait for CPU to initialize. */ for (ntries = 0; ntries < 100; ntries++) { if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY) break; rsu_ms_delay(sc, 1); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for microcontroller\n"); error = ETIMEDOUT; goto fail; } /* Update DMEM section before loading. */ dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv); memset(dmem, 0, sizeof(*dmem)); dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172; dmem->nendpoints = sc->sc_nendpoints; dmem->chip_version = sc->cut; dmem->rf_config = sc->sc_rftype; dmem->vcs_type = R92S_VCS_TYPE_AUTO; dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS; dmem->turbo_mode = 0; dmem->bw40_en = !! (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40); dmem->amsdu2ampdu_en = !! (sc->sc_ht); dmem->ampdu_en = !! (sc->sc_ht); dmem->agg_offload = !! (sc->sc_ht); dmem->qos_en = 1; dmem->ps_offload = 1; dmem->lowpower_mode = 1; /* XXX TODO: configurable? */ /* Load DMEM section. */ error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem)); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "DMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries < 100; ntries++) { if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE) break; rsu_ms_delay(sc, 1); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for %s transfer\n", "DMEM"); error = ETIMEDOUT; goto fail; } /* Wait for firmware readiness. */ for (ntries = 0; ntries < 60; ntries++) { if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY)) break; rsu_ms_delay(sc, 1); } if (ntries == 60) { device_printf(sc->sc_dev, "timeout waiting for firmware readiness\n"); error = ETIMEDOUT; goto fail; } fail: firmware_put(fw, FIRMWARE_UNLOAD); return (error); } static int rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct rsu_softc *sc = ic->ic_softc; struct rsu_data *bf; /* prevent management frames from being sent if we're not ready */ if (!sc->sc_running) { m_freem(m); return (ENETDOWN); } RSU_LOCK(sc); bf = rsu_getbuf(sc); if (bf == NULL) { m_freem(m); RSU_UNLOCK(sc); return (ENOBUFS); } if (rsu_tx_start(sc, ni, m, bf) != 0) { m_freem(m); rsu_freebuf(sc, bf); RSU_UNLOCK(sc); return (EIO); } RSU_UNLOCK(sc); return (0); } static void rsu_init(struct rsu_softc *sc) { struct ieee80211com *ic = &sc->sc_ic; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); uint8_t macaddr[IEEE80211_ADDR_LEN]; int error; int i; RSU_ASSERT_LOCKED(sc); /* Ensure the mbuf queue is drained */ rsu_drain_mbufq(sc); /* Init host async commands ring. */ sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0; /* Reset power management state. */ rsu_write_1(sc, R92S_USB_HRPWM, 0); /* Power on adapter. */ if (sc->cut == 1) rsu_power_on_acut(sc); else rsu_power_on_bcut(sc); /* Load firmware. */ error = rsu_load_firmware(sc); if (error != 0) goto fail; /* Enable Rx TCP checksum offload. */ rsu_write_4(sc, R92S_RCR, rsu_read_4(sc, R92S_RCR) | 0x04000000); /* Append PHY status. */ rsu_write_4(sc, R92S_RCR, rsu_read_4(sc, R92S_RCR) | 0x02000000); rsu_write_4(sc, R92S_CR, rsu_read_4(sc, R92S_CR) & ~0xff000000); /* Use 128 bytes pages. */ rsu_write_1(sc, 0x00b5, rsu_read_1(sc, 0x00b5) | 0x01); /* Enable USB Rx aggregation. */ rsu_write_1(sc, 0x00bd, rsu_read_1(sc, 0x00bd) | 0x80); /* Set USB Rx aggregation threshold. */ rsu_write_1(sc, 0x00d9, 0x01); /* Set USB Rx aggregation timeout (1.7ms/4). */ rsu_write_1(sc, 0xfe5b, 0x04); /* Fix USB Rx FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); /* Set MAC address. */ IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr); rsu_write_region_1(sc, R92S_MACID, macaddr, IEEE80211_ADDR_LEN); /* It really takes 1.5 seconds for the firmware to boot: */ rsu_ms_delay(sc, 2000); RSU_DPRINTF(sc, RSU_DEBUG_RESET, "%s: setting MAC address to %s\n", __func__, ether_sprintf(macaddr)); error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, macaddr, IEEE80211_ADDR_LEN); if (error != 0) { device_printf(sc->sc_dev, "could not set MAC address\n"); goto fail; } /* Set PS mode fully active */ error = rsu_set_fw_power_state(sc, RSU_PWR_ACTIVE); if (error != 0) { device_printf(sc->sc_dev, "could not set PS mode\n"); goto fail; } sc->sc_scan_pass = 0; usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]); /* We're ready to go. */ sc->sc_running = 1; sc->sc_scanning = 0; return; fail: /* Need to stop all failed transfers, if any */ for (i = 0; i != RSU_N_TRANSFER; i++) usbd_transfer_stop(sc->sc_xfer[i]); } static void rsu_stop(struct rsu_softc *sc) { int i; RSU_ASSERT_LOCKED(sc); sc->sc_running = 0; sc->sc_calibrating = 0; taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL); taskqueue_cancel(taskqueue_thread, &sc->tx_task, NULL); /* Power off adapter. */ rsu_power_off(sc); for (i = 0; i < RSU_N_TRANSFER; i++) usbd_transfer_stop(sc->sc_xfer[i]); /* Ensure the mbuf queue is drained */ rsu_drain_mbufq(sc); } /* * Note: usb_pause_mtx() actually releases the mutex before calling pause(), * which breaks any kind of driver serialisation. */ static void rsu_ms_delay(struct rsu_softc *sc, int ms) { //usb_pause_mtx(&sc->sc_mtx, hz / 1000); DELAY(ms * 1000); }
26.152019
88
0.690269
[ "mesh" ]
c825fddaadc637bb5b2a81ab55bed40d7cbec651
502
h
C
EdfSjfScheduler.h
BraveNewPumpkin/os-bankers
92cdb44d7ed9f3c4dd04c824b362e382247eff90
[ "MIT" ]
1
2020-06-01T03:27:49.000Z
2020-06-01T03:27:49.000Z
EdfSjfScheduler.h
BraveNewPumpkin/os-bankers
92cdb44d7ed9f3c4dd04c824b362e382247eff90
[ "MIT" ]
null
null
null
EdfSjfScheduler.h
BraveNewPumpkin/os-bankers
92cdb44d7ed9f3c4dd04c824b362e382247eff90
[ "MIT" ]
null
null
null
// // Created by Kyle Bolton on 10/13/16. // implements ProcessScheduler interface #ifndef TEST_EDFSJFSCHEDULER_H #define TEST_EDFSJFSCHEDULER_H #include "EdfScheduler.h" class EdfSjfScheduler : public EdfScheduler { private: protected: std::function<bool(std::unique_ptr<Process> &a, std::unique_ptr<Process> &b)> makeComparator(); public: EdfSjfScheduler(std::unique_ptr<std::vector<std::unique_ptr<Process> > > &processes) : EdfScheduler(processes) {} }; #endif //TEST_EDFSJFSCHEDULER_H
21.826087
115
0.762948
[ "vector" ]
c832e701e4802f236e1a4f679a30e1f4ecaa0589
1,024
h
C
minio-cpp-examples/include/awsdoc/s3/s3_examples.h
minio/training
60c2a4fc57b7bad116f8d6037482050ef138bee1
[ "CC-BY-4.0" ]
null
null
null
minio-cpp-examples/include/awsdoc/s3/s3_examples.h
minio/training
60c2a4fc57b7bad116f8d6037482050ef138bee1
[ "CC-BY-4.0" ]
null
null
null
minio-cpp-examples/include/awsdoc/s3/s3_examples.h
minio/training
60c2a4fc57b7bad116f8d6037482050ef138bee1
[ "CC-BY-4.0" ]
null
null
null
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 #pragma once #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/BucketLocationConstraint.h> #include <awsdoc/s3/S3_EXPORTS.h> namespace AwsDoc { namespace S3 { AWSDOC_S3_API bool CreateBucket(const Aws::String& bucketName, const Aws::S3::Model::BucketLocationConstraint& region); AWSDOC_S3_API bool DeleteObject(const Aws::String& objectKey, const Aws::String& fromBucket, const Aws::String& region = ""); AWSDOC_S3_API bool GetObject(const Aws::String& objectKey, const Aws::String& fromBucket, const Aws::String& region = ""); AWSDOC_S3_API bool ListObjects(const Aws::String& bucketName, const Aws::String& region = ""); AWSDOC_S3_API bool PutObject(const Aws::String& bucketName, const Aws::String& objectName, const Aws::String& region = ""); } }
36.571429
75
0.662109
[ "model" ]
c8332b3c9738762b41e33fb0f8e3b30930b9b132
8,762
h
C
Development/External/Novodex/Physics/include/NxContactStreamIterator.h
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/External/Novodex/Physics/include/NxContactStreamIterator.h
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/External/Novodex/Physics/include/NxContactStreamIterator.h
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
#ifndef NX_PHYSICS_NXCONTACTSTREAMITERATOR #define NX_PHYSICS_NXCONTACTSTREAMITERATOR /*----------------------------------------------------------------------------*\ | | Public Interface to NovodeX Technology | | www.novodex.com | \*----------------------------------------------------------------------------*/ #include "Nxp.h" typedef NxU32 * NxContactStream; typedef const NxU32 * NxConstContactStream; enum NxShapePairStreamFlags { NX_SF_HAS_MATS_PER_POINT = (1<<0), //!< used when we have materials per triangle in a mesh. In this case the extData field is used after the point separation value. NX_SF_IS_INVALID = (1<<1), //!< this pair was invalidated in the system after being generated. The user should ignore these pairs. NX_SF_HAS_FEATURES_PER_POINT = (1<<2), //!< the stream includes per-point feature data //note: bits 8-15 are reserved for internal use (static ccd pullback counter) }; /** NxContactStreamIterator is for iterating through packed contact streams. The user code to use this iterator looks like this: void MyUserContactInfo::onContactNotify(NxPair & pair, NxU32 events) { NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here } } } } Note: It is NOT OK to skip any of the iteration calls. For example, you may NOT put a break or a continue statement in any of the above blocks, short of completely aborting the iteration and deleting the NxContactStreamIterator object. If the stream was received from a NxFluidContactPair then some iterator methods work slightly different (see comments to the methods below). */ class NxContactStreamIterator { public: /** Starts the iteration, and returns the number of pairs. */ NX_INLINE NxContactStreamIterator(NxConstContactStream stream); //iteration: NX_INLINE bool goNextPair(); //!< Goes on to the next pair, silently skipping invalid pairs. Returns false if there are no more pairs. Note that getNumPairs() also includes invalid pairs in the count. NX_INLINE bool goNextPatch(); //!< Goes on to the next patch (contacts with the same normal). Returns false if there are no more. NX_INLINE bool goNextPoint(); //!< Goes on to the next contact point. Returns false if there are no more. //accessors: NX_INLINE NxU32 getNumPairs(); //!< May be called at any time. Returns the number of pairs in the structure. Note: now some of these pairs may be marked invalid using getShapeFlags() & NX_SF_IS_INVALID, so the effective number may be lower. goNextPair() will automatically skip these! /** may be called after goNextPair() returned true. ShapeIndex is 0 or 1. Fluid actor contact stream: getShape(1) always returns NULL. */ NX_INLINE NxShape * getShape(NxU32 shapeIndex); NX_INLINE NxU16 getShapeFlags(); //!< may be called after goNextPair() returned true NX_INLINE NxU32 getNumPatches(); //!< may be called after goNextPair() returned true NX_INLINE NxU32 getNumPatchesRemaining();//!< may be called after goNextPair() returned true NX_INLINE const NxVec3 & getPatchNormal(); //!< may be called after goNextPatch() returned true NX_INLINE NxU32 getNumPoints();//!< may be called after goNextPatch() returned true NX_INLINE NxU32 getNumPointsRemaining();//!< may be called after goNextPatch() returned true /** may be called after goNextPoint() returned true returns to contact point position. Fluid actor contact stream: If NX_SF_HAS_FEATURES_PER_POINT is specified, this returns the barycentric coordinates within the contact triangle. In this case the z coordinate is 0.0. */ NX_INLINE const NxVec3 & getPoint(); /** may be called after goNextPoint() returned true Fluid actor contact stream: always returns 0.0f. */ NX_INLINE NxReal getSeparation(); /** may be called after goNextPoint() returned true If NX_SF_HAS_FEATURES_PER_POINT is specified, this method returns a feature belonging to shape 0, Fluid actor contact stream: returns the triangle index if shape 0 is a mesh shape. */ NX_INLINE NxU32 getFeatureIndex0(); /** may be called after goNextPoint() returned true If NX_SF_HAS_FEATURES_PER_POINT is specified, this method returns a feature belonging to shape 1, Fluid actor contact stream: returns always 0. */ NX_INLINE NxU32 getFeatureIndex1(); NX_INLINE NxU32 getExtData(); //!< return a combination of ::NxShapePairStreamFlags private: //iterator variables -- are only initialized by stream iterator calls: //Note: structs are used so that we can leave the iterators vars on the stack as they were //and the user's iteration code doesn't have to change when we add members. NxU32 numPairs; //current pair properties: NxShape * shapes[2]; NxU16 shapeFlags; NxU16 numPatches; //current patch properties: const NxVec3 * patchNormal; NxU32 numPoints; //current point properties: const NxVec3 * point; NxReal separation; NxU32 featureIndex0; NxU32 featureIndex1; NxU32 extData; //only exists if (shapeFlags & NX_SF_HAS_MATS_PER_POINT) NxU32 numPairsRemaining, numPatchesRemaining, numPointsRemaining; protected: NxConstContactStream stream; }; NX_INLINE NxContactStreamIterator::NxContactStreamIterator(NxConstContactStream s) { stream = s; numPairsRemaining = numPairs = stream ? *stream++ : 0; } NX_INLINE NxU32 NxContactStreamIterator::getNumPairs() { return numPairs; } NX_INLINE NxShape * NxContactStreamIterator::getShape(NxU32 shapeIndex) { NX_ASSERT(shapeIndex<=1); return shapes[shapeIndex]; } NX_INLINE NxU16 NxContactStreamIterator::getShapeFlags() { return shapeFlags; } NX_INLINE NxU32 NxContactStreamIterator::getNumPatches() { return numPatches; } NX_INLINE NxU32 NxContactStreamIterator::getNumPatchesRemaining() { return numPatchesRemaining; } NX_INLINE const NxVec3 & NxContactStreamIterator::getPatchNormal() { return *patchNormal; } NX_INLINE NxU32 NxContactStreamIterator::getNumPoints() { return numPoints; } NX_INLINE NxU32 NxContactStreamIterator::getNumPointsRemaining() { return numPointsRemaining; } NX_INLINE const NxVec3 & NxContactStreamIterator::getPoint() { return *point; } NX_INLINE NxReal NxContactStreamIterator::getSeparation() { return separation; } NX_INLINE NxU32 NxContactStreamIterator::getFeatureIndex0() { return featureIndex0; } NX_INLINE NxU32 NxContactStreamIterator::getFeatureIndex1() { return featureIndex1; } NX_INLINE NxU32 NxContactStreamIterator::getExtData() { return extData; } NX_INLINE bool NxContactStreamIterator::goNextPair() { while (numPairsRemaining--) { #ifdef NX32 size_t bin0 = *stream++; size_t bin1 = *stream++; shapes[0] = (NxShape*)bin0; shapes[1] = (NxShape*)bin1; // shapes[0] = (NxShape*)*stream++; // shapes[1] = (NxShape*)*stream++; #else NxU64 low = (NxU64)*stream++; NxU64 high = (NxU64)*stream++; NxU64 bits = low|(high<<32); shapes[0] = (NxShape*)bits; low = (NxU64)*stream++; high = (NxU64)*stream++; bits = low|(high<<32); shapes[1] = (NxShape*)bits; #endif NxU32 t = *stream++; numPatchesRemaining = numPatches = t & 0xffff; shapeFlags = t >> 16; if (!(shapeFlags & NX_SF_IS_INVALID)) return true; } return false; } NX_INLINE bool NxContactStreamIterator::goNextPatch() { if (numPatches--) { patchNormal = reinterpret_cast<const NxVec3 *>(stream); stream += 3; numPointsRemaining = numPoints = *stream++; return true; } else return false; } NX_INLINE bool NxContactStreamIterator::goNextPoint() { if (numPointsRemaining--) { // Get contact point point = reinterpret_cast<const NxVec3 *>(stream); stream += 3; // Get separation NxU32 binary = *stream++; NxU32 is32bits = binary & NX_SIGN_BITMASK; binary |= NX_SIGN_BITMASK; // PT: separation is always negative, but the sign bit is used // for other purposes in the stream. separation = NX_FR(binary); // Get extra data if (shapeFlags & NX_SF_HAS_MATS_PER_POINT) extData = *stream++; else extData = 0xffffffff; //means that there is no ext data. if (shapeFlags & NX_SF_HAS_FEATURES_PER_POINT) { if(is32bits) { featureIndex0 = *stream++; featureIndex1 = *stream++; } else { featureIndex0 = *stream++; featureIndex1 = featureIndex0>>16; featureIndex0 &= 0xffff; } } else { featureIndex0 = 0xffffffff; featureIndex1 = 0xffffffff; } //bind = *stream++; //materialIDs[0] = bind & 0xffff; //materialIDs[1] = bind >> 16; return true; } else return false; } #endif
28.822368
288
0.721297
[ "mesh", "object", "shape" ]
c835a22077cecfd9d9642a1b2bc51d6a19ccbf6a
24,683
c
C
ds/ds/src/util/dcdiag/common/bindings.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/util/dcdiag/common/bindings.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/util/dcdiag/common/bindings.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999 Microsoft Corporation. All rights reserved. MODULE NAME: common\bindings.c ABSTRACT: This file has all the binding type functions, for getting Cached LDAP, DS, or Net Use/Named Pipe bindings. DETAILS: CREATED: 02 Sept 1999 Brett Shirley (BrettSh) --*/ #include <ntdspch.h> #include <ntdsa.h> #include <mdglobal.h> #include <dsutil.h> #include <ntldap.h> #include <ntlsa.h> #include <ntseapi.h> #include <winnetwk.h> #include <permit.h> #include <netevent.h> #include "dcdiag.h" #include "ldaputil.h" #include "ndnc.h" // Code.Improvement move this function here from intersite.c VOID InitLsaString( OUT PLSA_UNICODE_STRING pLsaString, IN LPWSTR pszString ); // =========================================================================== // Ldap connections/binding (ldap_init(), ldap_bind(), ldap_unbind(), etc) // =========================================================================== DWORD DcDiagCacheServerRootDseAttrs( IN LDAP *hLdapBinding, IN PDC_DIAG_SERVERINFO pServer ) /*++ Routine Description: Reads server-specific Root DSE attributes and caches them in the server object. Helper routine for GetLdapBinding(). This may also be called by GatherInfo, which constructs the ldap binding to the home server directly without calling GetLdapBinding(). In order to help diagnose binding errors, it is necessary to obtain Root DSE attributes before the bind takes place. We report errors here in this routine to help identify contributing factors to a bind failure. Arguments: hLdapBinding - Binding to server that is going to be queried pServer - Server corresponding to binding, to receive attributes Return Value: DWORD - --*/ { DWORD dwRet; LPWSTR ppszRootDseServerAttrs [] = { L"currentTime", L"highestCommittedUSN", L"isSynchronized", L"isGlobalCatalogReady", NULL }; LDAPMessage * pldmEntry = NULL; LDAPMessage * pldmRootResults = NULL; LPWSTR * ppszValues = NULL; dwRet = ldap_search_sW (hLdapBinding, NULL, LDAP_SCOPE_BASE, L"(objectCategory=*)", ppszRootDseServerAttrs, 0, &pldmRootResults); if (dwRet != ERROR_SUCCESS) { dwRet = LdapMapErrorToWin32(dwRet); PrintMessage(SEV_ALWAYS, L"[%s] LDAP search failed with error %d,\n", pServer->pszName, dwRet); PrintMessage(SEV_ALWAYS, L"%s.\n", Win32ErrToString(dwRet)); goto cleanup; } if (pldmRootResults == NULL) { dwRet = ERROR_DS_MISSING_EXPECTED_ATT; goto cleanup; } pldmEntry = ldap_first_entry (hLdapBinding, pldmRootResults); if (pldmEntry == NULL) { dwRet = ERROR_DS_MISSING_EXPECTED_ATT; goto cleanup; } // // Attribute: currentTime // ppszValues = ldap_get_valuesW( hLdapBinding, pldmEntry, L"currentTime" ); if ( (ppszValues) && (ppszValues[0]) ) { SYSTEMTIME systemTime; PrintMessage( SEV_DEBUG, L"%s.currentTime = %ls\n", pServer->pszName, ppszValues[0] ); dwRet = DcDiagGeneralizedTimeToSystemTime((LPWSTR) ppszValues[0], &systemTime); if(dwRet == ERROR_SUCCESS){ SystemTimeToFileTime(&systemTime, &(pServer->ftRemoteConnectTime) ); GetSystemTime( &systemTime ); SystemTimeToFileTime( &systemTime, &(pServer->ftLocalAcquireTime) ); } else { PrintMessage( SEV_ALWAYS, L"[%s] Warning: Root DSE attribute %ls is has invalid value %ls\n", pServer->pszName, L"currentTime", ppszValues[0] ); // keep going, not fatal } } else { PrintMessage( SEV_ALWAYS, L"[%s] Warning: Root DSE attribute %ls is missing\n", pServer->pszName, L"currentTime" ); // keep going, not fatal } ldap_value_freeW(ppszValues ); // // Attribute: highestCommittedUSN // ppszValues = ldap_get_valuesW( hLdapBinding, pldmEntry, L"highestCommittedUSN" ); if ( (ppszValues) && (ppszValues[0]) ) { pServer->usnHighestCommittedUSN = _wtoi64( *ppszValues ); } else { PrintMessage( SEV_ALWAYS, L"[%s] Warning: Root DSE attribute %ls is missing\n", pServer->pszName, L"highestCommittedUSN" ); // keep going, not fatal } ldap_value_freeW(ppszValues ); PrintMessage( SEV_DEBUG, L"%s.highestCommittedUSN = %I64d\n", pServer->pszName, pServer->usnHighestCommittedUSN ); // // Attribute: isSynchronized // ppszValues = ldap_get_valuesW( hLdapBinding, pldmEntry, L"isSynchronized" ); if ( (ppszValues) && (ppszValues[0]) ) { pServer->bIsSynchronized = (_wcsicmp( ppszValues[0], L"TRUE" ) == 0); } else { PrintMessage( SEV_ALWAYS, L"[%s] Warning: Root DSE attribute %ls is missing\n", pServer->pszName, L"isSynchronized" ); // keep going, not fatal } ldap_value_freeW(ppszValues ); PrintMessage( SEV_DEBUG, L"%s.isSynchronized = %d\n", pServer->pszName, pServer->bIsSynchronized ); if (!pServer->bIsSynchronized) { PrintMsg( SEV_ALWAYS, DCDIAG_INITIAL_DS_NOT_SYNCED, pServer->pszName ); } // // Attribute: isGlobalCatalogReady // ppszValues = ldap_get_valuesW( hLdapBinding, pldmEntry, L"isGlobalCatalogReady" ); if ( (ppszValues) && (ppszValues[0]) ) { pServer->bIsGlobalCatalogReady = (_wcsicmp( ppszValues[0], L"TRUE" ) == 0); } else { PrintMessage( SEV_ALWAYS, L"[%s] Warning: Root DSE attribute %ls is missing\n", pServer->pszName, L"isGlobalCatalogReady" ); // keep going, not fatal } ldap_value_freeW(ppszValues ); PrintMessage( SEV_DEBUG, L"%s.isGlobalCatalogReady = %d\n", pServer->pszName, pServer->bIsGlobalCatalogReady ); cleanup: if (pldmRootResults) { ldap_msgfree (pldmRootResults); } return dwRet; } /* DcDiagCacheServerRootDseAttrs */ DWORD DcDiagGetLdapBinding( IN PDC_DIAG_SERVERINFO pServer, IN SEC_WINNT_AUTH_IDENTITY_W * gpCreds, IN BOOL bUseGcPort, OUT LDAP * * phLdapBinding ) /*++ Routine Description: This returns a LDAP binding from ldap_init() and ldap_bind_sW(). The function caches the binding handle and the error. This function also turns off referrals. Arguments: pServer - Server for which binding is desired gpCreds - Credentials bUseGcPort - Whether to bind to the GC port phLdapBinding - Returned binding, on success. Also cached. Return Value: NOTE - DO NOT unbind the ldap handle. DWORD - Win32 error return --*/ { DWORD dwRet; LDAP * hLdapBinding; LPWSTR pszServer = NULL; ULONG ulOptions = PtrToUlong(LDAP_OPT_ON); // Return cached failure if stored // Success can mean never tried, or binding present dwRet = bUseGcPort ? pServer->dwGcLdapError : pServer->dwLdapError; if(dwRet != ERROR_SUCCESS){ return dwRet; } // Return cached binding if stored hLdapBinding = bUseGcPort ? pServer->hGcLdapBinding : pServer->hLdapBinding; if (hLdapBinding != NULL) { *phLdapBinding = hLdapBinding; return ERROR_SUCCESS; } // Try to refresh the cache by contacting the server if(pServer->pszGuidDNSName == NULL){ // This means that the Guid name isn't specified, use normal name. pszServer = pServer->pszName; } else { pszServer = pServer->pszGuidDNSName; } Assert(pszServer); // // There is no existing ldap binding of the kind we want. so create one // hLdapBinding = ldap_initW(pszServer, bUseGcPort ? LDAP_GC_PORT : LDAP_PORT); if(hLdapBinding == NULL){ dwRet = GetLastError(); PrintMessage(SEV_ALWAYS, L"[%s] LDAP connection failed with error %d,\n", pServer->pszName, dwRet); PrintMessage(SEV_ALWAYS, L"%s.\n", Win32ErrToString(dwRet)); goto cleanup; } // use only A record dns name discovery (void)ldap_set_optionW( hLdapBinding, LDAP_OPT_AREC_EXCLUSIVE, &ulOptions); // Set Ldap referral option dwRet = ldap_set_option(hLdapBinding, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); if(dwRet != LDAP_SUCCESS){ dwRet = LdapMapErrorToWin32(dwRet); PrintMessage(SEV_ALWAYS, L"[%s] LDAP setting options failed with error %d,\n", pServer->pszName, dwRet); PrintMessage(SEV_ALWAYS, L"%s.\n", Win32ErrToString(dwRet)); goto cleanup; } // Cache some RootDSE attributes we are interested in // Do this before binding so we can obtain info to help us diagnose // security problems. dwRet = DcDiagCacheServerRootDseAttrs( hLdapBinding, pServer ); if (dwRet) { // Error already displayed goto cleanup; } // Perform ldap bind dwRet = ldap_bind_sW(hLdapBinding, NULL, (RPC_AUTH_IDENTITY_HANDLE) gpCreds, LDAP_AUTH_SSPI); if(dwRet != LDAP_SUCCESS){ dwRet = LdapMapErrorToWin32(dwRet); PrintMessage(SEV_ALWAYS, L"[%s] LDAP bind failed with error %d,\n", pServer->pszName, dwRet); PrintMessage(SEV_ALWAYS, L"%s.\n", Win32ErrToString(dwRet)); goto cleanup; } cleanup: if (!dwRet) { *phLdapBinding = hLdapBinding; } else { if (hLdapBinding) { ldap_unbind(hLdapBinding); hLdapBinding = NULL; } } if(bUseGcPort){ pServer->hGcLdapBinding = hLdapBinding; pServer->dwGcLdapError = dwRet; } else { pServer->hLdapBinding = hLdapBinding; pServer->dwLdapError = dwRet; } return dwRet; } /* DcDiagGetLdapBinding */ DWORD DcDiagGetDomainNamingFsmoLdapBinding( IN PDC_DIAG_DSINFO pDsInfo, IN SEC_WINNT_AUTH_IDENTITY_W * gpCreds, OUT PULONG piFsmoServer, OUT LPWSTR * ppszFsmoServer, OUT LDAP ** phLdapBinding ) /*++ Routine Description: This returns a LDAP binding to the Domain Naming FSMO via calls to ldap_init() and ldap_bind_sW(). The function caches the binding handle. This function also turns off referrals. Arguments: pDsInfo - gpCreds - Credentials piFsmoServer - Either this or the next parameter will be returned. -1 if invalid, index into pDsInfo->pServers otherwise. ppszFsmoServer - NULL if invalid, string name of FSMO server otherwise. phLdapBinding - Returned binding, on success. Also cached. Return Value: NOTE - DO NOT unbind the ldap handle. DWORD - Win32 error return --*/ { DWORD dwRet = ERROR_SUCCESS; LPWSTR pszHostName = NULL; LDAP * hld = NULL; Assert(piFsmoServer); Assert(ppszFsmoServer); Assert(phLdapBinding); if(pDsInfo->hCachedDomainNamingFsmoLdap){ *piFsmoServer = pDsInfo->iDomainNamingFsmo; *ppszFsmoServer = pDsInfo->pszDomainNamingFsmo; *phLdapBinding = pDsInfo->hCachedDomainNamingFsmoLdap; return(ERROR_SUCCESS); } *piFsmoServer = -1; *ppszFsmoServer = NULL; // Unfortunately this existing function isn't very in tune with our // existing DcDiagGetLdapBinding() structure, so we call this function // to get the LDAP * on the right server and then merge the information // a little awkwardly into our existing DsInfo struct. hld = GetDomNameFsmoLdapBinding( pDsInfo->pServers[pDsInfo->ulHomeServer].pszGuidDNSName, FALSE, gpCreds, &dwRet); if(hld == NULL || dwRet){ Assert(hld == NULL); Assert(dwRet); return(dwRet); } Assert(hld); // Now must set iFsmoServer || pszFsmoServer on pDsInfo dwRet = GetRootAttr(hld, L"dnsHostName", &pszHostName); if (dwRet) { return(dwRet); } // Set return params *piFsmoServer = DcDiagGetServerNum(pDsInfo, NULL, NULL, NULL, pszHostName, NULL); if(*piFsmoServer == -1){ // No existing server object in pServers, so we have to cache // this the hard way. *phLdapBinding = hld; *ppszFsmoServer = pszHostName; } else { LocalFree(pszHostName); ldap_unbind(hld); dwRet = DcDiagGetLdapBinding(&pDsInfo->pServers[*piFsmoServer], gpCreds, FALSE, phLdapBinding); if (dwRet) { *phLdapBinding = NULL; } } Assert( (*piFsmoServer != -1) || (*ppszFsmoServer != NULL) ); Assert( *phLdapBinding ); // Cache the binding info on the pDsInfo struct. pDsInfo->iDomainNamingFsmo = *piFsmoServer; pDsInfo->pszDomainNamingFsmo = *ppszFsmoServer; pDsInfo->hCachedDomainNamingFsmoLdap = *phLdapBinding; return(ERROR_SUCCESS); } // =========================================================================== // Ds RPC handle binding (DsBind, DsUnBind(), etc) // =========================================================================== DWORD DcDiagGetDsBinding( IN PDC_DIAG_SERVERINFO pServer, IN SEC_WINNT_AUTH_IDENTITY_W * gpCreds, OUT HANDLE * phDsBinding ) /*++ Routine Description: This returns a Ds Binding from DsBindWithCredW(), this binding is cached, as well as the error if there is one. Arguments: pServer - A pointer to the server structure you want the Ds Binding of. gpCreds - Credentials. phDsBinding - return value for the ds binding handle. Return Value: Returns a standard Win32 error. NOTE - DO NOT unbind the ds handle. --*/ { DWORD dwRet; LPWSTR pszServer = NULL; if(pServer->dwDsError != ERROR_SUCCESS){ return(pServer->dwDsError); } if(pServer->pszGuidDNSName == NULL){ pszServer = pServer->pszName; } else { pszServer = pServer->pszGuidDNSName; } Assert(pszServer != NULL); if(pServer->hDsBinding == NULL){ // no exisiting binding stored, hey I have an idea ... lets create one! dwRet = DsBindWithSpnEx(pszServer, NULL, (RPC_AUTH_IDENTITY_HANDLE) gpCreds, NULL, // use default SPN 0, // no flags = impersonation, but no delegation binding &pServer->hDsBinding); if(dwRet != NO_ERROR){ PrintMessage(SEV_ALWAYS, L"[%s] DsBindWithSpnEx() failed with error %d,\n", pServer->pszName, dwRet); PrintMessage(SEV_ALWAYS, L"%s.\n", Win32ErrToString(dwRet)); PrintRpcExtendedInfo(SEV_VERBOSE, dwRet); pServer->dwDsError = dwRet; return(dwRet); } } // else we already had a binding in the pServer structure, either way // we now have a binding in the pServer structure. :) *phDsBinding = pServer->hDsBinding; pServer->dwDsError = ERROR_SUCCESS; return(NO_ERROR); } // =========================================================================== // Net Use binding (WNetAddConnection2(), WNetCancelConnection(), etc) // =========================================================================== DWORD DcDiagGetNetConnection( IN PDC_DIAG_SERVERINFO pServer, IN SEC_WINNT_AUTH_IDENTITY_W * gpCreds ) /*++ Routine Description: This routine will make sure there is a net use/unnamed pipe connection to the target machine pServer. Arguments: pServer - Server to Add the Net connection to. gpCreds - the crdentials. Return Value: DWORD - win 32 error. --*/ { DWORD dwToSet = ERROR_SUCCESS; LPWSTR pszNetUseServer = NULL; LPWSTR pszNetUseUser = NULL; LPWSTR pszNetUsePassword = NULL; ULONG iTemp; if(pServer->dwNetUseError != ERROR_SUCCESS){ return(pServer->dwNetUseError); } if(pServer->sNetUseBinding.pszNetUseServer != NULL){ // Do nothing if there already is a net use connection setup. Assert(pServer->dwNetUseError == ERROR_SUCCESS); } else { // INIT ---------------------------------------------------------- // Always initialize the object attributes to all zeroes. InitializeObjectAttributes( &(pServer->sNetUseBinding.ObjectAttributes), NULL, 0, NULL, NULL); // Initialize various strings for the Lsa Services and for // WNetAddConnection2() InitLsaString( &(pServer->sNetUseBinding.sLsaServerString), pServer->pszName ); InitLsaString( &(pServer->sNetUseBinding.sLsaRightsString), SE_NETWORK_LOGON_NAME ); if(gpCreds != NULL && gpCreds->User != NULL && gpCreds->Password != NULL && gpCreds->Domain != NULL){ // only need 2 for NULL, and an extra just in case. iTemp = wcslen(gpCreds->Domain) + wcslen(gpCreds->User) + 4; pszNetUseUser = LocalAlloc(LMEM_FIXED, iTemp * sizeof(WCHAR)); if(pszNetUseUser == NULL){ dwToSet = ERROR_NOT_ENOUGH_MEMORY; goto CleanUpAndExit; } wcscpy(pszNetUseUser, gpCreds->Domain); wcscat(pszNetUseUser, L"\\"); wcscat(pszNetUseUser, gpCreds->User); pszNetUsePassword = gpCreds->Password; } // end if creds, else assume default creds ... // pszNetUseUser = NULL; pszNetUsePassword = NULL; // "\\\\" + "\\ipc$" iTemp = wcslen(pServer->pszName) + 10; pszNetUseServer = LocalAlloc(LMEM_FIXED, iTemp * sizeof(WCHAR)); if(pszNetUseServer == NULL){ dwToSet = ERROR_NOT_ENOUGH_MEMORY; goto CleanUpAndExit; } wcscpy(pszNetUseServer, L"\\\\"); wcscat(pszNetUseServer, pServer->pszName); wcscat(pszNetUseServer, L"\\ipc$"); // Initialize NetResource structure for WNetAddConnection2() pServer->sNetUseBinding.NetResource.dwType = RESOURCETYPE_ANY; pServer->sNetUseBinding.NetResource.lpLocalName = NULL; pServer->sNetUseBinding.NetResource.lpRemoteName = pszNetUseServer; pServer->sNetUseBinding.NetResource.lpProvider = NULL; // CONNECT & QUERY ----------------------------------------------- //net use \\brettsh-posh\ipc$ /u:brettsh-fsmo\administrator "" dwToSet = WNetAddConnection2( &(pServer->sNetUseBinding.NetResource), // connection details pszNetUsePassword, // points to password pszNetUseUser, // points to user name string 0); // set of bit flags that specify CleanUpAndExit: if(dwToSet == ERROR_SUCCESS){ // Setup the servers binding struct. pServer->sNetUseBinding.pszNetUseServer = pszNetUseServer; pServer->sNetUseBinding.pszNetUseUser = pszNetUseUser; pServer->dwNetUseError = ERROR_SUCCESS; } else { // There was an error, print it, clean up, and set error. switch(dwToSet){ case ERROR_SUCCESS: Assert(!"This is completely impossible"); break; case ERROR_SESSION_CREDENTIAL_CONFLICT: PrintMessage(SEV_ALWAYS, L"* You must make sure there are no existing " L"net use connections,\n"); PrintMessage(SEV_ALWAYS, L" you can use \"net use /d %s\" or \"net use " L"/d\n", pszNetUseServer); PrintMessage(SEV_ALWAYS, L" \\\\<machine-name>\\<share-name>\"\n"); break; case ERROR_NOT_ENOUGH_MEMORY: PrintMessage(SEV_ALWAYS, L"Fatal Error: Not enough memory to complete " L"operation.\n"); break; case ERROR_ALREADY_ASSIGNED: PrintMessage(SEV_ALWAYS, L"Fatal Error: The network resource is already " L"in use\n"); break; case STATUS_ACCESS_DENIED: case ERROR_INVALID_PASSWORD: case ERROR_LOGON_FAILURE: // This comes from the LsaOpenPolicy or // LsaEnumerateAccountsWithUserRight or // from WNetAddConnection2 PrintMessage(SEV_ALWAYS, L"User credentials does not have permission to " L"perform this operation.\n"); PrintMessage(SEV_ALWAYS, L"The account used for this test must have " L"network logon privileges\n"); PrintMessage(SEV_ALWAYS, L"for the target machine's domain.\n"); break; case STATUS_NO_MORE_ENTRIES: // This comes from LsaEnumerateAccountsWithUserRight default: PrintMessage(SEV_ALWAYS, L"[%s] An net use or LsaPolicy operation failed " L"with error %d, %s.\n", pServer->pszName, dwToSet, Win32ErrToString(dwToSet)); break; } // Clean up any possible allocations. if(pszNetUseServer != NULL) LocalFree(pszNetUseServer); if(pszNetUseUser != NULL) LocalFree(pszNetUseUser); pServer->dwNetUseError = dwToSet; } } return(pServer->dwNetUseError); } VOID DcDiagTearDownNetConnection( IN PDC_DIAG_SERVERINFO pServer ) /*++ Routine Description: This will tear down the Net Connection added by DcDiagGetNetConnection() Arguments: pServer - The target server. Return Value: DWORD - win 32 error. --*/ { if(pServer->sNetUseBinding.pszNetUseServer != NULL){ WNetCancelConnection2(pServer->sNetUseBinding.pszNetUseServer, 0, FALSE); LocalFree(pServer->sNetUseBinding.pszNetUseServer); LocalFree(pServer->sNetUseBinding.pszNetUseUser); pServer->sNetUseBinding.pszNetUseServer = NULL; pServer->sNetUseBinding.pszNetUseUser = NULL; } else { Assert(!"Bad Programmer, calling TearDown on a closed connection\n"); } }
34.139696
106
0.547745
[ "object" ]
c83cf010d9afe3e8bc1a5ea09a0812ef68ed69ee
5,156
h
C
base/include/sys_event.h
chaoyangcui/hiviewdfx_hiview
32251dad5b7623631288a1947518e03494c1f7a4
[ "Apache-2.0" ]
null
null
null
base/include/sys_event.h
chaoyangcui/hiviewdfx_hiview
32251dad5b7623631288a1947518e03494c1f7a4
[ "Apache-2.0" ]
null
null
null
base/include/sys_event.h
chaoyangcui/hiviewdfx_hiview
32251dad5b7623631288a1947518e03494c1f7a4
[ "Apache-2.0" ]
1
2021-09-13T12:06:51.000Z
2021-09-13T12:06:51.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 HIVIEW_BASE_SYS_EVENT_H #define HIVIEW_BASE_SYS_EVENT_H #include <iomanip> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <vector> #include "pipeline.h" namespace OHOS { namespace HiviewDFX { class SysEventCreator; class SysEvent : public PipelineEvent { public: SysEvent(const std::string& sender, PipelineEventProducer* handler, const std::string& jsonStr); SysEvent(const std::string& sender, PipelineEventProducer* handler, SysEventCreator& sysEventCreator); ~SysEvent(); public: int PaserJson(); int32_t GetPid() const; int32_t GetTid() const; int32_t GetUid() const; int16_t GetTz() const; void SetSeq(int64_t); int64_t GetSeq() const; std::string GetEventValue(const std::string& key); void SetEventValue(const std::string& key, int64_t value); void SetEventValue(const std::string& key, const std::string& value, bool append = false); private: int64_t seq_; int32_t pid_; int32_t tid_; int32_t uid_; int16_t tz_; }; class SysEventCreator { public: enum EventType { FAULT = 1, // system fault event STATISTIC = 2, // system statistic event SECURITY = 3, // system security event BEHAVIOR = 4 // system behavior event }; public: SysEventCreator(const std::string &domain, const std::string &eventName, EventType type); template <typename T, typename U, typename... Rest> struct is_one_of : std::conditional_t<std::is_same_v<typename std::decay_t<T>, typename std::decay_t<U>>, std::true_type, is_one_of<T, Rest...>> {}; template <typename T, typename U> struct is_one_of<T, U> : std::conditional_t<std::is_same_v<typename std::decay_t<T>, typename std::decay_t<U>>, std::true_type, std::false_type> {}; template <typename Inst, template <typename...> typename Tmpl> struct is_instantiation_of : std::false_type {}; template <template <typename...> typename Tmpl, typename... Args> struct is_instantiation_of<Tmpl<Args...>, Tmpl> : std::true_type {}; // supported types of the key template <typename T> struct is_type_key : is_one_of<T, char *, char const *, std::string>::type {}; template <typename T> inline static constexpr bool is_type_key_v = is_type_key<T>::value; // supported base types of the value template <typename T> struct is_type_value_base : is_one_of<T, bool, char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long, float, double, char *, char const *, std::string>::type {}; template <typename T> inline static constexpr bool is_type_value_base_v = is_type_value_base<T>::value; // supported vector types of the value template <typename T> inline static constexpr bool is_type_value_vector_v = []() { if constexpr(is_instantiation_of<typename std::decay_t<T>, std::vector>::value) { return is_type_value_base_v<typename std::decay_t<T>::value_type>; } return false; }(); template<typename T> static decltype(auto) GetItem(T&& item) { if constexpr(is_one_of<T, char, signed char, unsigned char>::value) { return static_cast<short>(item); } else if constexpr(is_one_of<T, char *, char const *, std::string>::value) { return std::quoted(EscapeStringValue(item)); } else { return std::forward<T>(item); } } template<typename K, typename V> SysEventCreator& SetKeyValue(K&& key, V&& value) { jsonStr_ << GetItem(std::forward<K>(key)) << ":"; if constexpr(is_type_value_base_v<V>) { jsonStr_ << GetItem(std::forward<V>(value)) << ","; } else if constexpr(is_type_value_vector_v<V>) { jsonStr_ << "["; for (const auto &it : value) { jsonStr_ << GetItem(it) << ","; } if (!value.empty()) { jsonStr_.seekp(-1, std::ios_base::end); } jsonStr_ << "],"; } return *this; } private: friend class SysEvent; std::string BuildSysEventJson(); static std::string EscapeStringValue(const std::string &value); static std::string EscapeStringValue(const char* value); static std::string EscapeStringValue(char* value); private: std::stringstream jsonStr_; }; } // namespace HiviewDFX } // namespace OHOS #endif // HIVIEW_BASE_SYS_EVENT_H
35.07483
115
0.657874
[ "vector" ]
c843417e8de1c082caf9688007e6f15ca4247dc5
60,212
h
C
src/gallium/drivers/svga/include/svga3d_cmd.h
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
7
2019-09-04T03:44:26.000Z
2022-01-06T02:54:24.000Z
src/gallium/drivers/svga/include/svga3d_cmd.h
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
null
null
null
src/gallium/drivers/svga/include/svga3d_cmd.h
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
3
2021-06-11T23:53:38.000Z
2021-08-31T03:18:34.000Z
/********************************************************** * Copyright 1998-2015 VMware, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, 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. * **********************************************************/ /* * svga3d_cmd.h -- * * SVGA 3d hardware cmd definitions */ #ifndef _SVGA3D_CMD_H_ #define _SVGA3D_CMD_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "svga3d_types.h" /* * Identifiers for commands in the command FIFO. * * IDs between 1000 and 1039 (inclusive) were used by obsolete versions of * the SVGA3D protocol and remain reserved; they should not be used in the * future. * * IDs between 1040 and 1999 (inclusive) are available for use by the * current SVGA3D protocol. * * FIFO clients other than SVGA3D should stay below 1000, or at 2000 * and up. */ typedef enum { SVGA_3D_CMD_LEGACY_BASE = 1000, SVGA_3D_CMD_BASE = 1040, SVGA_3D_CMD_SURFACE_DEFINE = 1040, SVGA_3D_CMD_SURFACE_DESTROY = 1041, SVGA_3D_CMD_SURFACE_COPY = 1042, SVGA_3D_CMD_SURFACE_STRETCHBLT = 1043, SVGA_3D_CMD_SURFACE_DMA = 1044, SVGA_3D_CMD_CONTEXT_DEFINE = 1045, SVGA_3D_CMD_CONTEXT_DESTROY = 1046, SVGA_3D_CMD_SETTRANSFORM = 1047, SVGA_3D_CMD_SETZRANGE = 1048, SVGA_3D_CMD_SETRENDERSTATE = 1049, SVGA_3D_CMD_SETRENDERTARGET = 1050, SVGA_3D_CMD_SETTEXTURESTATE = 1051, SVGA_3D_CMD_SETMATERIAL = 1052, SVGA_3D_CMD_SETLIGHTDATA = 1053, SVGA_3D_CMD_SETLIGHTENABLED = 1054, SVGA_3D_CMD_SETVIEWPORT = 1055, SVGA_3D_CMD_SETCLIPPLANE = 1056, SVGA_3D_CMD_CLEAR = 1057, SVGA_3D_CMD_PRESENT = 1058, SVGA_3D_CMD_SHADER_DEFINE = 1059, SVGA_3D_CMD_SHADER_DESTROY = 1060, SVGA_3D_CMD_SET_SHADER = 1061, SVGA_3D_CMD_SET_SHADER_CONST = 1062, SVGA_3D_CMD_DRAW_PRIMITIVES = 1063, SVGA_3D_CMD_SETSCISSORRECT = 1064, SVGA_3D_CMD_BEGIN_QUERY = 1065, SVGA_3D_CMD_END_QUERY = 1066, SVGA_3D_CMD_WAIT_FOR_QUERY = 1067, SVGA_3D_CMD_PRESENT_READBACK = 1068, SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN = 1069, SVGA_3D_CMD_SURFACE_DEFINE_V2 = 1070, SVGA_3D_CMD_GENERATE_MIPMAPS = 1071, SVGA_3D_CMD_VIDEO_CREATE_DECODER = 1072, SVGA_3D_CMD_VIDEO_DESTROY_DECODER = 1073, SVGA_3D_CMD_VIDEO_CREATE_PROCESSOR = 1074, SVGA_3D_CMD_VIDEO_DESTROY_PROCESSOR = 1075, SVGA_3D_CMD_VIDEO_DECODE_START_FRAME = 1076, SVGA_3D_CMD_VIDEO_DECODE_RENDER = 1077, SVGA_3D_CMD_VIDEO_DECODE_END_FRAME = 1078, SVGA_3D_CMD_VIDEO_PROCESS_FRAME = 1079, SVGA_3D_CMD_ACTIVATE_SURFACE = 1080, SVGA_3D_CMD_DEACTIVATE_SURFACE = 1081, SVGA_3D_CMD_SCREEN_DMA = 1082, SVGA_3D_CMD_DEAD1 = 1083, SVGA_3D_CMD_DEAD2 = 1084, SVGA_3D_CMD_LOGICOPS_BITBLT = 1085, SVGA_3D_CMD_LOGICOPS_TRANSBLT = 1086, SVGA_3D_CMD_LOGICOPS_STRETCHBLT = 1087, SVGA_3D_CMD_LOGICOPS_COLORFILL = 1088, SVGA_3D_CMD_LOGICOPS_ALPHABLEND = 1089, SVGA_3D_CMD_LOGICOPS_CLEARTYPEBLEND = 1090, SVGA_3D_CMD_SET_OTABLE_BASE = 1091, SVGA_3D_CMD_READBACK_OTABLE = 1092, SVGA_3D_CMD_DEFINE_GB_MOB = 1093, SVGA_3D_CMD_DESTROY_GB_MOB = 1094, SVGA_3D_CMD_DEAD3 = 1095, SVGA_3D_CMD_UPDATE_GB_MOB_MAPPING = 1096, SVGA_3D_CMD_DEFINE_GB_SURFACE = 1097, SVGA_3D_CMD_DESTROY_GB_SURFACE = 1098, SVGA_3D_CMD_BIND_GB_SURFACE = 1099, SVGA_3D_CMD_COND_BIND_GB_SURFACE = 1100, SVGA_3D_CMD_UPDATE_GB_IMAGE = 1101, SVGA_3D_CMD_UPDATE_GB_SURFACE = 1102, SVGA_3D_CMD_READBACK_GB_IMAGE = 1103, SVGA_3D_CMD_READBACK_GB_SURFACE = 1104, SVGA_3D_CMD_INVALIDATE_GB_IMAGE = 1105, SVGA_3D_CMD_INVALIDATE_GB_SURFACE = 1106, SVGA_3D_CMD_DEFINE_GB_CONTEXT = 1107, SVGA_3D_CMD_DESTROY_GB_CONTEXT = 1108, SVGA_3D_CMD_BIND_GB_CONTEXT = 1109, SVGA_3D_CMD_READBACK_GB_CONTEXT = 1110, SVGA_3D_CMD_INVALIDATE_GB_CONTEXT = 1111, SVGA_3D_CMD_DEFINE_GB_SHADER = 1112, SVGA_3D_CMD_DESTROY_GB_SHADER = 1113, SVGA_3D_CMD_BIND_GB_SHADER = 1114, SVGA_3D_CMD_SET_OTABLE_BASE64 = 1115, SVGA_3D_CMD_BEGIN_GB_QUERY = 1116, SVGA_3D_CMD_END_GB_QUERY = 1117, SVGA_3D_CMD_WAIT_FOR_GB_QUERY = 1118, SVGA_3D_CMD_NOP = 1119, SVGA_3D_CMD_ENABLE_GART = 1120, SVGA_3D_CMD_DISABLE_GART = 1121, SVGA_3D_CMD_MAP_MOB_INTO_GART = 1122, SVGA_3D_CMD_UNMAP_GART_RANGE = 1123, SVGA_3D_CMD_DEFINE_GB_SCREENTARGET = 1124, SVGA_3D_CMD_DESTROY_GB_SCREENTARGET = 1125, SVGA_3D_CMD_BIND_GB_SCREENTARGET = 1126, SVGA_3D_CMD_UPDATE_GB_SCREENTARGET = 1127, SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL = 1128, SVGA_3D_CMD_INVALIDATE_GB_IMAGE_PARTIAL = 1129, SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE = 1130, SVGA_3D_CMD_GB_SCREEN_DMA = 1131, SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH = 1132, SVGA_3D_CMD_GB_MOB_FENCE = 1133, SVGA_3D_CMD_DEFINE_GB_SURFACE_V2 = 1134, SVGA_3D_CMD_DEFINE_GB_MOB64 = 1135, SVGA_3D_CMD_REDEFINE_GB_MOB64 = 1136, SVGA_3D_CMD_NOP_ERROR = 1137, SVGA_3D_CMD_SET_VERTEX_STREAMS = 1138, SVGA_3D_CMD_SET_VERTEX_DECLS = 1139, SVGA_3D_CMD_SET_VERTEX_DIVISORS = 1140, SVGA_3D_CMD_DRAW = 1141, SVGA_3D_CMD_DRAW_INDEXED = 1142, /* * DX10 Commands */ SVGA_3D_CMD_DX_MIN = 1143, SVGA_3D_CMD_DX_DEFINE_CONTEXT = 1143, SVGA_3D_CMD_DX_DESTROY_CONTEXT = 1144, SVGA_3D_CMD_DX_BIND_CONTEXT = 1145, SVGA_3D_CMD_DX_READBACK_CONTEXT = 1146, SVGA_3D_CMD_DX_INVALIDATE_CONTEXT = 1147, SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER = 1148, SVGA_3D_CMD_DX_SET_SHADER_RESOURCES = 1149, SVGA_3D_CMD_DX_SET_SHADER = 1150, SVGA_3D_CMD_DX_SET_SAMPLERS = 1151, SVGA_3D_CMD_DX_DRAW = 1152, SVGA_3D_CMD_DX_DRAW_INDEXED = 1153, SVGA_3D_CMD_DX_DRAW_INSTANCED = 1154, SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED = 1155, SVGA_3D_CMD_DX_DRAW_AUTO = 1156, SVGA_3D_CMD_DX_SET_INPUT_LAYOUT = 1157, SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS = 1158, SVGA_3D_CMD_DX_SET_INDEX_BUFFER = 1159, SVGA_3D_CMD_DX_SET_TOPOLOGY = 1160, SVGA_3D_CMD_DX_SET_RENDERTARGETS = 1161, SVGA_3D_CMD_DX_SET_BLEND_STATE = 1162, SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE = 1163, SVGA_3D_CMD_DX_SET_RASTERIZER_STATE = 1164, SVGA_3D_CMD_DX_DEFINE_QUERY = 1165, SVGA_3D_CMD_DX_DESTROY_QUERY = 1166, SVGA_3D_CMD_DX_BIND_QUERY = 1167, SVGA_3D_CMD_DX_SET_QUERY_OFFSET = 1168, SVGA_3D_CMD_DX_BEGIN_QUERY = 1169, SVGA_3D_CMD_DX_END_QUERY = 1170, SVGA_3D_CMD_DX_READBACK_QUERY = 1171, SVGA_3D_CMD_DX_SET_PREDICATION = 1172, SVGA_3D_CMD_DX_SET_SOTARGETS = 1173, SVGA_3D_CMD_DX_SET_VIEWPORTS = 1174, SVGA_3D_CMD_DX_SET_SCISSORRECTS = 1175, SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW = 1176, SVGA_3D_CMD_DX_CLEAR_DEPTHSTENCIL_VIEW = 1177, SVGA_3D_CMD_DX_PRED_COPY_REGION = 1178, SVGA_3D_CMD_DX_PRED_COPY = 1179, SVGA_3D_CMD_DX_STRETCHBLT = 1180, SVGA_3D_CMD_DX_GENMIPS = 1181, SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE = 1182, SVGA_3D_CMD_DX_READBACK_SUBRESOURCE = 1183, SVGA_3D_CMD_DX_INVALIDATE_SUBRESOURCE = 1184, SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW = 1185, SVGA_3D_CMD_DX_DESTROY_SHADERRESOURCE_VIEW = 1186, SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW = 1187, SVGA_3D_CMD_DX_DESTROY_RENDERTARGET_VIEW = 1188, SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW = 1189, SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_VIEW = 1190, SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT = 1191, SVGA_3D_CMD_DX_DESTROY_ELEMENTLAYOUT = 1192, SVGA_3D_CMD_DX_DEFINE_BLEND_STATE = 1193, SVGA_3D_CMD_DX_DESTROY_BLEND_STATE = 1194, SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE = 1195, SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_STATE = 1196, SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE = 1197, SVGA_3D_CMD_DX_DESTROY_RASTERIZER_STATE = 1198, SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE = 1199, SVGA_3D_CMD_DX_DESTROY_SAMPLER_STATE = 1200, SVGA_3D_CMD_DX_DEFINE_SHADER = 1201, SVGA_3D_CMD_DX_DESTROY_SHADER = 1202, SVGA_3D_CMD_DX_BIND_SHADER = 1203, SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT = 1204, SVGA_3D_CMD_DX_DESTROY_STREAMOUTPUT = 1205, SVGA_3D_CMD_DX_SET_STREAMOUTPUT = 1206, SVGA_3D_CMD_DX_SET_COTABLE = 1207, SVGA_3D_CMD_DX_READBACK_COTABLE = 1208, SVGA_3D_CMD_DX_BUFFER_COPY = 1209, SVGA_3D_CMD_DX_TRANSFER_FROM_BUFFER = 1210, SVGA_3D_CMD_DX_SURFACE_COPY_AND_READBACK = 1211, SVGA_3D_CMD_DX_MOVE_QUERY = 1212, SVGA_3D_CMD_DX_BIND_ALL_QUERY = 1213, SVGA_3D_CMD_DX_READBACK_ALL_QUERY = 1214, SVGA_3D_CMD_DX_PRED_TRANSFER_FROM_BUFFER = 1215, SVGA_3D_CMD_DX_MOB_FENCE_64 = 1216, SVGA_3D_CMD_DX_BIND_ALL_SHADER = 1217, SVGA_3D_CMD_DX_HINT = 1218, SVGA_3D_CMD_DX_BUFFER_UPDATE = 1219, SVGA_3D_CMD_DX_SET_VS_CONSTANT_BUFFER_OFFSET = 1220, SVGA_3D_CMD_DX_SET_PS_CONSTANT_BUFFER_OFFSET = 1221, SVGA_3D_CMD_DX_SET_GS_CONSTANT_BUFFER_OFFSET = 1222, /* * Reserve some IDs to be used for the DX11 shader types. */ SVGA_3D_CMD_DX_RESERVED1 = 1223, SVGA_3D_CMD_DX_RESERVED2 = 1224, SVGA_3D_CMD_DX_RESERVED3 = 1225, SVGA_3D_CMD_DX_COND_BIND_ALL_SHADER = 1226, SVGA_3D_CMD_DX_MAX = 1227, SVGA_3D_CMD_MAX = 1227, SVGA_3D_CMD_FUTURE_MAX = 3000 } SVGAFifo3dCmdId; /* * FIFO command format definitions: */ /* * The data size header following cmdNum for every 3d command */ typedef #include "vmware_pack_begin.h" struct { uint32 id; uint32 size; } #include "vmware_pack_end.h" SVGA3dCmdHeader; typedef #include "vmware_pack_begin.h" struct { uint32 numMipLevels; } #include "vmware_pack_end.h" SVGA3dSurfaceFace; typedef #include "vmware_pack_begin.h" struct { uint32 sid; SVGA3dSurfaceFlags surfaceFlags; SVGA3dSurfaceFormat format; /* * If surfaceFlags has SVGA3D_SURFACE_CUBEMAP bit set, all SVGA3dSurfaceFace * structures must have the same value of numMipLevels field. * Otherwise, all but the first SVGA3dSurfaceFace structures must have the * numMipLevels set to 0. */ SVGA3dSurfaceFace face[SVGA3D_MAX_SURFACE_FACES]; /* * Followed by an SVGA3dSize structure for each mip level in each face. * * A note on surface sizes: Sizes are always specified in pixels, * even if the true surface size is not a multiple of the minimum * block size of the surface's format. For example, a 3x3x1 DXT1 * compressed texture would actually be stored as a 4x4x1 image in * memory. */ } #include "vmware_pack_end.h" SVGA3dCmdDefineSurface; /* SVGA_3D_CMD_SURFACE_DEFINE */ typedef #include "vmware_pack_begin.h" struct { uint32 sid; SVGA3dSurfaceFlags surfaceFlags; SVGA3dSurfaceFormat format; /* * If surfaceFlags has SVGA3D_SURFACE_CUBEMAP bit set, all SVGA3dSurfaceFace * structures must have the same value of numMipLevels field. * Otherwise, all but the first SVGA3dSurfaceFace structures must have the * numMipLevels set to 0. */ SVGA3dSurfaceFace face[SVGA3D_MAX_SURFACE_FACES]; uint32 multisampleCount; SVGA3dTextureFilter autogenFilter; /* * Followed by an SVGA3dSize structure for each mip level in each face. * * A note on surface sizes: Sizes are always specified in pixels, * even if the true surface size is not a multiple of the minimum * block size of the surface's format. For example, a 3x3x1 DXT1 * compressed texture would actually be stored as a 4x4x1 image in * memory. */ } #include "vmware_pack_end.h" SVGA3dCmdDefineSurface_v2; /* SVGA_3D_CMD_SURFACE_DEFINE_V2 */ typedef #include "vmware_pack_begin.h" struct { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdDestroySurface; /* SVGA_3D_CMD_SURFACE_DESTROY */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdDefineContext; /* SVGA_3D_CMD_CONTEXT_DEFINE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyContext; /* SVGA_3D_CMD_CONTEXT_DESTROY */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dClearFlag clearFlag; uint32 color; float depth; uint32 stencil; /* Followed by variable number of SVGA3dRect structures */ } #include "vmware_pack_end.h" SVGA3dCmdClear; /* SVGA_3D_CMD_CLEAR */ typedef #include "vmware_pack_begin.h" struct { SVGA3dLightType type; SVGA3dBool inWorldSpace; float diffuse[4]; float specular[4]; float ambient[4]; float position[4]; float direction[4]; float range; float falloff; float attenuation0; float attenuation1; float attenuation2; float theta; float phi; } #include "vmware_pack_end.h" SVGA3dLightData; typedef #include "vmware_pack_begin.h" struct { uint32 sid; /* Followed by variable number of SVGA3dCopyRect structures */ } #include "vmware_pack_end.h" SVGA3dCmdPresent; /* SVGA_3D_CMD_PRESENT */ typedef #include "vmware_pack_begin.h" struct { SVGA3dRenderStateName state; union { uint32 uintValue; float floatValue; }; } #include "vmware_pack_end.h" SVGA3dRenderState; typedef #include "vmware_pack_begin.h" struct { uint32 cid; /* Followed by variable number of SVGA3dRenderState structures */ } #include "vmware_pack_end.h" SVGA3dCmdSetRenderState; /* SVGA_3D_CMD_SETRENDERSTATE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dRenderTargetType type; SVGA3dSurfaceImageId target; } #include "vmware_pack_end.h" SVGA3dCmdSetRenderTarget; /* SVGA_3D_CMD_SETRENDERTARGET */ typedef #include "vmware_pack_begin.h" struct { SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dest; /* Followed by variable number of SVGA3dCopyBox structures */ } #include "vmware_pack_end.h" SVGA3dCmdSurfaceCopy; /* SVGA_3D_CMD_SURFACE_COPY */ typedef #include "vmware_pack_begin.h" struct { SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dest; SVGA3dBox boxSrc; SVGA3dBox boxDest; SVGA3dStretchBltMode mode; } #include "vmware_pack_end.h" SVGA3dCmdSurfaceStretchBlt; /* SVGA_3D_CMD_SURFACE_STRETCHBLT */ typedef #include "vmware_pack_begin.h" struct { /* * If the discard flag is present in a surface DMA operation, the host may * discard the contents of the current mipmap level and face of the target * surface before applying the surface DMA contents. */ uint32 discard : 1; /* * If the unsynchronized flag is present, the host may perform this upload * without syncing to pending reads on this surface. */ uint32 unsynchronized : 1; /* * Guests *MUST* set the reserved bits to 0 before submitting the command * suffix as future flags may occupy these bits. */ uint32 reserved : 30; } #include "vmware_pack_end.h" SVGA3dSurfaceDMAFlags; typedef #include "vmware_pack_begin.h" struct { SVGAGuestImage guest; SVGA3dSurfaceImageId host; SVGA3dTransferType transfer; /* * Followed by variable number of SVGA3dCopyBox structures. For consistency * in all clipping logic and coordinate translation, we define the * "source" in each copyBox as the guest image and the * "destination" as the host image, regardless of transfer * direction. * * For efficiency, the SVGA3D device is free to copy more data than * specified. For example, it may round copy boxes outwards such * that they lie on particular alignment boundaries. */ } #include "vmware_pack_end.h" SVGA3dCmdSurfaceDMA; /* SVGA_3D_CMD_SURFACE_DMA */ /* * SVGA3dCmdSurfaceDMASuffix -- * * This is a command suffix that will appear after a SurfaceDMA command in * the FIFO. It contains some extra information that hosts may use to * optimize performance or protect the guest. This suffix exists to preserve * backwards compatibility while also allowing for new functionality to be * implemented. */ typedef #include "vmware_pack_begin.h" struct { uint32 suffixSize; /* * The maximum offset is used to determine the maximum offset from the * guestPtr base address that will be accessed or written to during this * surfaceDMA. If the suffix is supported, the host will respect this * boundary while performing surface DMAs. * * Defaults to MAX_UINT32 */ uint32 maximumOffset; /* * A set of flags that describes optimizations that the host may perform * while performing this surface DMA operation. The guest should never rely * on behaviour that is different when these flags are set for correctness. * * Defaults to 0 */ SVGA3dSurfaceDMAFlags flags; } #include "vmware_pack_end.h" SVGA3dCmdSurfaceDMASuffix; /* * SVGA_3D_CMD_DRAW_PRIMITIVES -- * * This command is the SVGA3D device's generic drawing entry point. * It can draw multiple ranges of primitives, optionally using an * index buffer, using an arbitrary collection of vertex buffers. * * Each SVGA3dVertexDecl defines a distinct vertex array to bind * during this draw call. The declarations specify which surface * the vertex data lives in, what that vertex data is used for, * and how to interpret it. * * Each SVGA3dPrimitiveRange defines a collection of primitives * to render using the same vertex arrays. An index buffer is * optional. */ typedef #include "vmware_pack_begin.h" struct { /* * A range hint is an optional specification for the range of indices * in an SVGA3dArray that will be used. If 'last' is zero, it is assumed * that the entire array will be used. * * These are only hints. The SVGA3D device may use them for * performance optimization if possible, but it's also allowed to * ignore these values. */ uint32 first; uint32 last; } #include "vmware_pack_end.h" SVGA3dArrayRangeHint; typedef #include "vmware_pack_begin.h" struct { /* * Define the origin and shape of a vertex or index array. Both * 'offset' and 'stride' are in bytes. The provided surface will be * reinterpreted as a flat array of bytes in the same format used * by surface DMA operations. To avoid unnecessary conversions, the * surface should be created with the SVGA3D_BUFFER format. * * Index 0 in the array starts 'offset' bytes into the surface. * Index 1 begins at byte 'offset + stride', etc. Array indices may * not be negative. */ uint32 surfaceId; uint32 offset; uint32 stride; } #include "vmware_pack_end.h" SVGA3dArray; typedef #include "vmware_pack_begin.h" struct { /* * Describe a vertex array's data type, and define how it is to be * used by the fixed function pipeline or the vertex shader. It * isn't useful to have two VertexDecls with the same * VertexArrayIdentity in one draw call. */ SVGA3dDeclType type; SVGA3dDeclMethod method; SVGA3dDeclUsage usage; uint32 usageIndex; } #include "vmware_pack_end.h" SVGA3dVertexArrayIdentity; typedef #include "vmware_pack_begin.h" struct SVGA3dVertexDecl { SVGA3dVertexArrayIdentity identity; SVGA3dArray array; SVGA3dArrayRangeHint rangeHint; } #include "vmware_pack_end.h" SVGA3dVertexDecl; typedef #include "vmware_pack_begin.h" struct SVGA3dPrimitiveRange { /* * Define a group of primitives to render, from sequential indices. * * The value of 'primitiveType' and 'primitiveCount' imply the * total number of vertices that will be rendered. */ SVGA3dPrimitiveType primType; uint32 primitiveCount; /* * Optional index buffer. If indexArray.surfaceId is * SVGA3D_INVALID_ID, we render without an index buffer. Rendering * without an index buffer is identical to rendering with an index * buffer containing the sequence [0, 1, 2, 3, ...]. * * If an index buffer is in use, indexWidth specifies the width in * bytes of each index value. It must be less than or equal to * indexArray.stride. * * (Currently, the SVGA3D device requires index buffers to be tightly * packed. In other words, indexWidth == indexArray.stride) */ SVGA3dArray indexArray; uint32 indexWidth; /* * Optional index bias. This number is added to all indices from * indexArray before they are used as vertex array indices. This * can be used in multiple ways: * * - When not using an indexArray, this bias can be used to * specify where in the vertex arrays to begin rendering. * * - A positive number here is equivalent to increasing the * offset in each vertex array. * * - A negative number can be used to render using a small * vertex array and an index buffer that contains large * values. This may be used by some applications that * crop a vertex buffer without modifying their index * buffer. * * Note that rendering with a negative bias value may be slower and * use more memory than rendering with a positive or zero bias. */ int32 indexBias; } #include "vmware_pack_end.h" SVGA3dPrimitiveRange; typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 numVertexDecls; uint32 numRanges; /* * There are two variable size arrays after the * SVGA3dCmdDrawPrimitives structure. In order, * they are: * * 1. SVGA3dVertexDecl, quantity 'numVertexDecls', but no more than * SVGA3D_MAX_VERTEX_ARRAYS; * 2. SVGA3dPrimitiveRange, quantity 'numRanges', but no more than * SVGA3D_MAX_DRAW_PRIMITIVE_RANGES; * 3. Optionally, SVGA3dVertexDivisor, quantity 'numVertexDecls' (contains * the frequency divisor for the corresponding vertex decl). */ } #include "vmware_pack_end.h" SVGA3dCmdDrawPrimitives; /* SVGA_3D_CMD_DRAWPRIMITIVES */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 primitiveCount; /* How many primitives to render */ uint32 startVertexLocation; /* Which vertex do we start rendering at. */ uint8 primitiveType; /* SVGA3dPrimitiveType */ uint8 padding[3]; } #include "vmware_pack_end.h" SVGA3dCmdDraw; typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint8 primitiveType; /* SVGA3dPrimitiveType */ uint32 indexBufferSid; /* Valid index buffer sid. */ uint32 indexBufferOffset; /* Byte offset into the vertex buffer, almost */ /* always 0 for DX9 guests, non-zero for OpenGL */ /* guests. We can't represent non-multiple of */ /* stride offsets in D3D9Renderer... */ uint8 indexBufferStride; /* Allowable values = 1, 2, or 4 */ int32 baseVertexLocation; /* Bias applied to the index when selecting a */ /* vertex from the streams, may be negative */ uint32 primitiveCount; /* How many primitives to render */ uint32 pad0; uint16 pad1; } #include "vmware_pack_end.h" SVGA3dCmdDrawIndexed; typedef #include "vmware_pack_begin.h" struct { /* * Describe a vertex array's data type, and define how it is to be * used by the fixed function pipeline or the vertex shader. It * isn't useful to have two VertexDecls with the same * VertexArrayIdentity in one draw call. */ uint16 streamOffset; uint8 stream; uint8 type; /* SVGA3dDeclType */ uint8 method; /* SVGA3dDeclMethod */ uint8 usage; /* SVGA3dDeclUsage */ uint8 usageIndex; uint8 padding; } #include "vmware_pack_end.h" SVGA3dVertexElement; /* * Should the vertex element respect the stream value? The high bit of the * stream should be set to indicate that the stream should be respected. If * the high bit is not set, the stream will be ignored and replaced by the index * of the position of the currently considered vertex element. * * All guests should set this bit and correctly specify the stream going * forward. */ #define SVGA3D_VERTEX_ELEMENT_RESPECT_STREAM (1 << 7) typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 numElements; /* * Followed by numElements SVGA3dVertexElement structures. * * If numElements < SVGA3D_MAX_VERTEX_ARRAYS, the remaining elements * are cleared and will not be used by following draws. */ } #include "vmware_pack_end.h" SVGA3dCmdSetVertexDecls; typedef #include "vmware_pack_begin.h" struct { uint32 sid; uint32 stride; uint32 offset; } #include "vmware_pack_end.h" SVGA3dVertexStream; typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 numStreams; /* * Followed by numStream SVGA3dVertexStream structures. * * If numStreams < SVGA3D_MAX_VERTEX_ARRAYS, the remaining streams * are cleared and will not be used by following draws. */ } #include "vmware_pack_end.h" SVGA3dCmdSetVertexStreams; typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 numDivisors; } #include "vmware_pack_end.h" SVGA3dCmdSetVertexDivisors; typedef #include "vmware_pack_begin.h" struct { uint32 stage; SVGA3dTextureStateName name; union { uint32 value; float floatValue; }; } #include "vmware_pack_end.h" SVGA3dTextureState; typedef #include "vmware_pack_begin.h" struct { uint32 cid; /* Followed by variable number of SVGA3dTextureState structures */ } #include "vmware_pack_end.h" SVGA3dCmdSetTextureState; /* SVGA_3D_CMD_SETTEXTURESTATE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dTransformType type; float matrix[16]; } #include "vmware_pack_end.h" SVGA3dCmdSetTransform; /* SVGA_3D_CMD_SETTRANSFORM */ typedef #include "vmware_pack_begin.h" struct { float min; float max; } #include "vmware_pack_end.h" SVGA3dZRange; typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dZRange zRange; } #include "vmware_pack_end.h" SVGA3dCmdSetZRange; /* SVGA_3D_CMD_SETZRANGE */ typedef #include "vmware_pack_begin.h" struct { float diffuse[4]; float ambient[4]; float specular[4]; float emissive[4]; float shininess; } #include "vmware_pack_end.h" SVGA3dMaterial; typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dFace face; SVGA3dMaterial material; } #include "vmware_pack_end.h" SVGA3dCmdSetMaterial; /* SVGA_3D_CMD_SETMATERIAL */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 index; SVGA3dLightData data; } #include "vmware_pack_end.h" SVGA3dCmdSetLightData; /* SVGA_3D_CMD_SETLIGHTDATA */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 index; uint32 enabled; } #include "vmware_pack_end.h" SVGA3dCmdSetLightEnabled; /* SVGA_3D_CMD_SETLIGHTENABLED */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dRect rect; } #include "vmware_pack_end.h" SVGA3dCmdSetViewport; /* SVGA_3D_CMD_SETVIEWPORT */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dRect rect; } #include "vmware_pack_end.h" SVGA3dCmdSetScissorRect; /* SVGA_3D_CMD_SETSCISSORRECT */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 index; float plane[4]; } #include "vmware_pack_end.h" SVGA3dCmdSetClipPlane; /* SVGA_3D_CMD_SETCLIPPLANE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 shid; SVGA3dShaderType type; /* Followed by variable number of DWORDs for shader bycode */ } #include "vmware_pack_end.h" SVGA3dCmdDefineShader; /* SVGA_3D_CMD_SHADER_DEFINE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 shid; SVGA3dShaderType type; } #include "vmware_pack_end.h" SVGA3dCmdDestroyShader; /* SVGA_3D_CMD_SHADER_DESTROY */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 reg; /* register number */ SVGA3dShaderType type; SVGA3dShaderConstType ctype; uint32 values[4]; /* * Followed by a variable number of additional values. */ } #include "vmware_pack_end.h" SVGA3dCmdSetShaderConst; /* SVGA_3D_CMD_SET_SHADER_CONST */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dShaderType type; uint32 shid; } #include "vmware_pack_end.h" SVGA3dCmdSetShader; /* SVGA_3D_CMD_SET_SHADER */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dQueryType type; } #include "vmware_pack_end.h" SVGA3dCmdBeginQuery; /* SVGA_3D_CMD_BEGIN_QUERY */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dQueryType type; SVGAGuestPtr guestResult; /* Points to an SVGA3dQueryResult structure */ } #include "vmware_pack_end.h" SVGA3dCmdEndQuery; /* SVGA_3D_CMD_END_QUERY */ /* * SVGA3D_CMD_WAIT_FOR_QUERY -- * * Will read the SVGA3dQueryResult structure pointed to by guestResult, * and if the state member is set to anything else than * SVGA3D_QUERYSTATE_PENDING, this command will always be a no-op. * * Otherwise, in addition to the query explicitly waited for, * All queries with the same type and issued with the same cid, for which * an SVGA_3D_CMD_END_QUERY command has previously been sent, will * be finished after execution of this command. * * A query will be identified by the gmrId and offset of the guestResult * member. If the device can't find an SVGA_3D_CMD_END_QUERY that has * been sent previously with an indentical gmrId and offset, it will * effectively end all queries with an identical type issued with the * same cid, and the SVGA3dQueryResult structure pointed to by * guestResult will not be written to. This property can be used to * implement a query barrier for a given cid and query type. */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; /* Same parameters passed to END_QUERY */ SVGA3dQueryType type; SVGAGuestPtr guestResult; } #include "vmware_pack_end.h" SVGA3dCmdWaitForQuery; /* SVGA_3D_CMD_WAIT_FOR_QUERY */ typedef #include "vmware_pack_begin.h" struct { uint32 totalSize; /* Set by guest before query is ended. */ SVGA3dQueryState state; /* Set by host or guest. See SVGA3dQueryState. */ union { /* Set by host on exit from PENDING state */ uint32 result32; uint32 queryCookie; /* May be used to identify which QueryGetData this result corresponds to. */ }; } #include "vmware_pack_end.h" SVGA3dQueryResult; /* * SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN -- * * This is a blit from an SVGA3D surface to a Screen Object. * This blit must be directed at a specific screen. * * The blit copies from a rectangular region of an SVGA3D surface * image to a rectangular region of a screen. * * This command takes an optional variable-length list of clipping * rectangles after the body of the command. If no rectangles are * specified, there is no clipping region. The entire destRect is * drawn to. If one or more rectangles are included, they describe * a clipping region. The clip rectangle coordinates are measured * relative to the top-left corner of destRect. * * The srcImage must be from mip=0 face=0. * * This supports scaling if the src and dest are of different sizes. * * Availability: * SVGA_FIFO_CAP_SCREEN_OBJECT */ typedef #include "vmware_pack_begin.h" struct { SVGA3dSurfaceImageId srcImage; SVGASignedRect srcRect; uint32 destScreenId; /* Screen Object ID */ SVGASignedRect destRect; /* Clipping: zero or more SVGASignedRects follow */ } #include "vmware_pack_end.h" SVGA3dCmdBlitSurfaceToScreen; /* SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN */ typedef #include "vmware_pack_begin.h" struct { uint32 sid; SVGA3dTextureFilter filter; } #include "vmware_pack_end.h" SVGA3dCmdGenerateMipmaps; /* SVGA_3D_CMD_GENERATE_MIPMAPS */ typedef #include "vmware_pack_begin.h" struct { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdActivateSurface; /* SVGA_3D_CMD_ACTIVATE_SURFACE */ typedef #include "vmware_pack_begin.h" struct { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdDeactivateSurface; /* SVGA_3D_CMD_DEACTIVATE_SURFACE */ /* * Screen DMA command * * Available with SVGA_FIFO_CAP_SCREEN_OBJECT_2. The SVGA_CAP_3D device * cap bit is not required. * * - refBuffer and destBuffer are 32bit BGRX; refBuffer and destBuffer could * be different, but it is required that guest makes sure refBuffer has * exactly the same contents that were written to when last time screen DMA * command is received by host. * * - changemap is generated by lib/blit, and it has the changes from last * received screen DMA or more. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdScreenDMA { uint32 screenId; SVGAGuestImage refBuffer; SVGAGuestImage destBuffer; SVGAGuestImage changeMap; } #include "vmware_pack_end.h" SVGA3dCmdScreenDMA; /* SVGA_3D_CMD_SCREEN_DMA */ /* * Logic ops */ #define SVGA3D_LOTRANSBLT_HONORALPHA (0x01) #define SVGA3D_LOSTRETCHBLT_MIRRORX (0x01) #define SVGA3D_LOSTRETCHBLT_MIRRORY (0x02) #define SVGA3D_LOALPHABLEND_SRCHASALPHA (0x01) typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsBitBlt { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dst; SVGA3dLogicOp logicOp; /* Followed by variable number of SVGA3dCopyBox structures */ } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsBitBlt; /* SVGA_3D_CMD_LOGICOPS_BITBLT */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsTransBlt { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dst; uint32 color; uint32 flags; SVGA3dBox srcBox; SVGA3dBox dstBox; } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsTransBlt; /* SVGA_3D_CMD_LOGICOPS_TRANSBLT */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsStretchBlt { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dst; uint16 mode; uint16 flags; SVGA3dBox srcBox; SVGA3dBox dstBox; } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsStretchBlt; /* SVGA_3D_CMD_LOGICOPS_STRETCHBLT */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsColorFill { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId dst; uint32 color; SVGA3dLogicOp logicOp; /* Followed by variable number of SVGA3dRect structures. */ } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsColorFill; /* SVGA_3D_CMD_LOGICOPS_COLORFILL */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsAlphaBlend { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId src; SVGA3dSurfaceImageId dst; uint32 alphaVal; uint32 flags; SVGA3dBox srcBox; SVGA3dBox dstBox; } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsAlphaBlend; /* SVGA_3D_CMD_LOGICOPS_ALPHABLEND */ #define SVGA3D_CLEARTYPE_INVALID_GAMMA_INDEX 0xFFFFFFFF #define SVGA3D_CLEARTYPE_GAMMA_WIDTH 512 #define SVGA3D_CLEARTYPE_GAMMA_HEIGHT 16 typedef #include "vmware_pack_begin.h" struct SVGA3dCmdLogicOpsClearTypeBlend { /* * All LogicOps surfaces are one-level * surfaces so mipmap & face should always * be zero. */ SVGA3dSurfaceImageId tmp; SVGA3dSurfaceImageId dst; SVGA3dSurfaceImageId gammaSurf; SVGA3dSurfaceImageId alphaSurf; uint32 gamma; uint32 color; uint32 color2; int32 alphaOffsetX; int32 alphaOffsetY; /* Followed by variable number of SVGA3dBox structures */ } #include "vmware_pack_end.h" SVGA3dCmdLogicOpsClearTypeBlend; /* SVGA_3D_CMD_LOGICOPS_CLEARTYPEBLEND */ /* * Guest-backed objects definitions. */ typedef #include "vmware_pack_begin.h" struct { SVGAMobFormat ptDepth; uint32 sizeInBytes; PPN64 base; } #include "vmware_pack_end.h" SVGAOTableMobEntry; #define SVGA3D_OTABLE_MOB_ENTRY_SIZE (sizeof(SVGAOTableMobEntry)) typedef #include "vmware_pack_begin.h" struct { SVGA3dSurfaceFormat format; SVGA3dSurfaceFlags surfaceFlags; uint32 numMipLevels; uint32 multisampleCount; SVGA3dTextureFilter autogenFilter; SVGA3dSize size; SVGAMobId mobid; uint32 arraySize; uint32 mobPitch; uint32 pad[5]; } #include "vmware_pack_end.h" SVGAOTableSurfaceEntry; #define SVGA3D_OTABLE_SURFACE_ENTRY_SIZE (sizeof(SVGAOTableSurfaceEntry)) typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGAMobId mobid; } #include "vmware_pack_end.h" SVGAOTableContextEntry; #define SVGA3D_OTABLE_CONTEXT_ENTRY_SIZE (sizeof(SVGAOTableContextEntry)) typedef #include "vmware_pack_begin.h" struct { SVGA3dShaderType type; uint32 sizeInBytes; uint32 offsetInBytes; SVGAMobId mobid; } #include "vmware_pack_end.h" SVGAOTableShaderEntry; #define SVGA3D_OTABLE_SHADER_ENTRY_SIZE (sizeof(SVGAOTableShaderEntry)) #define SVGA_STFLAG_PRIMARY (1 << 0) typedef uint32 SVGAScreenTargetFlags; typedef #include "vmware_pack_begin.h" struct { SVGA3dSurfaceImageId image; uint32 width; uint32 height; int32 xRoot; int32 yRoot; SVGAScreenTargetFlags flags; uint32 dpi; uint32 pad[7]; } #include "vmware_pack_end.h" SVGAOTableScreenTargetEntry; #define SVGA3D_OTABLE_SCREEN_TARGET_ENTRY_SIZE \ (sizeof(SVGAOTableScreenTargetEntry)) typedef #include "vmware_pack_begin.h" struct { float value[4]; } #include "vmware_pack_end.h" SVGA3dShaderConstFloat; typedef #include "vmware_pack_begin.h" struct { int32 value[4]; } #include "vmware_pack_end.h" SVGA3dShaderConstInt; typedef #include "vmware_pack_begin.h" struct { uint32 value; } #include "vmware_pack_end.h" SVGA3dShaderConstBool; typedef #include "vmware_pack_begin.h" struct { uint16 streamOffset; uint8 stream; uint8 type; uint8 methodUsage; uint8 usageIndex; } #include "vmware_pack_end.h" SVGAGBVertexElement; typedef #include "vmware_pack_begin.h" struct { uint32 sid; uint16 stride; uint32 offset; } #include "vmware_pack_end.h" SVGAGBVertexStream; typedef #include "vmware_pack_begin.h" struct { SVGA3dRect viewport; SVGA3dRect scissorRect; SVGA3dZRange zRange; SVGA3dSurfaceImageId renderTargets[SVGA3D_RT_MAX]; SVGAGBVertexElement decl1[4]; uint32 renderStates[SVGA3D_RS_MAX]; SVGAGBVertexElement decl2[18]; uint32 pad0[2]; struct { SVGA3dFace face; SVGA3dMaterial material; } material; float clipPlanes[SVGA3D_NUM_CLIPPLANES][4]; float matrices[SVGA3D_TRANSFORM_MAX][16]; SVGA3dBool lightEnabled[SVGA3D_NUM_LIGHTS]; SVGA3dLightData lightData[SVGA3D_NUM_LIGHTS]; /* * Shaders currently bound */ uint32 shaders[SVGA3D_NUM_SHADERTYPE_PREDX]; SVGAGBVertexElement decl3[10]; uint32 pad1[3]; uint32 occQueryActive; uint32 occQueryValue; /* * Int/Bool Shader constants */ SVGA3dShaderConstInt pShaderIValues[SVGA3D_CONSTINTREG_MAX]; SVGA3dShaderConstInt vShaderIValues[SVGA3D_CONSTINTREG_MAX]; uint16 pShaderBValues; uint16 vShaderBValues; SVGAGBVertexStream streams[SVGA3D_MAX_VERTEX_ARRAYS]; SVGA3dVertexDivisor divisors[SVGA3D_MAX_VERTEX_ARRAYS]; uint32 numVertexDecls; uint32 numVertexStreams; uint32 numVertexDivisors; uint32 pad2[30]; /* * Texture Stages * * SVGA3D_TS_INVALID through SVGA3D_TS_CONSTANT are in the * textureStages array. * SVGA3D_TS_COLOR_KEY is in tsColorKey. */ uint32 tsColorKey[SVGA3D_NUM_TEXTURE_UNITS]; uint32 textureStages[SVGA3D_NUM_TEXTURE_UNITS][SVGA3D_TS_CONSTANT + 1]; uint32 tsColorKeyEnable[SVGA3D_NUM_TEXTURE_UNITS]; /* * Float Shader constants. */ SVGA3dShaderConstFloat pShaderFValues[SVGA3D_CONSTREG_MAX]; SVGA3dShaderConstFloat vShaderFValues[SVGA3D_CONSTREG_MAX]; } #include "vmware_pack_end.h" SVGAGBContextData; #define SVGA3D_CONTEXT_DATA_SIZE (sizeof(SVGAGBContextData)) /* * SVGA3dCmdSetOTableBase -- * * This command allows the guest to specify the base PPN of the * specified object table. */ typedef #include "vmware_pack_begin.h" struct { SVGAOTableType type; PPN baseAddress; uint32 sizeInBytes; uint32 validSizeInBytes; SVGAMobFormat ptDepth; } #include "vmware_pack_end.h" SVGA3dCmdSetOTableBase; /* SVGA_3D_CMD_SET_OTABLE_BASE */ typedef #include "vmware_pack_begin.h" struct { SVGAOTableType type; PPN64 baseAddress; uint32 sizeInBytes; uint32 validSizeInBytes; SVGAMobFormat ptDepth; } #include "vmware_pack_end.h" SVGA3dCmdSetOTableBase64; /* SVGA_3D_CMD_SET_OTABLE_BASE64 */ typedef #include "vmware_pack_begin.h" struct { SVGAOTableType type; } #include "vmware_pack_end.h" SVGA3dCmdReadbackOTable; /* SVGA_3D_CMD_READBACK_OTABLE */ /* * Define a memory object (Mob) in the OTable. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDefineGBMob { SVGAMobId mobid; SVGAMobFormat ptDepth; PPN base; uint32 sizeInBytes; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBMob; /* SVGA_3D_CMD_DEFINE_GB_MOB */ /* * Destroys an object in the OTable. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDestroyGBMob { SVGAMobId mobid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyGBMob; /* SVGA_3D_CMD_DESTROY_GB_MOB */ /* * Define a memory object (Mob) in the OTable with a PPN64 base. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDefineGBMob64 { SVGAMobId mobid; SVGAMobFormat ptDepth; PPN64 base; uint32 sizeInBytes; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBMob64; /* SVGA_3D_CMD_DEFINE_GB_MOB64 */ /* * Redefine an object in the OTable with PPN64 base. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdRedefineGBMob64 { SVGAMobId mobid; SVGAMobFormat ptDepth; PPN64 base; uint32 sizeInBytes; } #include "vmware_pack_end.h" SVGA3dCmdRedefineGBMob64; /* SVGA_3D_CMD_REDEFINE_GB_MOB64 */ /* * Notification that the page tables have been modified. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdUpdateGBMobMapping { SVGAMobId mobid; } #include "vmware_pack_end.h" SVGA3dCmdUpdateGBMobMapping; /* SVGA_3D_CMD_UPDATE_GB_MOB_MAPPING */ /* * Define a guest-backed surface. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDefineGBSurface { uint32 sid; SVGA3dSurfaceFlags surfaceFlags; SVGA3dSurfaceFormat format; uint32 numMipLevels; uint32 multisampleCount; SVGA3dTextureFilter autogenFilter; SVGA3dSize size; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBSurface; /* SVGA_3D_CMD_DEFINE_GB_SURFACE */ /* * Destroy a guest-backed surface. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDestroyGBSurface { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyGBSurface; /* SVGA_3D_CMD_DESTROY_GB_SURFACE */ /* * Bind a guest-backed surface to a mob. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdBindGBSurface { uint32 sid; SVGAMobId mobid; } #include "vmware_pack_end.h" SVGA3dCmdBindGBSurface; /* SVGA_3D_CMD_BIND_GB_SURFACE */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdBindGBSurfaceWithPitch { uint32 sid; SVGAMobId mobid; uint32 baseLevelPitch; } #include "vmware_pack_end.h" SVGA3dCmdBindGBSurfaceWithPitch; /* SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH */ /* * Conditionally bind a mob to a guest-backed surface if testMobid * matches the currently bound mob. Optionally issue a * readback/update on the surface while it is still bound to the old * mobid if the mobid is changed by this command. */ #define SVGA3D_COND_BIND_GB_SURFACE_FLAG_READBACK (1 << 0) #define SVGA3D_COND_BIND_GB_SURFACE_FLAG_UPDATE (1 << 1) typedef #include "vmware_pack_begin.h" struct SVGA3dCmdCondBindGBSurface { uint32 sid; SVGAMobId testMobid; SVGAMobId mobid; uint32 flags; } #include "vmware_pack_end.h" SVGA3dCmdCondBindGBSurface; /* SVGA_3D_CMD_COND_BIND_GB_SURFACE */ /* * Update an image in a guest-backed surface. * (Inform the device that the guest-contents have been updated.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdUpdateGBImage { SVGA3dSurfaceImageId image; SVGA3dBox box; } #include "vmware_pack_end.h" SVGA3dCmdUpdateGBImage; /* SVGA_3D_CMD_UPDATE_GB_IMAGE */ /* * Update an entire guest-backed surface. * (Inform the device that the guest-contents have been updated.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdUpdateGBSurface { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdUpdateGBSurface; /* SVGA_3D_CMD_UPDATE_GB_SURFACE */ /* * Readback an image in a guest-backed surface. * (Request the device to flush the dirty contents into the guest.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdReadbackGBImage { SVGA3dSurfaceImageId image; } #include "vmware_pack_end.h" SVGA3dCmdReadbackGBImage; /* SVGA_3D_CMD_READBACK_GB_IMAGE */ /* * Readback an entire guest-backed surface. * (Request the device to flush the dirty contents into the guest.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdReadbackGBSurface { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdReadbackGBSurface; /* SVGA_3D_CMD_READBACK_GB_SURFACE */ /* * Readback a sub rect of an image in a guest-backed surface. After * issuing this command the driver is required to issue an update call * of the same region before issuing any other commands that reference * this surface or rendering is not guaranteed. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdReadbackGBImagePartial { SVGA3dSurfaceImageId image; SVGA3dBox box; uint32 invertBox; } #include "vmware_pack_end.h" SVGA3dCmdReadbackGBImagePartial; /* SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL */ /* * Invalidate an image in a guest-backed surface. * (Notify the device that the contents can be lost.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdInvalidateGBImage { SVGA3dSurfaceImageId image; } #include "vmware_pack_end.h" SVGA3dCmdInvalidateGBImage; /* SVGA_3D_CMD_INVALIDATE_GB_IMAGE */ /* * Invalidate an entire guest-backed surface. * (Notify the device that the contents if all images can be lost.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdInvalidateGBSurface { uint32 sid; } #include "vmware_pack_end.h" SVGA3dCmdInvalidateGBSurface; /* SVGA_3D_CMD_INVALIDATE_GB_SURFACE */ /* * Invalidate a sub rect of an image in a guest-backed surface. After * issuing this command the driver is required to issue an update call * of the same region before issuing any other commands that reference * this surface or rendering is not guaranteed. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdInvalidateGBImagePartial { SVGA3dSurfaceImageId image; SVGA3dBox box; uint32 invertBox; } #include "vmware_pack_end.h" SVGA3dCmdInvalidateGBImagePartial; /* SVGA_3D_CMD_INVALIDATE_GB_IMAGE_PARTIAL */ /* * Define a guest-backed context. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDefineGBContext { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBContext; /* SVGA_3D_CMD_DEFINE_GB_CONTEXT */ /* * Destroy a guest-backed context. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDestroyGBContext { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyGBContext; /* SVGA_3D_CMD_DESTROY_GB_CONTEXT */ /* * Bind a guest-backed context. * * validContents should be set to 0 for new contexts, * and 1 if this is an old context which is getting paged * back on to the device. * * For new contexts, it is recommended that the driver * issue commands to initialize all interesting state * prior to rendering. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdBindGBContext { uint32 cid; SVGAMobId mobid; uint32 validContents; } #include "vmware_pack_end.h" SVGA3dCmdBindGBContext; /* SVGA_3D_CMD_BIND_GB_CONTEXT */ /* * Readback a guest-backed context. * (Request that the device flush the contents back into guest memory.) */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdReadbackGBContext { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdReadbackGBContext; /* SVGA_3D_CMD_READBACK_GB_CONTEXT */ /* * Invalidate a guest-backed context. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdInvalidateGBContext { uint32 cid; } #include "vmware_pack_end.h" SVGA3dCmdInvalidateGBContext; /* SVGA_3D_CMD_INVALIDATE_GB_CONTEXT */ /* * Define a guest-backed shader. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDefineGBShader { uint32 shid; SVGA3dShaderType type; uint32 sizeInBytes; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBShader; /* SVGA_3D_CMD_DEFINE_GB_SHADER */ /* * Bind a guest-backed shader. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdBindGBShader { uint32 shid; SVGAMobId mobid; uint32 offsetInBytes; } #include "vmware_pack_end.h" SVGA3dCmdBindGBShader; /* SVGA_3D_CMD_BIND_GB_SHADER */ /* * Destroy a guest-backed shader. */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdDestroyGBShader { uint32 shid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyGBShader; /* SVGA_3D_CMD_DESTROY_GB_SHADER */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; uint32 regStart; SVGA3dShaderType shaderType; SVGA3dShaderConstType constType; /* * Followed by a variable number of shader constants. * * Note that FLOAT and INT constants are 4-dwords in length, while * BOOL constants are 1-dword in length. */ } #include "vmware_pack_end.h" SVGA3dCmdSetGBShaderConstInline; /* SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dQueryType type; } #include "vmware_pack_end.h" SVGA3dCmdBeginGBQuery; /* SVGA_3D_CMD_BEGIN_GB_QUERY */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dQueryType type; SVGAMobId mobid; uint32 offset; } #include "vmware_pack_end.h" SVGA3dCmdEndGBQuery; /* SVGA_3D_CMD_END_GB_QUERY */ /* * SVGA_3D_CMD_WAIT_FOR_GB_QUERY -- * * The semantics of this command are identical to the * SVGA_3D_CMD_WAIT_FOR_QUERY except that the results are written * to a Mob instead of a GMR. */ typedef #include "vmware_pack_begin.h" struct { uint32 cid; SVGA3dQueryType type; SVGAMobId mobid; uint32 offset; } #include "vmware_pack_end.h" SVGA3dCmdWaitForGBQuery; /* SVGA_3D_CMD_WAIT_FOR_GB_QUERY */ typedef #include "vmware_pack_begin.h" struct { SVGAMobId mobid; uint32 mustBeZero; uint32 initialized; } #include "vmware_pack_end.h" SVGA3dCmdEnableGart; /* SVGA_3D_CMD_ENABLE_GART */ typedef #include "vmware_pack_begin.h" struct { SVGAMobId mobid; uint32 gartOffset; } #include "vmware_pack_end.h" SVGA3dCmdMapMobIntoGart; /* SVGA_3D_CMD_MAP_MOB_INTO_GART */ typedef #include "vmware_pack_begin.h" struct { uint32 gartOffset; uint32 numPages; } #include "vmware_pack_end.h" SVGA3dCmdUnmapGartRange; /* SVGA_3D_CMD_UNMAP_GART_RANGE */ /* * Screen Targets */ typedef #include "vmware_pack_begin.h" struct { uint32 stid; uint32 width; uint32 height; int32 xRoot; int32 yRoot; SVGAScreenTargetFlags flags; /* * The physical DPI that the guest expects this screen displayed at. * * Guests which are not DPI-aware should set this to zero. */ uint32 dpi; } #include "vmware_pack_end.h" SVGA3dCmdDefineGBScreenTarget; /* SVGA_3D_CMD_DEFINE_GB_SCREENTARGET */ typedef #include "vmware_pack_begin.h" struct { uint32 stid; } #include "vmware_pack_end.h" SVGA3dCmdDestroyGBScreenTarget; /* SVGA_3D_CMD_DESTROY_GB_SCREENTARGET */ typedef #include "vmware_pack_begin.h" struct { uint32 stid; SVGA3dSurfaceImageId image; } #include "vmware_pack_end.h" SVGA3dCmdBindGBScreenTarget; /* SVGA_3D_CMD_BIND_GB_SCREENTARGET */ typedef #include "vmware_pack_begin.h" struct { uint32 stid; SVGA3dRect rect; } #include "vmware_pack_end.h" SVGA3dCmdUpdateGBScreenTarget; /* SVGA_3D_CMD_UPDATE_GB_SCREENTARGET */ typedef #include "vmware_pack_begin.h" struct SVGA3dCmdGBScreenDMA { uint32 screenId; uint32 dead; SVGAMobId destMobID; uint32 destPitch; SVGAMobId changeMapMobID; } #include "vmware_pack_end.h" SVGA3dCmdGBScreenDMA; /* SVGA_3D_CMD_GB_SCREEN_DMA */ typedef #include "vmware_pack_begin.h" struct { uint32 value; uint32 mobId; uint32 mobOffset; } #include "vmware_pack_end.h" SVGA3dCmdGBMobFence; /* SVGA_3D_CMD_GB_MOB_FENCE */ #endif /* _SVGA3D_CMD_H_ */
29.328787
87
0.664319
[ "render", "object", "shape", "3d" ]
c84ff4937b8d16db531b82a119d67c25aa9c4ce8
999
h
C
engine/src/math/mvpstack.h
preversewharf45/freetype-demo
8af8eae2976bac3709d1494adbc5a64907adef64
[ "MIT" ]
null
null
null
engine/src/math/mvpstack.h
preversewharf45/freetype-demo
8af8eae2976bac3709d1494adbc5a64907adef64
[ "MIT" ]
null
null
null
engine/src/math/mvpstack.h
preversewharf45/freetype-demo
8af8eae2976bac3709d1494adbc5a64907adef64
[ "MIT" ]
null
null
null
#ifndef __MVP_STACK_H__ #define __MVP_STACK_H__ #include "matrixstack.h" #include <utils/singleton.h> namespace engine { namespace math { class MVPStack : public utils::Singleton<MVPStack> { friend class utils::Singleton<MVPStack>; private: MVPStack() { m_Cache = m_Projection.Get() * m_View.Get() * m_Model.Get(); } ~MVPStack() {} public: inline bool IsChanged() const { return (m_Model.IsChanged() || m_View.IsChanged() || m_Projection.IsChanged()); } prevmath::Mat4 GetMVP() const { if (IsChanged()) { RecalculateMVP(); } return m_Cache; } MatrixStack & Model() { return m_Model; }; MatrixStack & View() { return m_View; }; MatrixStack & Projection() { return m_Projection; }; private: inline void RecalculateMVP() const { m_Cache = m_Projection.Get() * m_View.Get() * m_Model.Get(); } private: mutable MatrixStack m_Model; mutable MatrixStack m_View; mutable MatrixStack m_Projection; mutable prevmath::Mat4 m_Cache; }; } } #endif //__MVP_STACK_H__
26.289474
115
0.702703
[ "model" ]
c852b98430119fba808b3ae7bf59ee1eba8f7b41
2,465
h
C
src/callback_registry.h
ThePrez/later
97df19a0b4024674d25b40b75ccc6b4339f82758
[ "Zlib" ]
null
null
null
src/callback_registry.h
ThePrez/later
97df19a0b4024674d25b40b75ccc6b4339f82758
[ "Zlib" ]
null
null
null
src/callback_registry.h
ThePrez/later
97df19a0b4024674d25b40b75ccc6b4339f82758
[ "Zlib" ]
null
null
null
#ifndef _CALLBACK_REGISTRY_H_ #define _CALLBACK_REGISTRY_H_ #include <Rcpp.h> #include <queue> #include <boost/operators.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include "timestamp.h" #include "optional.h" #include "threadutils.h" typedef boost::function0<void> Task; class Callback : boost::operators<Callback> { public: Callback(Timestamp when, Task func); bool operator<(const Callback& other) const { return this->when < other.when || (!(this->when > other.when) && this->callbackNum < other.callbackNum); } void operator()() const { func(); } Timestamp when; private: Task func; // Used to break ties when comparing to a callback that has precisely the same // timestamp uint64_t callbackNum; }; typedef boost::shared_ptr<Callback> Callback_sp; template <typename T> struct pointer_greater_than { const bool operator()(const T a, const T b) const { return *a > *b; } }; // Stores R function callbacks, ordered by timestamp. class CallbackRegistry { private: // This is a priority queue of shared pointers to Callback objects. The // reason it is not a priority_queue<Callback> is because that can cause // objects to be copied on the wrong thread, and even trigger an R GC event // on the wrong thread. https://github.com/r-lib/later/issues/39 std::priority_queue<Callback_sp, std::vector<Callback_sp>, pointer_greater_than<Callback_sp> > queue; mutable Mutex mutex; mutable ConditionVariable condvar; public: CallbackRegistry(); // Add a function to the registry, to be executed at `secs` seconds in // the future (i.e. relative to the current time). void add(Rcpp::Function func, double secs); // Add a C function to the registry, to be executed at `secs` seconds in // the future (i.e. relative to the current time). void add(void (*func)(void*), void* data, double secs); // The smallest timestamp present in the registry, if any. // Use this to determine the next time we need to pump events. Optional<Timestamp> nextTimestamp() const; // Is the registry completely empty? bool empty() const; // Is anything ready to execute? bool due(const Timestamp& time = Timestamp()) const; // Pop and return an ordered list of functions to execute now. std::vector<Callback_sp> take(size_t max = -1, const Timestamp& time = Timestamp()); bool wait(double timeoutSecs) const; }; #endif // _CALLBACK_REGISTRY_H_
28.333333
103
0.712779
[ "vector" ]
c85ad2c6fe48f999ab4a7b22c4ce18b280d185ff
139
h
C
GeneticAlgorithm/Fitness.h
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
2
2019-11-04T15:09:52.000Z
2022-01-12T05:41:16.000Z
GeneticAlgorithm/Fitness.h
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
null
null
null
GeneticAlgorithm/Fitness.h
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
1
2020-09-09T12:24:35.000Z
2020-09-09T12:24:35.000Z
#pragma once #include <vector> namespace GA { class Fitness { public: virtual int forGenotype(std::vector<int>& genotype) = 0; }; }
11.583333
58
0.676259
[ "vector" ]
c860e10acd3c8c5c8852adc3983a05a73d5e647a
1,773
c
C
3rd_party_programs/exonerate-2.2.0/src/c4/alignment.test.c
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
12
2015-10-29T15:55:02.000Z
2021-09-10T05:17:16.000Z
3rd_party_programs/exonerate-2.2.0/src/c4/alignment.test.c
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
3
2017-01-13T12:03:29.000Z
2018-10-05T15:02:45.000Z
3rd_party_programs/exonerate-2.2.0/src/c4/alignment.test.c
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
7
2017-02-17T21:11:10.000Z
2021-04-08T21:06:56.000Z
/****************************************************************\ * * * C4 dynamic programming library - alignment code * * * * Guy St.C. Slater.. mailto:guy@ebi.ac.uk * * Copyright (C) 2000-2008. All Rights Reserved. * * * * This source code is distributed under the terms of the * * GNU General Public License, version 3. See the file COPYING * * or http://www.gnu.org/licenses/gpl.txt for details * * * * If you use this code, please keep this notice intact. * * * \****************************************************************/ #include <glib.h> #include "alignment.h" #include "match.h" gint Argument_main(Argument *arg){ register Region *region = Region_create_blank(); register C4_Model *model = C4_Model_create("test"); register Alignment *alignment; register Match *match; Match_ArgumentSet_create(arg); Argument_process(arg, "alignment.test", NULL, NULL); match = Match_find(Match_Type_DNA2DNA); C4_Model_add_transition(model, "start to end", NULL, NULL, 1, 1, NULL, C4_Label_MATCH, match); C4_Model_close(model); alignment = Alignment_create(model, region, 0); g_message("alignment test"); Alignment_destroy(alignment); C4_Model_destroy(model); Region_destroy(region); return 0; } /* Proper testing is done with the model tests */
41.232558
67
0.467569
[ "model" ]
c861283d1ac45a3f08f1e5cfea5504bec87f985c
1,522
c
C
lib/wizards/proge/lair/hall_1_4.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/proge/lair/hall_1_4.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/proge/lair/hall_1_4.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
inherit "room/room"; object monster1; object monster2; object monster3; reset(arg) { if(!monster) { monster = clone_object("/wizards/proge/suunnitelmat/lair/aggro_troll"); move_object(monster, this_object()); } if(!monster2) { monster2 = clone_object("/wizards/proge/suunnitelmat/lair/aggro_troll"); move_object(monster2, this_object()); } if(!monster3) { monster3 = clone_object("/wizards/proge/suunnitelmat/lair/easy_aggro_orc"); move_object(monster, this_object()); } if(arg) return; set_not_out(); add_exit("west","/wizards/proge/lair/hall_1_3"); add_exit("south","/wizards/proge/lair/hall_2_4"); add_exit("southwest", "/wizards/proge/lair/hall_2_3"); add_exit("east", "/wizards/proge/lair/hall_1_5"); add_exit("southeast", "/wizards/proge/lair/hall_2_5"); short_desc = "Northern side of the hall"; long_desc = "You're standing in a big, lighted hall, full of nasty looking\n"+ "creatures. There's torches haning on the walls, and on the\n"+ "southern side of the hall you can see somekind of big chair, like\n"+ "a throne. Hideous creatures swarm everywhere, eating raw flesh\n"+ "and fighting each other. Screams and wailing is getting louder.\n"+ "There might be a prison or dungeon of somekind in here. Air\n"+ "stinks of rotten meat, orcs, trolls and other nasty beasts.\n"+ "The stone floor is covered in blood, probably result of the\n"+ "monstrous rituals that the orcs and trolls been having in here.\n"; }
36.238095
79
0.701051
[ "object" ]
c86ae542f9fe3e4f8536b1ec2e42be94211eec69
13,061
c
C
masses/perceptron.c
yuvarajbora/demo
82edce9b2f40611e59207787fb71806c4e8a37fc
[ "Apache-2.0" ]
null
null
null
masses/perceptron.c
yuvarajbora/demo
82edce9b2f40611e59207787fb71806c4e8a37fc
[ "Apache-2.0" ]
4
2021-04-28T20:02:39.000Z
2021-04-29T00:59:20.000Z
masses/perceptron.c
jeandersoncruz/github-move
82edce9b2f40611e59207787fb71806c4e8a37fc
[ "Apache-2.0" ]
1
2021-07-05T18:55:19.000Z
2021-07-05T18:55:19.000Z
/* This program uses stochastic gradient descent to learn a scoreset for * SpamAssassin. You'll need to run logs-to-c from spamassassin/masses to * generate the stuff in tmp. * * <@LICENSE> * Copyright 2004 Apache Software Foundation * * 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. * </@LICENSE> */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/time.h> #include <math.h> #include <unistd.h> #include "tmp/scores.h" #include "tmp/tests.h" /* Ensure that multiple error functions have not been chosen. */ #ifdef ENTROPIC_ERROR #ifdef LEAST_SQUARES_ERROR #warn Both entropic error and least squares error chosen. Using least squares. #endif #endif /* Choose the least squares error function by default. */ #ifndef ENTROPIC_ERROR #ifndef LEAST_SQUARES_ERROR #define LEAST_SQUARES_ERROR #endif #endif #define OUTPUT_FILE "perceptron.scores" /* #define IGNORE_SCORE_RANGES 1 */ void init_wheel (); void destroy_wheel (); int get_random_test (); void init_weights(); void destroy_weights (); void write_weights (FILE * fp); void scale_scores (double old_threshold, double new_threshold); double evaluate_test (int test); double evaluate_test_nogain (int test); void train (int num_epochs, double learning_rate); void usage (); /* Converts a weight to a SpamAssassin score. */ #define weight_to_score(x) (-threshold*(x)/bias) #define score_to_weight(x) (-(x)*bias/threshold) int wheel_size; /* The number of entries in the roulette wheel (NOT THE SIZE OF THE ROULETTE_WHEEL ARRAY!). */ int * roulette_wheel; /* Used for roulette wheel selection. */ double ham_preference = 2.0; #define DEFAULT_THRESHOLD 5.0 double threshold = DEFAULT_THRESHOLD; double * weights; /* The weights of the single-layer perceptron. */ double bias; /* The network bias for the single-layer perceptron. */ int num_epochs = 15; double learning_rate = 2.0; double weight_decay = 1.0; /* Initialize the roulette wheel and populate it, replicating harder-to-classify hams. */ void init_wheel () { int i; int spam = 0, ham = 0; /* cache locations on the roulette wheel for fast lookups */ roulette_wheel = (int*)calloc(num_nondup, sizeof(int)); wheel_size = 0; roulette_wheel[0] = 0; for (i = 0; i < num_nondup - 1; i++) { int slot_size = 1; /* Hams with more tests are rare and harder to classify but are the * most important to classify correctly. They are thus replicated in the * training set proportionally to their difficulty. */ if ( ! is_spam[i] ) { slot_size += (int)(num_tests_hit[i] * ham_preference * tests_count[i]); } else { slot_size = tests_count[i]; } /* The database is compressed with all instances mapped in the same place. */ wheel_size += slot_size; if ( ! is_spam[i] ) { ham += slot_size; } else { spam++; } roulette_wheel[i+1] = roulette_wheel[i] + slot_size; } printf ("Modified training set statistics: %d spam, %d ham.\n", spam, ham); } /* Free the resources for the roulette wheel selector. */ void destroy_wheel () { if ( roulette_wheel ) { free (roulette_wheel); roulette_wheel = 0; wheel_size = 0; } } /* Get a random test using roulette wheel selection. This is not used anymore. */ int get_random_test () { int r; int bottom, middle, top; r = lrand48() % wheel_size; bottom = 0; top = num_nondup - 1; middle = top / 2; while (1) { if ( r < roulette_wheel[bottom+1] ) { return bottom; } else if ( r >= roulette_wheel[top] ) { return top; } else if ( r >= roulette_wheel[middle] && r < roulette_wheel[middle+1] ) { return middle; } else if ( r < roulette_wheel[middle] ) { top = middle-1; bottom++; middle = bottom + (top-bottom)/2; } else { bottom = middle+1; top--; middle = bottom + (top-bottom)/2; } } } /* Allocate and initialize the weights over the range [-0.5..0.5] */ void init_weights () { int i; weights = (double*)calloc(num_scores, sizeof(double)); bias = drand48() - 0.5; for (i = 0; i < num_scores; i++) { weights[i] = range_lo[i] + drand48() * (range_hi[i] - range_lo[i]); } } /* Free the resources allocated for the weights. */ void destroy_weights () { if ( weights ) { free(weights); weights = 0; } } /* Writes out the weights in SpamAssassin score space. */ void write_weights (FILE * fp) { int i; int ga_nn, ga_yy, ga_ny, ga_yn; double nnscore, yyscore, nyscore, ynscore; ga_nn = ga_yy = ga_ny = ga_yn = 0; nnscore = yyscore = nyscore = ynscore = 0; /* Run through all of the instances in the training set and tally up * the scores. */ for (i = 0; i < num_nondup; i++) { double score = weight_to_score(evaluate_test_nogain(i)) + threshold; if ( score >= threshold && is_spam[i] ) { ga_yy += tests_count[i]; yyscore += tests_count[i] * score; } else if ( score < threshold && !is_spam[i] ) { ga_nn += tests_count[i]; nnscore += tests_count[i] * score; } else if ( score >= threshold && !is_spam[i] ) { ga_ny += tests_count[i]; nyscore += tests_count[i] * score; } else { ga_yn += tests_count[i]; ynscore += tests_count[i] * score; } } /* This is copied from the dump() function in craig-evolve.c. It * outputs some nice statistics about the learned classifier. */ fprintf (fp,"\n# SUMMARY for threshold %3.1f:\n", threshold); fprintf (fp, "# Correctly non-spam: %6d %4.2f%%\n", ga_nn, (ga_nn / (float) num_ham) * 100.0); fprintf (fp, "# Correctly spam: %6d %4.2f%%\n", ga_yy, (ga_yy / (float) num_spam) * 100.0); fprintf (fp, "# False positives: %6d %4.2f%%\n", ga_ny, (ga_ny / (float) num_ham) * 100.0); fprintf (fp, "# False negatives: %6d %4.2f%%\n", ga_yn, (ga_yn / (float) num_spam) * 100.0); fprintf (fp,"# Average score for spam: %3.3f ham: %3.1f\n",(ynscore+yyscore)/((double)(ga_yn+ga_yy)),(nyscore+nnscore)/((double)(ga_nn+ga_ny))); fprintf (fp,"# Average for false-pos: %3.3f false-neg: %3.1f\n",(nyscore/(double)ga_ny),(ynscore/(double)ga_yn)); fprintf (fp,"# TOTAL: %6d %3.2f%%\n\n", num_tests, 100.0); for (i = 0; i < num_scores; i++) { if ( is_mutable[i] ) { fprintf(fp, "score %-30s %2.3f # [%2.3f..%2.3f]\n", score_names[i], weight_to_score(weights[i]), range_lo[i], range_hi[i]); } else { fprintf(fp, "score %-30s %2.3f # not mutable\n", score_names[i], range_lo[i]); } } } /* This is to support Daniel's threshold thing. */ void scale_scores (double old_threshold, double new_threshold) { int i; /* No need to scale something to itself. */ if ( old_threshold == new_threshold ) { return; } for (i = 0; i < num_scores; i++) { if ( is_mutable[i] ) { range_lo[i] = range_lo[i] * new_threshold / old_threshold; range_hi[i] = range_hi[i] * new_threshold / old_threshold; } } /* Maybe we don't want this bit. This prescaling stuff makes my * brain hurt.*/ /* for (i = 0; i < num_nondup; i++) { scores[i] = scores[i] * new_threshold / old_threshold; } */ } /* Computes the value of the activation function of the perceptron for * a given input. */ double evaluate_test (int test) { #ifdef LEAST_SQUARES_ERROR return 1/(1+exp(-evaluate_test_nogain(test))); #else #ifdef ENTROPIC_ERROR return tanh(evaluate_test_nogain(test)); #endif #endif } /* Computes the value of the transfer function (in this case, linear) for * an input defined in tests_hit[test]* */ double evaluate_test_nogain (int test) { double sum; int i; sum = bias; for (i = 0; i < num_tests_hit[test]; i++) { sum += weights[tests_hit[test][i]]; } /* Translate the 'unmutable' scores to weight space. */ sum += score_to_weight(scores[test]); return sum; } /* Trains the perceptron using stochastic gradient descent. */ void train (int num_epochs, double learning_rate) { int epoch, random_test; int i, j; int * tests; double y_out, error, delta; /* Initialize and populate an array containing indices of training * instances. This is shuffled on every epoch and then iterated * through. I had originally planned to use roulette wheel selection, * but shuffled selection seems to work better. */ tests = (int*)calloc(wheel_size, sizeof(int)); for (i = 0, j = 0; i < num_nondup-1; i++) { for (; j < roulette_wheel[i+1]; j++) { tests[j] = i; } } for (; j < wheel_size; j++) { tests[j] = num_nondup-1; } for (epoch = 0; epoch < num_epochs; epoch++) { /* decay the weights on every epoch to smooth out statistical * anomalies */ if ( weight_decay != 1.0 ) { bias *= weight_decay; for (i = 0; i < num_mutable; i++) { weights[i] *= weight_decay; } } /* shuffle the training instances */ for (i = 0; i < wheel_size-1; i++) { int tmp; int r = lrand48 () % (wheel_size - i); tmp = tests[i]; tests[i] = tests[r+i]; tests[r+i] = tmp; } for (j = 0; j < wheel_size; j++) { /* select a random test (they have been randomized above) */ random_test = tests[j]; /* compute the output of the network */ y_out = evaluate_test(random_test); /* compute the error gradient for the logsig node with least squares error */ #ifdef LEAST_SQUARES_ERROR error = is_spam[random_test] - y_out; delta = y_out * (1-y_out) * error / (num_tests_hit[random_test]+1) * learning_rate; #else /* compute the error gradient for the tanh node with entropic error */ #ifdef ENTROPIC_ERROR error = (2.0*is_spam[random_test]-1) - y_out; delta = error / (num_tests_hit[random_test]+1) * learning_rate; #endif #endif /* adjust the weights to descend the steepest part of the error gradient */ if ( epoch + 1 < num_epochs ) { bias += delta; } for (i = 0; i < num_tests_hit[random_test]; i++) { int idx = tests_hit[random_test][i]; weights[idx] += delta; #ifdef IGNORE_SCORE_RANGES /* Constrain the weights so that nice rules are always <= 0 etc. */ if ( range_lo[idx] >= 0 && weights[idx] < 0 ) { weights[idx] = 0; } else if ( range_hi[idx] <= 0 && weights[idx] > 0 ) { weights[idx] = 0; } #else if ( weights[idx] < score_to_weight(range_lo[idx]) ) { weights[idx] = score_to_weight(range_lo[idx]); } else if ( weights[idx] > score_to_weight(range_hi[idx]) ) { weights[idx] = score_to_weight(range_hi[idx]); } #endif } } } free(tests); } void usage () { printf ("usage: perceptron [args]\n" "\n" " -p ham_preference = adds extra ham to training set multiplied by number of\n" " tests hit (2.0 default)\n" " -e num_epochs = number of epochs to train (15 default)\n" " -l learning_rate = learning rate for gradient descent (2.0 default)\n" " -t threshold = minimum threshold for spam (5.0 default)\n" " -w weight_decay = per-epoch decay of learned weight and bias (1.0 default)\n" " -h = print this help\n" "\n"); exit(30); } int main (int argc, char ** argv) { struct timeval tv, tv_start, tv_end; long long int t_usec; FILE * fp; int arg; /* Read the command line options */ while ((arg = getopt (argc, argv, "p:e:l:t:w:h?")) != -1) { switch (arg) { case 'p': ham_preference = atof(optarg); break; case 'e': num_epochs = atoi(optarg); break; case 'l': learning_rate = atof(optarg); break; case 't': threshold = atof(optarg); break; case 'w': weight_decay = atof(optarg); break; case 'h': case '?': usage(); break; } } /* Seed the PRNG */ gettimeofday (&tv, 0); t_usec = tv.tv_sec * 1000000 + tv.tv_usec; srand48 ((int)t_usec); /* Load the instances and score constraints generated by logs-to-c. */ loadtests(); loadscores(); /* If the threshold has been changed, the ranges and scores need to be * scaled so that the output of the program will not be affected. */ scale_scores (DEFAULT_THRESHOLD, threshold); /* Replicate instances from the training set to bias against false positives. */ init_wheel (); /* Allocate and initialize the weight vector. */ init_weights (); /* Train the network using stochastic gradient descent. */ gettimeofday(&tv_start, 0); train(num_epochs, learning_rate); gettimeofday(&tv_end, 0); t_usec = tv_end.tv_sec * 1000000 + tv_end.tv_usec - (tv_start.tv_sec *1000000 + tv_start.tv_usec); printf ("Training time = %fs.\n", t_usec / 1000000.0f); /* Translate the learned weights to SA score space and output to a file. */ fp = fopen (OUTPUT_FILE, "w"); if ( fp ) { write_weights(fp); fclose(fp); } else { perror (OUTPUT_FILE); } /* Free resources */ destroy_weights (); destroy_wheel (); return 0; }
27.210417
149
0.65531
[ "vector" ]
c86cd2ef27069256f1f9e75044774af952d17aa2
7,218
c
C
Controller_Software/Kingfisher_ELC_Workspace/KP_Controller_1/src/PieVect_Init.c
equinoxorg/Micro-Hydro-ELC
242d1e07ae4defe1c675bc45748f24709c9eba0d
[ "CC-BY-3.0" ]
2
2017-04-05T13:08:33.000Z
2018-02-06T22:35:38.000Z
Controller_Software/Kingfisher_ELC_Workspace/KP_Controller_1/src/PieVect_Init.c
equinoxorg/Micro-Hydro-ELC
242d1e07ae4defe1c675bc45748f24709c9eba0d
[ "CC-BY-3.0" ]
null
null
null
Controller_Software/Kingfisher_ELC_Workspace/KP_Controller_1/src/PieVect_Init.c
equinoxorg/Micro-Hydro-ELC
242d1e07ae4defe1c675bc45748f24709c9eba0d
[ "CC-BY-3.0" ]
5
2015-11-14T21:53:00.000Z
2021-01-12T01:02:28.000Z
//########################################################################### // // FILE: F2806x_PieVect.c // // TITLE: F2806x Devices PIE Vector Table Initialisation Functions. // //########################################################################### // $TI Release: F2806x C/C++ Header Files and Peripheral Examples V130 $ // $Release Date: November 30, 2011 $ //########################################################################### #include "F2806x_Device.h" #include "F2806x_DefaultISR.h" const struct PIE_VECT_TABLE PieVectTableInit = { PIE_RESERVED, // 1 Reserved space PIE_RESERVED, // 2 Reserved space PIE_RESERVED, // 3 Reserved space PIE_RESERVED, // 4 Reserved space PIE_RESERVED, // 5 Reserved space PIE_RESERVED, // 6 Reserved space PIE_RESERVED, // 7 Reserved space PIE_RESERVED, // 8 Reserved space PIE_RESERVED, // 9 Reserved space PIE_RESERVED, // 10 Reserved space PIE_RESERVED, // 11 Reserved space PIE_RESERVED, // 12 Reserved space PIE_RESERVED, // 13 Reserved space // Non-Peripheral Interrupts INT13_ISR, // CPU-Timer 1 INT14_ISR, // CPU-Timer 2 DATALOG_ISR, // Datalogging interrupt RTOSINT_ISR, // RTOS interrupt EMUINT_ISR, // Emulation interrupt NMI_ISR, // Non-maskable interrupt ILLEGAL_ISR, // Illegal operation TRAP USER1_ISR, // User Defined trap 1 USER2_ISR, // User Defined trap 2 USER3_ISR, // User Defined trap 3 USER4_ISR, // User Defined trap 4 USER5_ISR, // User Defined trap 5 USER6_ISR, // User Defined trap 6 USER7_ISR, // User Defined trap 7 USER8_ISR, // User Defined trap 8 USER9_ISR, // User Defined trap 9 USER10_ISR, // User Defined trap 10 USER11_ISR, // User Defined trap 11 USER12_ISR, // User Defined trap 12 // Group 1 PIE Vectors ADCINT1_ISR, // 1.1 ADC ADC - make rsvd1_1 if ADCINT1 is wanted in Group 10 instead. ADCINT2_ISR, // 1.2 ADC ADC - make rsvd1_2 if ADCINT2 is wanted in Group 10 instead. rsvd_ISR, // 1.3 XINT1_ISR, // 1.4 External Interrupt XINT2_ISR, // 1.5 External Interrupt ADCINT9_ISR, // 1.6 ADC Interrupt 9 TINT0_ISR, // 1.7 Timer 0 WAKEINT_ISR, // 1.8 WD, Low Power // Group 2 PIE Vectors EPWM1_TZINT_ISR, // 2.1 EPWM-1 Trip Zone EPWM2_TZINT_ISR, // 2.2 EPWM-2 Trip Zone EPWM3_TZINT_ISR, // 2.3 EPWM-3 Trip Zone EPWM4_TZINT_ISR, // 2.4 EPWM-4 Trip Zone EPWM5_TZINT_ISR, // 2.5 EPWM-5 Trip Zone EPWM6_TZINT_ISR, // 2.6 EPWM-6 Trip Zone EPWM7_TZINT_ISR, // 2.7 EPWM-7 Trip Zone EPWM8_TZINT_ISR, // 2.8 EPWM-8 Trip Zone // Group 3 PIE Vectors EPWM1_INT_ISR, // 3.1 EPWM-1 Interrupt EPWM2_INT_ISR, // 3.2 EPWM-2 Interrupt EPWM3_INT_ISR, // 3.3 EPWM-3 Interrupt EPWM4_INT_ISR, // 3.4 EPWM-4 Interrupt EPWM5_INT_ISR, // 3.5 EPWM-5 Interrupt EPWM6_INT_ISR, // 3.6 EPWM-6 Interrupt EPWM7_INT_ISR, // 3.7 EPWM-7 Interrupt EPWM8_INT_ISR, // 3.8 EPWM-8 Interrupt // Group 4 PIE Vectors ECAP1_INT_ISR, // 4.1 ECAP-1 ECAP2_INT_ISR, // 4.2 ECAP-2 ECAP3_INT_ISR, // 4.3 ECAP-3 rsvd_ISR, // 4.4 rsvd_ISR, // 4.5 rsvd_ISR, // 4.6 HRCAP1_INT_ISR, // 4.7 HRCAP-1 HRCAP2_INT_ISR, // 4.8 HRCAP-2 // Group 5 PIE Vectors EQEP1_INT_ISR, // 5.1 EQEP-1 EQEP2_INT_ISR, // 5.2 EQEP-2 rsvd_ISR, // 5.3 HRCAP3_INT_ISR, // 5.4 HRCAP-3 HRCAP4_INT_ISR, // 5.5 HRCAP-4 rsvd_ISR, // 5.6 rsvd_ISR, // 5.7 USB0_INT_ISR, // 5.8 USB-0 // Group 6 PIE Vectors SPIRXINTA_ISR, // 6.1 SPI-A SPITXINTA_ISR, // 6.2 SPI-A SPIRXINTB_ISR, // 6.3 SPI-B SPITXINTA_ISR, // 6.4 SPI-B MRINTA_ISR, // 6.5 McBSP-A MXINTA_ISR, // 6.6 McBSP-A rsvd_ISR, // 6.7 rsvd_ISR, // 6.8 // Group 7 PIE Vectors DINTCH1_ISR, // 7.1 DMA Channel 1 DINTCH2_ISR, // 7.2 DMA Channel 2 DINTCH3_ISR, // 7.3 DMA Channel 3 DINTCH4_ISR, // 7.4 DMA Channel 4 DINTCH5_ISR, // 7.5 DMA Channel 5 DINTCH6_ISR, // 7.6 DMA Channel 6 rsvd_ISR, // 7.7 rsvd_ISR, // 7.8 // Group 8 PIE Vectors I2CINT1A_ISR, // 8.1 I2C-A I2CINT2A_ISR, // 8.2 I2C-A rsvd_ISR, // 8.3 rsvd_ISR, // 8.4 rsvd_ISR, // 8.5 rsvd_ISR, // 8.6 rsvd_ISR, // 8.7 rsvd_ISR, // 8.8 // Group 9 PIE Vectors SCIRXINTA_ISR, // 9.1 SCI-A SCITXINTA_ISR, // 9.2 SCI-A SCIRXINTB_ISR, // 9.3 SCI-B SCITXINTB_ISR, // 9.4 SCI-B ECAN0INTA_ISR, // 9.5 ECAN-A ECAN1INTA_ISR, // 9.6 ECAN-A rsvd_ISR, // 9.7 rsvd_ISR, // 9.8 // Group 10 PIE Vectors rsvd_ISR, // 10.1 Can be ADCINT1, but must make ADCINT1 in Group 1 space "reserved". rsvd_ISR, // 10.2 Can be ADCINT2, but must make ADCINT2 in Group 1 space "reserved". ADCINT3_ISR, // 10.3 ADC ADCINT4_ISR, // 10.4 ADC ADCINT5_ISR, // 10.5 ADC ADCINT6_ISR, // 10.6 ADC ADCINT7_ISR, // 10.7 ADC ADCINT8_ISR, // 10.8 ADC // Group 11 PIE Vectors CLA1_INT1_ISR, // 11.1 CLA1 CLA1_INT2_ISR, // 11.2 CLA1 CLA1_INT3_ISR, // 11.3 CLA1 CLA1_INT4_ISR, // 11.4 CLA1 CLA1_INT5_ISR, // 11.5 CLA1 CLA1_INT6_ISR, // 11.6 CLA1 CLA1_INT7_ISR, // 11.7 CLA1 CLA1_INT8_ISR, // 11.8 CLA1 // Group 12 PIE Vectors XINT3_ISR, // 12.1 External Interrupt rsvd_ISR, // 12.2 rsvd_ISR, // 12.3 rsvd_ISR, // 12.4 rsvd_ISR, // 12.5 rsvd_ISR, // 12.6 LVF_ISR, // 12.7 Latched Overflow LUF_ISR // 12.8 Latched Underflow }; //--------------------------------------------------------------------------- // InitPieVectTable: //--------------------------------------------------------------------------- // This function initializes the PIE vector table to a known state. // This function must be executed after boot time. // void InitPieVectTable(void) { int16 i; Uint32 *Source = (void *) &PieVectTableInit; Uint32 *Dest = (void *) &PieVectTable; // Do not write over first 3 32-bit locations (these locations are // initialized by Boot ROM with boot variables) Source = Source + 3; Dest = Dest + 3; EALLOW; for(i=0; i < 125; i++) *Dest++ = *Source++; EDIS; // Enable the PIE Vector Table PieCtrlRegs.PIECTRL.bit.ENPIE = 1; } //=========================================================================== // End of file. //===========================================================================
35.038835
98
0.515655
[ "vector" ]
c8703e0a4dfabf772e2497cc9b47de1c75049311
368
h
C
Plugin/FbxExporter/pch.h
Hengle/FbxExporter
5324c74394156af043edd78018740299be789d1d
[ "MIT" ]
205
2017-06-29T13:28:43.000Z
2022-03-01T05:39:51.000Z
Plugin/FbxExporter/pch.h
Hengle/FbxExporter
5324c74394156af043edd78018740299be789d1d
[ "MIT" ]
3
2017-08-01T09:16:27.000Z
2018-05-05T04:25:31.000Z
Plugin/FbxExporter/pch.h
Hengle/FbxExporter
5324c74394156af043edd78018740299be789d1d
[ "MIT" ]
40
2017-07-05T04:01:23.000Z
2022-01-18T14:14:29.000Z
#pragma once #include <cstdio> #include <cstdlib> #include <cstring> #include <cstdint> #include <cfloat> #include <string> #include <vector> #include <map> #include <set> #include <functional> #include <memory> #include <iostream> #include <sstream> #include <atomic> #include <numeric> #include <future> #include <fbxsdk.h> #define fbxeImpl
16
22
0.682065
[ "vector" ]
c876c5156aba5d3f1c30af1e8b90bad3b792adb5
3,894
h
C
tensorflow/core/lib/png/png_io.h
knightvishal/tensorflow
5d3dd19b7146d954fc1b4e9e44e9881e75d363c1
[ "Apache-2.0" ]
4
2021-06-15T17:26:07.000Z
2021-11-17T10:58:08.000Z
tensorflow/core/lib/png/png_io.h
knightvishal/tensorflow
5d3dd19b7146d954fc1b4e9e44e9881e75d363c1
[ "Apache-2.0" ]
4
2020-09-26T00:55:50.000Z
2022-02-10T01:53:06.000Z
tensorflow/core/lib/png/png_io.h
knightvishal/tensorflow
5d3dd19b7146d954fc1b4e9e44e9881e75d363c1
[ "Apache-2.0" ]
6
2018-12-20T01:35:20.000Z
2020-07-10T17:29:57.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Functions to read and write images in PNG format. // // The advantage over image/codec/png{enc,dec}ocder.h is that this library // supports both 8 and 16 bit images. // // The decoding routine accepts binary image data as a StringPiece. These are // implicitly constructed from strings or char* so they're completely // transparent to the caller. They're also very cheap to construct so this // doesn't introduce any additional overhead. // // The primary benefit of StringPieces being, in this case, that APIs already // returning StringPieces (e.g., Bigtable Scanner) or Cords (e.g., IOBuffer; // only when they're flat, though) or protocol buffer fields typed to either of // these can be decoded without copying the data into a C++ string. #ifndef TENSORFLOW_LIB_PNG_PNG_IO_H_ #define TENSORFLOW_LIB_PNG_PNG_IO_H_ #include <string> #include <utility> #include <vector> #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/platform/png.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace png { // Handy container for decoding informations and struct pointers struct DecodeContext { const uint8* data; int data_left; png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int num_passes; int color_type; int bit_depth; int channels; bool need_to_synthesize_16; bool error_condition; DecodeContext() : png_ptr(NULL), info_ptr(NULL) {} }; bool DecodeHeader(StringPiece png_string, int* width, int* height, int* components, int* channel_bit_depth, std::vector<std::pair<string, string> >* metadata); // Sample usage for reading PNG: // // string png_string; /* fill with input PNG format data */ // DecodeContext context; // CHECK(CommonInitDecode(png_string, 3 /*RGB*/, 8 /*uint8*/, &context)); // char* image_buffer = new char[3*context.width*context.height]; // CHECK(CommonFinishDecode(bit_cast<png_byte*>(image_buffer), // 3*context.width /*stride*/, &context)); // // desired_channels may be 0 to detected it from the input. bool CommonInitDecode(StringPiece png_string, int desired_channels, int desired_channel_bits, DecodeContext* context); bool CommonFinishDecode(png_bytep data, int row_bytes, DecodeContext* context); // Normally called automatically from CommonFinishDecode. If CommonInitDecode // is called but not CommonFinishDecode, call this to clean up. Safe to call // extra times. void CommonFreeDecode(DecodeContext* context); // Sample usage for writing PNG: // // uint16* image_buffer = new uint16[width*height]; /* fill with pixels */ // string png_string; // CHECK(WriteImageToBuffer(image_buffer, width, height, 2*width /*stride*/, // 1 /*gray*/, 16 /*uint16*/, &png_string, NULL)); // // compression is in [-1,9], where 0 is fast and weak compression, 9 is slow // and strong, and -1 is the zlib default. bool WriteImageToBuffer( const void* image, int width, int height, int row_bytes, int num_channels, int channel_bits, int compression, string* png_string, const std::vector<std::pair<string, string> >* metadata); } // namespace png } // namespace tensorflow #endif // TENSORFLOW_LIB_PNG_PNG_IO_H_
37.085714
80
0.725989
[ "vector" ]
c87c27202f76e4361c38a2d39467f1c00b7968d9
2,182
h
C
vendor/bundle/ruby/2.1.0/gems/unicorn-4.6.3/ext/unicorn_http/ext_help.h
suhongrui/gitlab
33063034d30951b48a3edc94245185dcae742e5a
[ "MIT" ]
null
null
null
vendor/bundle/ruby/2.1.0/gems/unicorn-4.6.3/ext/unicorn_http/ext_help.h
suhongrui/gitlab
33063034d30951b48a3edc94245185dcae742e5a
[ "MIT" ]
1
2021-08-24T05:33:06.000Z
2021-08-24T05:33:06.000Z
vendor/bundle/ruby/2.1.0/gems/unicorn-4.6.3/ext/unicorn_http/ext_help.h
suhongrui/gitlab
33063034d30951b48a3edc94245185dcae742e5a
[ "MIT" ]
1
2015-10-05T14:27:57.000Z
2015-10-05T14:27:57.000Z
#ifndef ext_help_h #define ext_help_h #ifndef RSTRING_PTR #define RSTRING_PTR(s) (RSTRING(s)->ptr) #endif /* !defined(RSTRING_PTR) */ #ifndef RSTRING_LEN #define RSTRING_LEN(s) (RSTRING(s)->len) #endif /* !defined(RSTRING_LEN) */ #ifndef HAVE_RB_STR_SET_LEN # ifdef RUBINIUS # error we should never get here with current Rubinius (1.x) # endif /* this is taken from Ruby 1.8.7, 1.8.6 may not have it */ static void rb_18_str_set_len(VALUE str, long len) { RSTRING(str)->len = len; RSTRING(str)->ptr[len] = '\0'; } # define rb_str_set_len(str,len) rb_18_str_set_len(str,len) #endif /* !defined(HAVE_RB_STR_SET_LEN) */ /* not all Ruby implementations support frozen objects (Rubinius does not) */ #if defined(OBJ_FROZEN) # define assert_frozen(f) assert(OBJ_FROZEN(f) && "unfrozen object") #else # define assert_frozen(f) do {} while (0) #endif /* !defined(OBJ_FROZEN) */ #if !defined(OFFT2NUM) # if SIZEOF_OFF_T == SIZEOF_LONG # define OFFT2NUM(n) LONG2NUM(n) # else # define OFFT2NUM(n) LL2NUM(n) # endif #endif /* ! defined(OFFT2NUM) */ #if !defined(SIZET2NUM) # if SIZEOF_SIZE_T == SIZEOF_LONG # define SIZET2NUM(n) ULONG2NUM(n) # else # define SIZET2NUM(n) ULL2NUM(n) # endif #endif /* ! defined(SIZET2NUM) */ #if !defined(NUM2SIZET) # if SIZEOF_SIZE_T == SIZEOF_LONG # define NUM2SIZET(n) ((size_t)NUM2ULONG(n)) # else # define NUM2SIZET(n) ((size_t)NUM2ULL(n)) # endif #endif /* ! defined(NUM2SIZET) */ static inline int str_cstr_eq(VALUE val, const char *ptr, long len) { return (RSTRING_LEN(val) == len && !memcmp(ptr, RSTRING_PTR(val), len)); } #define STR_CSTR_EQ(val, const_str) \ str_cstr_eq(val, const_str, sizeof(const_str) - 1) /* strcasecmp isn't locale independent */ static int str_cstr_case_eq(VALUE val, const char *ptr, long len) { if (RSTRING_LEN(val) == len) { const char *v = RSTRING_PTR(val); for (; len--; ++ptr, ++v) { if ((*ptr == *v) || (*v >= 'A' && *v <= 'Z' && (*v | 0x20) == *ptr)) continue; return 0; } return 1; } return 0; } #define STR_CSTR_CASE_EQ(val, const_str) \ str_cstr_case_eq(val, const_str, sizeof(const_str) - 1) #endif /* ext_help_h */
26.289157
77
0.668194
[ "object" ]
c8889d7708db5239683518da20668cc14d85609c
17,367
c
C
sample/framework/vx_distribution.c
JohnZ03/OpenVX-sample-impl
0dd99dfb55cf3f195c8c6880fd6f5da5b7f8fde0
[ "Apache-2.0" ]
96
2018-12-06T18:44:57.000Z
2022-03-22T04:37:14.000Z
sample/framework/vx_distribution.c
GeeShun/OpenVX-sample-impl
8968ea0736e060d13acdd9b14d19c72df48cf88c
[ "Apache-2.0" ]
40
2018-12-05T16:00:49.000Z
2022-03-04T07:58:34.000Z
sample/framework/vx_distribution.c
GeeShun/OpenVX-sample-impl
8968ea0736e060d13acdd9b14d19c72df48cf88c
[ "Apache-2.0" ]
43
2019-02-24T15:17:50.000Z
2022-03-26T23:20:59.000Z
/* * Copyright (c) 2012-2017 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "vx_internal.h" #include "vx_distribution.h" VX_API_ENTRY vx_distribution VX_API_CALL vxCreateDistribution(vx_context context, vx_size numBins, vx_int32 offset, vx_uint32 range) { vx_distribution distribution = NULL; if (ownIsValidContext(context) == vx_true_e) { if ((numBins != 0) && (range != 0)) { distribution = (vx_distribution)ownCreateReference(context, VX_TYPE_DISTRIBUTION, VX_EXTERNAL, &context->base); if ( vxGetStatus((vx_reference)distribution) == VX_SUCCESS && distribution->base.type == VX_TYPE_DISTRIBUTION) { distribution->memory.ndims = 2; distribution->memory.nptrs = 1; distribution->memory.strides[0][VX_DIM_C] = sizeof(vx_int32); distribution->memory.dims[0][VX_DIM_C] = 1; distribution->memory.dims[0][VX_DIM_X] = (vx_uint32)numBins; distribution->memory.dims[0][VX_DIM_Y] = 1; distribution->range_x = (vx_uint32)range; distribution->range_y = 1; distribution->offset_x = offset; distribution->offset_y = 0; } } else { VX_PRINT(VX_ZONE_ERROR, "Invalid parameters to distribution\n"); vxAddLogEntry(&context->base, VX_ERROR_INVALID_PARAMETERS, "Invalid parameters to distribution\n"); distribution = (vx_distribution)ownGetErrorObject(context, VX_ERROR_INVALID_PARAMETERS); } } return distribution; } VX_API_ENTRY vx_distribution VX_API_CALL vxCreateVirtualDistribution( vx_graph graph, vx_size numBins, vx_int32 offset, vx_uint32 range) { vx_distribution distribution = NULL; vx_reference_t *gref = (vx_reference_t *)graph; if (ownIsValidSpecificReference(gref, VX_TYPE_GRAPH) == vx_true_e) { distribution = vxCreateDistribution(gref->context, numBins, offset, range); if (vxGetStatus((vx_reference)distribution) == VX_SUCCESS && distribution->base.type == VX_TYPE_DISTRIBUTION) { distribution->base.scope = (vx_reference_t *)graph; distribution->base.is_virtual = vx_true_e; } } return distribution; } void ownDestructDistribution(vx_reference ref) { vx_distribution distribution = (vx_distribution)ref; ownFreeMemory(distribution->base.context, &distribution->memory); } vx_status vxReleaseDistributionInt(vx_distribution *distribution) { return ownReleaseReferenceInt((vx_reference *)distribution, VX_TYPE_DISTRIBUTION, VX_INTERNAL, &ownDestructDistribution); } VX_API_ENTRY vx_status VX_API_CALL vxReleaseDistribution(vx_distribution *d) { return ownReleaseReferenceInt((vx_reference *)d, VX_TYPE_DISTRIBUTION, VX_EXTERNAL, &ownDestructDistribution); } VX_API_ENTRY vx_status VX_API_CALL vxQueryDistribution(vx_distribution distribution, vx_enum attribute, void *ptr, vx_size size) { vx_status status = VX_SUCCESS; if (ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) == vx_false_e) return VX_ERROR_INVALID_REFERENCE; switch (attribute) { case VX_DISTRIBUTION_DIMENSIONS: if (VX_CHECK_PARAM(ptr, size, vx_size, 0x3)) { *(vx_size*)ptr = (vx_size)(distribution->memory.ndims - 1); } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_DISTRIBUTION_RANGE: if (VX_CHECK_PARAM(ptr, size, vx_uint32, 0x3)) { *(vx_uint32*)ptr = (vx_uint32)(distribution->range_x); } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_DISTRIBUTION_BINS: if (VX_CHECK_PARAM(ptr, size, vx_size, 0x3)) { *(vx_size*)ptr = (vx_size)distribution->memory.dims[0][VX_DIM_X]; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_DISTRIBUTION_WINDOW: if (VX_CHECK_PARAM(ptr, size, vx_uint32, 0x3)) { vx_size nbins = (vx_size)distribution->memory.dims[0][VX_DIM_X]; vx_uint32 range = (vx_uint32)(distribution->range_x); vx_uint32 window = (vx_uint32)(range / nbins); if (window*nbins == range) *(vx_uint32*)ptr = window; else *(vx_uint32*)ptr = 0; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_DISTRIBUTION_OFFSET: if (VX_CHECK_PARAM(ptr, size, vx_int32, 0x3)) { *(vx_int32*)ptr = distribution->offset_x; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_DISTRIBUTION_SIZE: if (VX_CHECK_PARAM(ptr, size, vx_size, 0x3)) { *(vx_size*)ptr = distribution->memory.strides[0][VX_DIM_C] * distribution->memory.dims[0][VX_DIM_X]; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; default: status = VX_ERROR_NOT_SUPPORTED; break; } return status; } VX_API_ENTRY vx_status VX_API_CALL vxAccessDistribution(vx_distribution distribution, void **ptr, vx_enum usage) { vx_status status = VX_FAILURE; (void)usage; if ((ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) == vx_true_e) && (ownAllocateMemory(distribution->base.context, &distribution->memory) == vx_true_e)) { if (ptr != NULL) { ownSemWait(&distribution->base.lock); { vx_size size = ownComputeMemorySize(&distribution->memory, 0); ownPrintMemory(&distribution->memory); if (*ptr == NULL) { *ptr = distribution->memory.ptrs[0]; } else if (*ptr != NULL) { memcpy(*ptr, distribution->memory.ptrs[0], size); } } ownSemPost(&distribution->base.lock); ownReadFromReference(&distribution->base); } ownIncrementReference(&distribution->base, VX_EXTERNAL); status = VX_SUCCESS; } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxCommitDistribution(vx_distribution distribution, const void *ptr) { vx_status status = VX_FAILURE; if ((ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) == vx_true_e) && (ownAllocateMemory(distribution->base.context, &distribution->memory) == vx_true_e)) { if (ptr != NULL) { ownSemWait(&distribution->base.lock); { if (ptr != distribution->memory.ptrs[0]) { vx_size size = ownComputeMemorySize(&distribution->memory, 0); memcpy(distribution->memory.ptrs[0], ptr, size); VX_PRINT(VX_ZONE_INFO, "Copied distribution from %p to %p for "VX_FMT_SIZE" bytes\n", ptr, distribution->memory.ptrs[0], size); } } ownSemPost(&distribution->base.lock); ownWroteToReference(&distribution->base); } ownDecrementReference(&distribution->base, VX_EXTERNAL); status = VX_SUCCESS; } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxCopyDistribution(vx_distribution distribution, void *user_ptr, vx_enum usage, vx_enum mem_type) { vx_status status = VX_FAILURE; vx_size size = 0; /* bad references */ if ((ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) != vx_true_e) || (ownAllocateMemory(distribution->base.context, &distribution->memory) != vx_true_e)) { status = VX_ERROR_INVALID_REFERENCE; VX_PRINT(VX_ZONE_ERROR, "Not a valid distribution object!\n"); return status; } /* bad parameters */ if (((usage != VX_READ_ONLY) && (usage != VX_WRITE_ONLY)) || (user_ptr == NULL) || (mem_type != VX_MEMORY_TYPE_HOST)) { status = VX_ERROR_INVALID_PARAMETERS; VX_PRINT(VX_ZONE_ERROR, "Invalid parameters to copy distribution\n"); return status; } /* copy data */ size = ownComputeMemorySize(&distribution->memory, 0); ownPrintMemory(&distribution->memory); #ifdef OPENVX_USE_OPENCL_INTEROP void * user_ptr_given = user_ptr; vx_enum mem_type_given = mem_type; if (mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { // get ptr from OpenCL buffer for HOST size_t size = 0; cl_mem opencl_buf = (cl_mem)user_ptr; cl_int cerr = clGetMemObjectInfo(opencl_buf, CL_MEM_SIZE, sizeof(size_t), &size, NULL); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxCopyDistribution: clGetMemObjectInfo(%p) => (%d)\n", opencl_buf, cerr); if (cerr != CL_SUCCESS) { return VX_ERROR_INVALID_PARAMETERS; } user_ptr = clEnqueueMapBuffer(distribution->base.context->opencl_command_queue, opencl_buf, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size, 0, NULL, NULL, &cerr); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxCopyDistribution: clEnqueueMapBuffer(%p,%d) => %p (%d)\n", opencl_buf, (int)size, user_ptr, cerr); if (cerr != CL_SUCCESS) { return VX_ERROR_INVALID_PARAMETERS; } mem_type = VX_MEMORY_TYPE_HOST; } #endif switch (usage) { case VX_READ_ONLY: if (ownSemWait(&distribution->base.lock) == vx_true_e) { memcpy(user_ptr, distribution->memory.ptrs[0], size); ownSemPost(&distribution->base.lock); ownReadFromReference(&distribution->base); status = VX_SUCCESS; } break; case VX_WRITE_ONLY: if (ownSemWait(&distribution->base.lock) == vx_true_e) { memcpy(distribution->memory.ptrs[0], user_ptr, size); ownSemPost(&distribution->base.lock); ownWroteToReference(&distribution->base); status = VX_SUCCESS; } break; } #ifdef OPENVX_USE_OPENCL_INTEROP if (mem_type_given == VX_MEMORY_TYPE_OPENCL_BUFFER) { clEnqueueUnmapMemObject(distribution->base.context->opencl_command_queue, (cl_mem)user_ptr_given, user_ptr, 0, NULL, NULL); clFinish(distribution->base.context->opencl_command_queue); } #endif return status; } VX_API_ENTRY vx_status VX_API_CALL vxMapDistribution(vx_distribution distribution, vx_map_id *map_id, void **ptr, vx_enum usage, vx_enum mem_type, vx_bitfield flags) { vx_status status = VX_FAILURE; vx_size size = 0; /* bad references */ if ((ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) != vx_true_e) || (ownAllocateMemory(distribution->base.context, &distribution->memory) != vx_true_e)) { status = VX_ERROR_INVALID_REFERENCE; VX_PRINT(VX_ZONE_ERROR, "Not a valid distribution object!\n"); return status; } #ifdef OPENVX_USE_OPENCL_INTEROP vx_enum mem_type_requested = mem_type; if (mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { mem_type = VX_MEMORY_TYPE_HOST; } #endif /* bad parameters */ if (((usage != VX_READ_ONLY) && (usage != VX_READ_AND_WRITE) && (usage != VX_WRITE_ONLY)) || (mem_type != VX_MEMORY_TYPE_HOST)) { status = VX_ERROR_INVALID_PARAMETERS; VX_PRINT(VX_ZONE_ERROR, "Invalid parameters to map distribution\n"); return status; } /* map data */ size = ownComputeMemorySize(&distribution->memory, 0); ownPrintMemory(&distribution->memory); if (ownMemoryMap(distribution->base.context, (vx_reference)distribution, size, usage, mem_type, flags, NULL, ptr, map_id) == vx_true_e) { switch (usage) { case VX_READ_ONLY: case VX_READ_AND_WRITE: if (ownSemWait(&distribution->base.lock) == vx_true_e) { memcpy(*ptr, distribution->memory.ptrs[0], size); ownSemPost(&distribution->base.lock); ownReadFromReference(&distribution->base); status = VX_SUCCESS; } break; case VX_WRITE_ONLY: status = VX_SUCCESS; break; } if (status == VX_SUCCESS) ownIncrementReference(&distribution->base, VX_EXTERNAL); } #ifdef OPENVX_USE_OPENCL_INTEROP if ((status == VX_SUCCESS) && distribution->base.context->opencl_context && (mem_type_requested == VX_MEMORY_TYPE_OPENCL_BUFFER) && (size > 0) && ptr && *ptr) { /* create OpenCL buffer using the host allocated pointer */ cl_int cerr = 0; cl_mem opencl_buf = clCreateBuffer(distribution->base.context->opencl_context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, size, *ptr, &cerr); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxMapDistribution: clCreateBuffer(%u) => %p (%d)\n", (vx_uint32)size, opencl_buf, cerr); if (cerr == CL_SUCCESS) { distribution->base.context->memory_maps[*map_id].opencl_buf = opencl_buf; *ptr = opencl_buf; } else { status = VX_FAILURE; } } #endif return status; } VX_API_ENTRY vx_status VX_API_CALL vxUnmapDistribution(vx_distribution distribution, vx_map_id map_id) { vx_status status = VX_FAILURE; vx_size size = 0; /* bad references */ if ((ownIsValidSpecificReference(&distribution->base, VX_TYPE_DISTRIBUTION) != vx_true_e) || (ownAllocateMemory(distribution->base.context, &distribution->memory) != vx_true_e)) { status = VX_ERROR_INVALID_REFERENCE; VX_PRINT(VX_ZONE_ERROR, "Not a valid distribution object!\n"); return status; } /* bad parameters */ if (ownFindMemoryMap(distribution->base.context, (vx_reference)distribution, map_id) != vx_true_e) { status = VX_ERROR_INVALID_PARAMETERS; VX_PRINT(VX_ZONE_ERROR, "Invalid parameters to unmap distribution\n"); return status; } #ifdef OPENVX_USE_OPENCL_INTEROP if (distribution->base.context->opencl_context && distribution->base.context->memory_maps[map_id].opencl_buf && distribution->base.context->memory_maps[map_id].ptr) { clEnqueueUnmapMemObject(distribution->base.context->opencl_command_queue, distribution->base.context->memory_maps[map_id].opencl_buf, distribution->base.context->memory_maps[map_id].ptr, 0, NULL, NULL); clFinish(distribution->base.context->opencl_command_queue); cl_int cerr = clReleaseMemObject(distribution->base.context->memory_maps[map_id].opencl_buf); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxUnmapDistribution: clReleaseMemObject(%p) => (%d)\n", distribution->base.context->memory_maps[map_id].opencl_buf, cerr); distribution->base.context->memory_maps[map_id].opencl_buf = NULL; } #endif /* unmap data */ size = ownComputeMemorySize(&distribution->memory, 0); ownPrintMemory(&distribution->memory); { vx_uint32 id = (vx_uint32)map_id; vx_memory_map_t* map = &distribution->base.context->memory_maps[id]; switch (map->usage) { case VX_READ_ONLY: status = VX_SUCCESS; break; case VX_READ_AND_WRITE: case VX_WRITE_ONLY: if (ownSemWait(&distribution->base.lock) == vx_true_e) { memcpy(distribution->memory.ptrs[0], map->ptr, size); ownSemPost(&distribution->base.lock); ownWroteToReference(&distribution->base); status = VX_SUCCESS; } break; } ownMemoryUnmap(distribution->base.context, (vx_uint32)map_id); /* regardless of the current status, if we're here, so previous call to vxMapDistribution() * was successful and thus ref was locked once by a call to ownIncrementReference() */ ownDecrementReference(&distribution->base, VX_EXTERNAL); } return status; }
35.588115
165
0.617781
[ "object" ]
c88e477e90e6abb7bd10f994245011e30c44645c
3,489
h
C
storage/src/tests/distributor/maintenancemocks.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-06-02T13:28:29.000Z
2020-06-02T13:28:29.000Z
storage/src/tests/distributor/maintenancemocks.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:24:20.000Z
2021-03-31T22:24:20.000Z
storage/src/tests/distributor/maintenancemocks.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-09-03T11:39:52.000Z
2020-09-03T11:39:52.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/document/test/make_bucket_space.h> #include <vespa/storage/distributor/maintenance/maintenanceprioritygenerator.h> #include <vespa/storage/distributor/maintenance/maintenanceoperationgenerator.h> #include <vespa/storage/distributor/operationstarter.h> #include <vespa/storage/distributor/operations/operation.h> #include <vespa/storageframework/defaultimplementation/clock/fakeclock.h> #include <sstream> using document::test::makeBucketSpace; namespace storage::distributor { class MockMaintenancePriorityGenerator : public MaintenancePriorityGenerator { MaintenancePriorityAndType prioritize( const document::Bucket&, NodeMaintenanceStatsTracker& stats) const override { stats.incMovingOut(1, makeBucketSpace()); stats.incCopyingIn(2, makeBucketSpace()); return MaintenancePriorityAndType( MaintenancePriority(MaintenancePriority::VERY_HIGH), MaintenanceOperation::MERGE_BUCKET); } }; class MockOperation : public MaintenanceOperation { document::Bucket _bucket; std::string _reason; bool _shouldBlock; public: MockOperation(const document::Bucket &bucket) : _bucket(bucket), _shouldBlock(false) {} std::string toString() const override { return _bucket.toString(); } void onClose(DistributorMessageSender&) override {} const char* getName() const override { return "MockOperation"; } const std::string& getDetailedReason() const override { return _reason; } void onStart(DistributorMessageSender&) override {} void onReceive(DistributorMessageSender&, const std::shared_ptr<api::StorageReply>&) override {} bool isBlocked(const PendingMessageTracker&) const override { return _shouldBlock; } void setShouldBlock(bool shouldBlock) { _shouldBlock = shouldBlock; } }; class MockMaintenanceOperationGenerator : public MaintenanceOperationGenerator { public: MaintenanceOperation::SP generate(const document::Bucket&bucket) const override { return MaintenanceOperation::SP(new MockOperation(bucket)); } std::vector<MaintenanceOperation::SP> generateAll( const document::Bucket &bucket, NodeMaintenanceStatsTracker& tracker) const override { (void) tracker; std::vector<MaintenanceOperation::SP> ret; ret.push_back(MaintenanceOperation::SP(new MockOperation(bucket))); return ret; } }; class MockOperationStarter : public OperationStarter { std::ostringstream _started; std::vector<Operation::SP> _operations; bool _shouldStart; public: MockOperationStarter() : _shouldStart(true) {} bool start(const std::shared_ptr<Operation>& operation, Priority priority) override { if (_shouldStart) { _started << operation->toString() << ", pri " << static_cast<int>(priority) << "\n"; _operations.push_back(operation); } return _shouldStart; } void setShouldStartOperations(bool shouldStart) { _shouldStart = shouldStart; } std::vector<Operation::SP>& getOperations() { return _operations; } std::string toString() const { return _started.str(); } }; }
29.567797
118
0.688449
[ "vector" ]
c89b53d8bbe1f1667aedb1b70fe2032463cf5cce
1,899
h
C
ur_modern_driver/include/ur_modern_driver/ur/messages_parser.h
harrycomeon/apriltags2_ros
8aeda468497042a22d953b14c604c1f3f8afdaf0
[ "BSD-2-Clause-FreeBSD" ]
16
2021-03-10T14:18:04.000Z
2022-03-16T02:18:22.000Z
ur_modern_driver/include/ur_modern_driver/ur/messages_parser.h
harrycomeon/apriltags2_ros
8aeda468497042a22d953b14c604c1f3f8afdaf0
[ "BSD-2-Clause-FreeBSD" ]
4
2021-03-23T08:50:22.000Z
2022-02-26T15:15:09.000Z
ur_modern_driver/include/ur_modern_driver/ur/messages_parser.h
harrycomeon/apriltags2_ros
8aeda468497042a22d953b14c604c1f3f8afdaf0
[ "BSD-2-Clause-FreeBSD" ]
6
2021-03-12T02:37:59.000Z
2022-02-16T09:19:41.000Z
/* * Copyright 2017, 2018 Simon Rasmussen (refactor) * * Copyright 2015, 2016 Thomas Timm Andersen (original version) * * 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 <vector> #include "ur_modern_driver/bin_parser.h" #include "ur_modern_driver/log.h" #include "ur_modern_driver/pipeline.h" #include "ur_modern_driver/ur/messages.h" #include "ur_modern_driver/ur/parser.h" class URMessageParser : public URParser<MessagePacket> { public: bool parse(BinParser& bp, std::vector<unique_ptr<MessagePacket>>& results) { int32_t packet_size; message_type type; bp.parse(packet_size); bp.parse(type); if (type != message_type::ROBOT_MESSAGE) { LOG_WARN("Invalid message type recieved: %u", static_cast<uint8_t>(type)); return false; } uint64_t timestamp; uint8_t source; robot_message_type message_type; bp.parse(timestamp); bp.parse(source); bp.parse(message_type); std::unique_ptr<MessagePacket> result; bool parsed = false; switch (message_type) { case robot_message_type::ROBOT_MESSAGE_VERSION: { VersionMessage* vm = new VersionMessage(timestamp, source); parsed = vm->parseWith(bp); result.reset(vm); break; } default: return false; } results.push_back(std::move(result)); return parsed; } };
26.746479
80
0.695629
[ "vector" ]
c89fa31e39f5a8941cc46a280ee8e441d5df1f91
13,729
h
C
ModelViewer/ViewerFoundation/Utilities/NuoModelBoard.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
265
2017-03-15T17:11:27.000Z
2022-03-30T07:50:00.000Z
ModelViewer/ViewerFoundation/Utilities/NuoModelBoard.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
6
2017-07-03T01:57:49.000Z
2020-01-24T19:28:22.000Z
ModelViewer/ViewerFoundation/Utilities/NuoModelBoard.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
39
2016-09-30T03:26:44.000Z
2022-01-24T07:37:20.000Z
// // NuoModelCube.hpp // ModelViewer // // Created by middleware on 5/22/17. // Copyright © 2017 middleware. All rights reserved. // #ifndef NuoModelBoard_hpp #define NuoModelBoard_hpp #include "NuoModelBase.h" #include "NuoModelTextured.h" template <class ItemBase> class NuoModelBoardBase : virtual public NuoModelCommon<ItemBase> { enum { kCorner_TL, kCorner_TR, kCorner_BL, kCorner_BR } kCorner; public: float _width; float _height; float _thickness; NuoModelBoardBase(float width, float height, float thickness); virtual void CreateBuffer(); private: }; class NuoModelBoard : virtual public NuoModelBoardBase<NuoItemSimple>, virtual public NuoModelSimple { // diffuse factor is used in ray tracing. the direct lighting shadow is independent from // the value, but indirect lighting will be affected // // set to 0.15 by default to simulate a dark plane. see more comments in // the "illumination_blend()" fragment shader // NuoVectorFloat3 _diffuse; NuoVectorFloat3 _specular; float _specularPower; public: NuoModelBoard(float width, float height, float thickness); void SetDiffuse(const NuoVectorFloat3& diffuse); const NuoVectorFloat3& GetDiffuse(); void SetSpecular(const NuoVectorFloat3& specular); const NuoVectorFloat3& GetSpecular(); void SetSpecularPower(float power); float GetSpecularPower(); virtual NuoGlobalBuffers GetGlobalBuffers() const override; }; typedef std::shared_ptr<NuoModelBoard> PNuoModelBoard; class NuoModelBackDrop : virtual public NuoModelBoardBase<NuoItemTextured>, virtual public NuoModelTextureBase<NuoItemTextured> { public: NuoModelBackDrop(float width, float height, float thickness); NuoModelBackDrop(const NuoModelBackDrop& other); IMPL_CLONE(NuoModelBackDrop); virtual void AddMaterial(const NuoMaterial& material) override; virtual NuoMaterial GetMaterial(size_t primtiveIndex) const override; virtual bool HasTransparent() override; virtual std::shared_ptr<NuoMaterial> GetUnifiedMaterial() override; virtual void UpdateBufferWithUnifiedMaterial() override; virtual void GenerateTangents() override; virtual void SetTexturePathBump(const std::string texPath) override; virtual std::string GetTexturePathBump() override; }; template <class ItemBase> NuoModelBoardBase<ItemBase>::NuoModelBoardBase(float width, float height, float thickness) : _width(width), _height(height), _thickness(thickness) { } template <class ItemBase> void NuoModelBoardBase<ItemBase>::CreateBuffer() { NuoVectorFloat2 corners[4]; corners[kCorner_BL].x(-_width / 2.0); corners[kCorner_BL].y(-_height / 2.0); corners[kCorner_BR].x(_width / 2.0); corners[kCorner_BR].y(-_height / 2.0); corners[kCorner_TL].x(-_width / 2.0); corners[kCorner_TL].y(_height / 2.0); corners[kCorner_TR].x(_width / 2.0); corners[kCorner_TR].y(_height / 2.0); std::vector<float> bufferPosition(9), bufferNormal(3), bufferTexCoord(6); float halfHeight = _thickness / 2.0; // top-half bufferPosition[0] = corners[kCorner_TL].x(); bufferPosition[1] = corners[kCorner_TL].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BL].x(); bufferPosition[4] = corners[kCorner_BL].y(); bufferPosition[5] = halfHeight; bufferPosition[6] = corners[kCorner_TR].x(); bufferPosition[7] = corners[kCorner_TR].y(); bufferPosition[8] = halfHeight; bufferNormal[0] = 0; bufferNormal[1] = 0; bufferNormal[2] = 1; bufferTexCoord[0] = 0.0; bufferTexCoord[1] = 0.0; bufferTexCoord[2] = 0.0; bufferTexCoord[3] = 1.0; bufferTexCoord[4] = 1.0; bufferTexCoord[5] = 0.0; this->AddPosition(0, bufferPosition); this->AddTexCoord(0, bufferTexCoord); this->AddNormal(0, bufferNormal); this->AddPosition(1, bufferPosition); this->AddTexCoord(1, bufferTexCoord); this->AddNormal(0, bufferNormal); this->AddPosition(2, bufferPosition); this->AddTexCoord(2, bufferTexCoord); this->AddNormal(0, bufferNormal); // top-half bufferPosition[0] = corners[kCorner_TR].x(); bufferPosition[1] = corners[kCorner_TR].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BL].x(); bufferPosition[4] = corners[kCorner_BL].y(); bufferPosition[5] = halfHeight; bufferPosition[6] = corners[kCorner_BR].x(); bufferPosition[7] = corners[kCorner_BR].y(); bufferPosition[8] = halfHeight; bufferTexCoord[0] = 1.0; bufferTexCoord[1] = 0.0; bufferTexCoord[2] = 0.0; bufferTexCoord[3] = 1.0; bufferTexCoord[4] = 1.0; bufferTexCoord[5] = 1.0; this->AddPosition(0, bufferPosition); this->AddTexCoord(0, bufferTexCoord); this->AddNormal(0, bufferNormal); this->AddPosition(1, bufferPosition); this->AddTexCoord(1, bufferTexCoord); this->AddNormal(0, bufferNormal); this->AddPosition(2, bufferPosition); this->AddTexCoord(2, bufferTexCoord); this->AddNormal(0, bufferNormal); // bottom-half bufferPosition[0] = corners[kCorner_TL].x(); bufferPosition[1] = corners[kCorner_TL].y(); bufferPosition[2] = -halfHeight; bufferPosition[3] = corners[kCorner_TR].x(); bufferPosition[4] = corners[kCorner_TR].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BL].x(); bufferPosition[7] = corners[kCorner_BL].y(); bufferPosition[8] = -halfHeight; bufferNormal[0] = 0; bufferNormal[1] = 0; bufferNormal[2] = -1; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // bottom-half bufferPosition[0] = corners[kCorner_TR].x(); bufferPosition[1] = corners[kCorner_TR].y(); bufferPosition[2] = -halfHeight; bufferPosition[3] = corners[kCorner_BR].x(); bufferPosition[4] = corners[kCorner_BR].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BL].x(); bufferPosition[7] = corners[kCorner_BL].y(); bufferPosition[8] = -halfHeight; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // front-half bufferPosition[0] = corners[kCorner_BL].x(); bufferPosition[1] = corners[kCorner_BL].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BL].x(); bufferPosition[4] = corners[kCorner_BL].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BR].x(); bufferPosition[7] = corners[kCorner_BR].y(); bufferPosition[8] = halfHeight; bufferNormal[0] = 0; bufferNormal[1] = -1; bufferNormal[2] = 0; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // front-half bufferPosition[0] = corners[kCorner_BR].x(); bufferPosition[1] = corners[kCorner_BR].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BL].x(); bufferPosition[4] = corners[kCorner_BL].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BR].x(); bufferPosition[7] = corners[kCorner_BR].y(); bufferPosition[8] = -halfHeight; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // left-half bufferPosition[0] = corners[kCorner_TL].x(); bufferPosition[1] = corners[kCorner_TL].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_TL].x(); bufferPosition[4] = corners[kCorner_TL].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BL].x(); bufferPosition[7] = corners[kCorner_BL].y(); bufferPosition[8] = halfHeight; bufferNormal[0] = -1; bufferNormal[1] = 0; bufferNormal[2] = 0; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // left-half bufferPosition[0] = corners[kCorner_BL].x(); bufferPosition[1] = corners[kCorner_BL].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_TL].x(); bufferPosition[4] = corners[kCorner_TL].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_BL].x(); bufferPosition[7] = corners[kCorner_BL].y(); bufferPosition[8] = -halfHeight; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // right-half bufferPosition[0] = corners[kCorner_BR].x(); bufferPosition[1] = corners[kCorner_BR].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BR].x(); bufferPosition[4] = corners[kCorner_BR].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_TR].x(); bufferPosition[7] = corners[kCorner_TR].y(); bufferPosition[8] = halfHeight; bufferNormal[0] = 1; bufferNormal[1] = 0; bufferNormal[2] = 0; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // right-half bufferPosition[0] = corners[kCorner_TR].x(); bufferPosition[1] = corners[kCorner_TR].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_BR].x(); bufferPosition[4] = corners[kCorner_BR].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_TR].x(); bufferPosition[7] = corners[kCorner_TR].y(); bufferPosition[8] = -halfHeight; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // back-half bufferPosition[0] = corners[kCorner_TR].x(); bufferPosition[1] = corners[kCorner_TR].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_TR].x(); bufferPosition[4] = corners[kCorner_TR].y(); bufferPosition[5] = -halfHeight; bufferPosition[6] = corners[kCorner_TL].x(); bufferPosition[7] = corners[kCorner_TL].y(); bufferPosition[8] = -halfHeight; bufferNormal[0] = 0; bufferNormal[1] = 1; bufferNormal[2] = 0; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); // back-half bufferPosition[0] = corners[kCorner_TL].x(); bufferPosition[1] = corners[kCorner_TL].y(); bufferPosition[2] = halfHeight; bufferPosition[3] = corners[kCorner_TR].x(); bufferPosition[4] = corners[kCorner_TR].y(); bufferPosition[5] = halfHeight; bufferPosition[6] = corners[kCorner_TL].x(); bufferPosition[7] = corners[kCorner_TL].y(); bufferPosition[8] = -halfHeight; NuoModelCommon<ItemBase>::AddPosition(0, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(1, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::AddPosition(2, bufferPosition); NuoModelCommon<ItemBase>::AddNormal(0, bufferNormal); NuoModelCommon<ItemBase>::GenerateIndices(); } #endif /* NuoModelCube_hpp */
33.898765
92
0.68898
[ "vector" ]
c8a05f184eff2a4d5853d6d7123cefba20f69240
7,545
h
C
src/mongo/base/error_extra_info.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/base/error_extra_info.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/base/error_extra_info.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include <memory> // This file is included by many low-level headers including status.h, so it isn't able to include // much without creating a cycle. #include "mongo/base/error_codes.h" #include "mongo/base/static_assert.h" namespace mongo { class BSONObj; class BSONObjBuilder; /** * Base class for the extra info that can be attached to commands. * * Actual implementations must have a 'constexpr ErrorCode::Error code' to indicate which * error code they bind to, and a static method with the following signature: * static std::shared_ptr<const ErrorExtraInfo> parse(const BSONObj&); * You must call the MONGO_INIT_REGISTER_ERROR_EXTRA_INFO(type) macro in the cpp file that contains * the implementation for your subtype. */ class ErrorExtraInfo { public: using Parser = std::shared_ptr<const ErrorExtraInfo>(const BSONObj&); ErrorExtraInfo() = default; virtual ~ErrorExtraInfo() = default; /** * Puts the extra info (and just the extra info) into builder. */ virtual void serialize(BSONObjBuilder* builder) const = 0; /** * Returns the registered parser for a given code or nullptr if none is registered. */ static Parser* parserFor(ErrorCodes::Error); /** * Use the MONGO_INIT_REGISTER_ERROR_EXTRA_INFO(type) macro below rather than calling this * directly. */ template <typename T> static void registerType() { MONGO_STATIC_ASSERT(std::is_base_of<ErrorExtraInfo, T>()); MONGO_STATIC_ASSERT(std::is_same<error_details::ErrorExtraInfoFor<T::code>, T>()); MONGO_STATIC_ASSERT(std::is_final<T>()); MONGO_STATIC_ASSERT(std::is_move_constructible<T>()); registerParser(T::code, T::parse); } /** * Fails fatally if any error codes that should have parsers registered don't. An invariant in * this function indicates that there isn't a MONGO_INIT_REGISTER_ERROR_EXTRA_INFO declaration * for some error code, which requires an extra info. * * Call this during startup of any shipping executable to prevent failures at runtime. */ static void invariantHaveAllParsers(); private: static void registerParser(ErrorCodes::Error code, Parser* parser); }; /** * Registers the parser for an ErrorExtraInfo subclass. This must be called at namespace scope in * the same cpp file as the virtual methods for that type. * * You must separately #include "mongo/base/init.h" since including it here would create an include * cycle. */ #define MONGO_INIT_REGISTER_ERROR_EXTRA_INFO(type) \ MONGO_INITIALIZER_GENERAL(RegisterErrorExtraInfoFor##type, (), ("default")) \ (InitializerContext*) { \ ErrorExtraInfo::registerType<type>(); \ } /** * This is an example ErrorExtraInfo subclass. It is used for testing the ErrorExtraInfoHandling. * * The default parser just throws a numeric code since this class should never be encountered in * production. A normal parser is activated while an EnableParserForTesting object is in scope. */ class ErrorExtraInfoExample final : public ErrorExtraInfo { public: static constexpr auto code = ErrorCodes::ForTestingErrorExtraInfo; void serialize(BSONObjBuilder*) const override; static std::shared_ptr<const ErrorExtraInfo> parse(const BSONObj&); // Everything else in this class is just for testing and shouldn't by copied by users. struct EnableParserForTest { EnableParserForTest() { isParserEnabledForTest = true; } ~EnableParserForTest() { isParserEnabledForTest = false; } }; ErrorExtraInfoExample(int data) : data(data) {} int data; // This uses the fieldname "data". private: static bool isParserEnabledForTest; }; /** * This is an example ErrorExtraInfo subclass. It is used for testing the ErrorExtraInfoHandling. * * It is meant to be a duplicate of ErrorExtraInfoExample, except that it is optional. This will * make sure we don't crash the server when an ErrorExtraInfo class is meant to be optional. */ class OptionalErrorExtraInfoExample final : public ErrorExtraInfo { public: static constexpr auto code = ErrorCodes::ForTestingOptionalErrorExtraInfo; void serialize(BSONObjBuilder*) const override; static std::shared_ptr<const ErrorExtraInfo> parse(const BSONObj&); // Everything else in this class is just for testing and shouldn't by copied by users. struct EnableParserForTest { EnableParserForTest() { isParserEnabledForTest = true; } ~EnableParserForTest() { isParserEnabledForTest = false; } }; OptionalErrorExtraInfoExample(int data) : data(data) {} int data; // This uses the fieldname "data". private: static bool isParserEnabledForTest; }; namespace nested::twice { /** * This is an example ErrorExtraInfo subclass. It is used for testing the ErrorExtraInfoHandling. * * It is meant to be a duplicate of ErrorExtraInfoExample, except that it is within a namespace * (and so exercises a different codepath in the parser). */ class NestedErrorExtraInfoExample final : public ErrorExtraInfo { public: static constexpr auto code = ErrorCodes::ForTestingErrorExtraInfoWithExtraInfoInNamespace; void serialize(BSONObjBuilder*) const override; static std::shared_ptr<const ErrorExtraInfo> parse(const BSONObj&); // Everything else in this class is just for testing and shouldn't by copied by users. struct EnableParserForTest { EnableParserForTest() { isParserEnabledForTest = true; } ~EnableParserForTest() { isParserEnabledForTest = false; } }; NestedErrorExtraInfoExample(int data) : data(data) {} int data; // This uses the fieldname "data". private: static bool isParserEnabledForTest; }; } // namespace nested::twice } // namespace mongo
36.804878
99
0.705368
[ "object" ]
c8aa9d09feed782424082ce54872fa93c4601dae
4,258
h
C
include/uecho/device.h
ammgws/uecho
b05de85e6269af9489731e35c2a408c3fdf37154
[ "BSD-3-Clause" ]
null
null
null
include/uecho/device.h
ammgws/uecho
b05de85e6269af9489731e35c2a408c3fdf37154
[ "BSD-3-Clause" ]
null
null
null
include/uecho/device.h
ammgws/uecho
b05de85e6269af9489731e35c2a408c3fdf37154
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * uEcho for C * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #ifndef _UECHO_DEVICE_H_ #define _UECHO_DEVICE_H_ #include <uecho/object.h> #ifdef __cplusplus extern "C" { #endif /**************************************** * Device ****************************************/ uEchoObject* uecho_device_new(void); /**************************************** * Device Object Super Class ****************************************/ typedef enum { uEchoDeviceOperatingStatus = 0x80, uEchoDeviceInstallationLocation = 0x81, uEchoDeviceStandardVersion = 0x82, uEchoDeviceIdentificationNumber = 0x83, uEchoDeviceMeasuredInstantaneousPowerConsumption = 0x84, uEchoDeviceMeasuredCumulativePowerConsumption = 0x85, uEchoDeviceManufacturerFaultCode = 0x86, uEchoDeviceCurrentLimitSetting = 0x87, uEchoDeviceFaultStatus = 0x88, uEchoDeviceFaultDescription = 0x89, uEchoDeviceManufacturerCode = uEchoObjectManufacturerCode, uEchoDeviceBusinessFacilityCode = 0x8B, uEchoDeviceProductCode = 0x8C, uEchoDeviceProductionNumber = 0x8D, uEchoDeviceProductionDate = 0x8E, uEchoDevicePowerSavingOperationSetting = 0x8F, uEchoDeviceRemoteControlSetting = 0x93, uEchoDeviceCurrentTimeSetting = 0x97, uEchoDeviceCurrentDateSetting = 0x98, uEchoDevicePowerLimitSetting = 0x99, uEchoDeviceCumulativeOperatingTime = 0x9A, uEchoDeviceAnnoPropertyMap = uEchoObjectAnnoPropertyMap, uEchoDeviceSetPropertyMap = uEchoObjectSetPropertyMap, uEchoDeviceGetPropertyMap = uEchoObjectGetPropertyMap, } uEchoDeviceEPC; typedef enum { uEchoDeviceOperatingStatusSize = 1, uEchoDeviceInstallationLocationSize = 1, uEchoDeviceStandardVersionSize = 4, uEchoDeviceIdentificationNumberSize = 9, uEchoDeviceMeasuredInstantaneousPowerConsumptionSize = 2, uEchoDeviceMeasuredCumulativePowerConsumptionSize = 4, uEchoDeviceManufacturerFaultCodeSize = 255, uEchoDeviceCurrentLimitSettingSize = 1, uEchoDeviceFaultStatusSize = 1, uEchoDeviceFaultDescriptionSize = 2, uEchoDeviceManufacturerCodeSize = uEchoObjectManufacturerCodeLen, uEchoDeviceBusinessFacilityCodeSize = 3, uEchoDeviceProductCodeSize = 12, uEchoDeviceProductionNumberSize = 12, uEchoDeviceProductionDateSize = 4, uEchoDevicePowerSavingOperationSettingSize = 1, uEchoDeviceRemoteControlSettingSize = 1, uEchoDeviceCurrentTimeSettingSize = 2, uEchoDeviceCurrentDateSettingSize = 4, uEchoDevicePowerLimitSettingSize = 2, uEchoDeviceCumulativeOperatingTimeSize = 5, uEchoDeviceAnnoPropertyMapSize = uEchoObjectAnnoPropertyMapMaxLen, uEchoDeviceSetPropertyMapSize = uEchoObjectSetPropertyMapMaxLen, uEchoDeviceGetPropertyMapSize = uEchoObjectGetPropertyMapMaxLen, } uEchoDevicenEPCSize; enum { uEchoDeviceOperatingStatusOn = 0x30, uEchoDeviceOperatingStatusOff = 0x31, uEchoDeviceVersionAppendixA = 'A', uEchoDeviceVersionAppendixB = 'B', uEchoDeviceVersionAppendixC = 'C', uEchoDeviceVersionAppendixD = 'D', uEchoDeviceVersionAppendixE = 'E', uEchoDeviceVersionAppendixF = 'F', uEchoDeviceVersionAppendixG = 'G', uEchoDeviceVersionUnknown = 0, uEchoDeviceDefaultVersionAppendix = uEchoDeviceVersionAppendixG, uEchoDeviceFaultOccurred = 0x41, uEchoDeviceNoFaultOccurred = 0x42, uEchoDeviceInstallationLocationUnknown = 0x00, }; bool uecho_device_addmandatoryproperties(uEchoObject* obj); bool uecho_device_setoperatingstatus(uEchoObject* obj, bool stats); bool uecho_device_setinstallationlocation(uEchoObject* obj, byte location); bool uecho_device_setstandardversion(uEchoObject* obj, char ver); bool uecho_device_setfaultstatus(uEchoObject* obj, bool stats); bool uecho_device_setmanufacturercode(uEchoObject* obj, uEchoManufacturerCode code); bool uecho_device_isoperatingstatus(uEchoObject* obj); byte uecho_device_getinstallationlocation(uEchoObject* obj); char uecho_device_getstandardversion(uEchoObject* obj); bool uecho_device_isfaultstatus(uEchoObject* obj); uEchoManufacturerCode uecho_device_getmanufacturercode(uEchoObject* obj); #ifdef __cplusplus } /* extern C */ #endif #endif /* _UECHO_NODE_H_ */
35.483333
84
0.767262
[ "object" ]
c8b02fb00ecfd09b1d4973d019cb4acb07d9452a
6,074
h
C
chrome/common/spellcheck_messages.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-01-16T03:57:39.000Z
2019-01-16T03:57:39.000Z
chrome/common/spellcheck_messages.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
chrome/common/spellcheck_messages.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // IPC messages for spellcheck. // Multiply-included message file, hence no include guard. #include "chrome/common/spellcheck_marker.h" #include "chrome/common/spellcheck_result.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_platform_file.h" #if !defined(ENABLE_SPELLCHECK) #error "Spellcheck should be enabled" #endif #define IPC_MESSAGE_START SpellCheckMsgStart IPC_ENUM_TRAITS(SpellCheckResult::Decoration) IPC_STRUCT_TRAITS_BEGIN(SpellCheckResult) IPC_STRUCT_TRAITS_MEMBER(decoration) IPC_STRUCT_TRAITS_MEMBER(location) IPC_STRUCT_TRAITS_MEMBER(length) IPC_STRUCT_TRAITS_MEMBER(replacement) IPC_STRUCT_TRAITS_MEMBER(hash) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(SpellCheckMarker) IPC_STRUCT_TRAITS_MEMBER(hash) IPC_STRUCT_TRAITS_MEMBER(offset) IPC_STRUCT_TRAITS_END() // Messages sent from the browser to the renderer. IPC_MESSAGE_CONTROL1(SpellCheckMsg_EnableSpellCheck, bool) // Passes some initialization params from the browser to the renderer's // spellchecker. This can be called directly after startup or in (async) // response to a RequestDictionary ViewHost message. IPC_MESSAGE_CONTROL4(SpellCheckMsg_Init, IPC::PlatformFileForTransit /* bdict_file */, std::set<std::string> /* custom_dict_words */, std::string /* language */, bool /* auto spell correct */) // Words have been added and removed in the custom dictionary; update the local // custom word list. IPC_MESSAGE_CONTROL2(SpellCheckMsg_CustomDictionaryChanged, std::vector<std::string> /* words_added */, std::vector<std::string> /* words_removed */) // Toggle the auto spell correct functionality. IPC_MESSAGE_CONTROL1(SpellCheckMsg_EnableAutoSpellCorrect, bool /* enable */) // Request a list of all document markers in the renderer for spelling service // feedback. IPC_MESSAGE_CONTROL0(SpellCheckMsg_RequestDocumentMarkers) // Send a list of document markers in the renderer to the spelling service // feedback sender. IPC_MESSAGE_CONTROL1(SpellCheckHostMsg_RespondDocumentMarkers, std::vector<uint32> /* document marker identifiers */) #if !defined(OS_MACOSX) // Sends text-check results from the Spelling service when the service finishes // checking text received by a SpellCheckHostMsg_CallSpellingService message. // If the service is not available, the 4th parameter should be false and the // 5th parameter should contain the requested sentence. IPC_MESSAGE_ROUTED4(SpellCheckMsg_RespondSpellingService, int /* request identifier given by WebKit */, bool /* succeeded calling service */, base::string16 /* sentence */, std::vector<SpellCheckResult>) #endif #if defined(OS_MACOSX) // This message tells the renderer to advance to the next misspelling. It is // sent when the user clicks the "Find Next" button on the spelling panel. IPC_MESSAGE_ROUTED0(SpellCheckMsg_AdvanceToNextMisspelling) // Sends when NSSpellChecker finishes checking text received by a preceding // SpellCheckHostMsg_RequestTextCheck message. IPC_MESSAGE_ROUTED2(SpellCheckMsg_RespondTextCheck, int /* request identifier given by WebKit */, std::vector<SpellCheckResult>) IPC_MESSAGE_ROUTED1(SpellCheckMsg_ToggleSpellPanel, bool) #endif // Messages sent from the renderer to the browser. // The renderer has tried to spell check a word, but couldn't because no // dictionary was available to load. Request that the browser find an // appropriate dictionary and return it. IPC_MESSAGE_CONTROL0(SpellCheckHostMsg_RequestDictionary) // Tracks spell checking occurrence to collect histogram. IPC_MESSAGE_ROUTED2(SpellCheckHostMsg_NotifyChecked, base::string16 /* word */, bool /* true if checked word is misspelled */) #if !defined(OS_MACOSX) // Asks the Spelling service to check text. When the service finishes checking // the input text, it sends a SpellingCheckMsg_RespondSpellingService with // text-check results. IPC_MESSAGE_CONTROL4(SpellCheckHostMsg_CallSpellingService, int /* route_id for response */, int /* request identifier given by WebKit */, base::string16 /* sentence */, std::vector<SpellCheckMarker> /* markers */) #endif #if defined(OS_MACOSX) // Tells the browser to display or not display the SpellingPanel IPC_MESSAGE_ROUTED1(SpellCheckHostMsg_ShowSpellingPanel, bool /* if true, then show it, otherwise hide it*/) // Tells the browser to update the spelling panel with the given word. IPC_MESSAGE_ROUTED1(SpellCheckHostMsg_UpdateSpellingPanelWithMisspelledWord, base::string16 /* the word to update the panel with */) // TODO(groby): This needs to originate from SpellcheckProvider. IPC_SYNC_MESSAGE_CONTROL2_1(SpellCheckHostMsg_CheckSpelling, base::string16 /* word */, int /* route_id */, bool /* correct */) IPC_SYNC_MESSAGE_CONTROL1_1(SpellCheckHostMsg_FillSuggestionList, base::string16 /* word */, std::vector<base::string16> /* suggestions */) IPC_MESSAGE_CONTROL4(SpellCheckHostMsg_RequestTextCheck, int /* route_id for response */, int /* request identifier given by WebKit */, base::string16 /* sentence */, std::vector<SpellCheckMarker> /* markers */) IPC_MESSAGE_ROUTED2(SpellCheckHostMsg_ToggleSpellCheck, bool /* enabled */, bool /* checked */) #endif // OS_MACOSX
41.60274
79
0.695258
[ "vector" ]
c8b46abe7ecea9e1ced0a4d53dc4802b5eba2ed7
621
c
C
IAED/LAB/08/exercicio1.c
pakhmomo/LeicA
981addd69bde5599fadabc589d920d0402597d95
[ "MIT" ]
2
2017-03-12T14:20:07.000Z
2017-07-02T23:39:04.000Z
IAED/LAB/08/exercicio1.c
pakhmomo/LeicA
981addd69bde5599fadabc589d920d0402597d95
[ "MIT" ]
null
null
null
IAED/LAB/08/exercicio1.c
pakhmomo/LeicA
981addd69bde5599fadabc589d920d0402597d95
[ "MIT" ]
null
null
null
# include <stdio.h> # include <stdlib.h> void le_n_numeros(int, int []); void mostra_positivos(int, int []); void le_n_numeros(int n, int vector[]){ int i; printf("A ler inteiros...\n"); for (i=0; i < n; ++i) scanf("%d", &vector[i]); } void mostra_positivos(int n, int vector[]){ int i; printf("A imprimir positivos...\n"); for (i=0; i<n; ++i) if (vector[i]>0) printf("%d\n", vector[i]); } int main(){ int n, *v; printf("Quantos inteiros?\n"); scanf("%d", &n); if (n>0) { v = (int *) malloc( sizeof(int)*n ); le_n_numeros(n, v); mostra_positivos(n, v); free(v); } return 0; }
12.9375
43
0.566828
[ "vector" ]
c8b5aef36fa257e0b5f631ee8d8c1b81f7ffff71
11,392
c
C
platform/mt6582/dummy_ap.c
foric/lk-lollipop
26bd7a9a4bb99eadc8e9e1211d009668c1c450a9
[ "MIT" ]
null
null
null
platform/mt6582/dummy_ap.c
foric/lk-lollipop
26bd7a9a4bb99eadc8e9e1211d009668c1c450a9
[ "MIT" ]
null
null
null
platform/mt6582/dummy_ap.c
foric/lk-lollipop
26bd7a9a4bb99eadc8e9e1211d009668c1c450a9
[ "MIT" ]
null
null
null
// Dummy AP #include <platform/boot_mode.h> #include <debug.h> #include <dev/uart.h> #include <platform/mtk_key.h> #include <target/cust_key.h> #include <platform/mt_gpio.h> #define MAX_MD_NUM (1) #define MAX_IMG_NUM (8) #define PART_HEADER_MAGIC (0x58881688) #define BOOT_ARGS_ADDR (0x87F00000) #define IMG_HEADER_ADDR (0x87F00000+1024) typedef enum{ DUMMY_AP_IMG = 0, MD1_IMG, MD1_RAM_DISK, MD2_IMG, MD2_RAM_DISK }img_idx_t; typedef struct _map { char name[32]; img_idx_t idx; }map_t; //typedef union //{ // struct // { // unsigned int magic; /* partition magic */ // unsigned int dsize; /* partition data size */ // char name[32]; /* partition name */ // unsigned int maddr; /* partition memory address */ // } info; // unsigned char data[512]; //} part_hdr_t; // Notice for MT6582 // Update LK BOOT_ARGUMENT structure /* typedef struct { unsigned int magic_number; BOOTMODE boot_mode; unsigned int e_flag; unsigned int log_port; unsigned int log_baudrate; unsigned char log_enable; unsigned char part_num; //<<<------- unsigned char reserved[2]; //<<<------- unsigned int dram_rank_num; unsigned int dram_rank_size[4]; unsigned int boot_reason; unsigned int meta_com_type; unsigned int meta_com_id; unsigned int boot_time; da_info_t da_info; SEC_LIMIT sec_limit; part_hdr_t *part_info; //<<<------ } BOOT_ARGUMENT; */ extern BOOT_ARGUMENT *g_boot_arg; //<<<----- //static BOOT_ARGUMENT *boot_args=BOOT_ARGS_ADDR; //static unsigned int *img_header_array = (unsigned int*)IMG_HEADER_ADDR; static unsigned int img_load_flag = 0; static part_hdr_t *img_info_start = NULL; static unsigned int img_addr_tbl[MAX_IMG_NUM]; static unsigned int img_size_tbl[MAX_IMG_NUM]; static map_t map_tbl[] = { {"DUMMY_AP", DUMMY_AP_IMG}, {"MD_IMG", MD1_IMG}, {"MD_RAM_DISK", MD1_RAM_DISK}, //{"MD2IMG", MD2_IMG}, //{"MD2_RAM_DISK", MD2_RAM_DISK}, }; extern int mt_set_gpio_mode_chip(unsigned int pin, unsigned int mode); int parse_img_header(unsigned int *start_addr, unsigned int img_num) //<<<------ { int i, j; int idx; if(start_addr == NULL) { printf("parse_img_header get invalid parameters!\n"); return -1; } img_info_start = (part_hdr_t*)start_addr; for(i=0; i<img_num; i++) //<<<------ { if(img_info_start[i].info.magic != PART_HEADER_MAGIC) continue; for(j=0; j<(sizeof(map_tbl)/sizeof(map_t)); j++) { if(strcmp(img_info_start[i].info.name, map_tbl[j].name) == 0) { idx = map_tbl[j].idx; img_addr_tbl[idx] = img_info_start[i].info.maddr; img_size_tbl[idx] = img_info_start[i].info.dsize; img_load_flag |= (1<<idx); printf("[%s] idx:%d, addr:0x%x, size:0x%x\n", map_tbl[j].name, idx, img_addr_tbl[idx], img_size_tbl[idx]); } } } return 0; } static int meta_detection(void) { int boot_mode = 0; // Put check bootmode code here if(g_boot_arg->boot_mode != NORMAL_BOOT) boot_mode = 1; //else if(mtk_detect_key(MT65XX_BOOT_MENU_KEY)) // boot_mode = 1; //boot_mode=0;//always enter normal mode //boot_mode=1;//always enter meta mode printf("Meta mode: %d, boot_mode: %d-v1)\n", boot_mode, g_boot_arg->boot_mode); return boot_mode; } static void md_gpio_config(unsigned int boot_md_id) { unsigned int tmp; volatile unsigned int loop = 10000; switch(boot_md_id) { case 0: printf("configure SIM GPIO as SIM mode\n"); //set GPIO as sim mode: GPIO0=SIM2_SCLK, GPIO1=SIM2_SIO, GPIO2=SIM1_SCLK, GPIO3=SIM1_SIO mt_set_gpio_mode(GPIO0, 1); //SIM2_SCLK mt_set_gpio_mode(GPIO1, 1); //SIM2_SIO mt_set_gpio_mode(GPIO2, 1); //SIM1_SCLK mt_set_gpio_mode(GPIO3, 1); //SIM1_SIO //set GPIO dir: SCLK=output, SIO=input mt_set_gpio_dir(GPIO0, GPIO_DIR_OUT); //GPIO0->SIM2_CLK, out mt_set_gpio_dir(GPIO1, GPIO_DIR_IN); //GPIO1->SIM2_SIO, in mt_set_gpio_dir(GPIO2, GPIO_DIR_OUT); //GPIO2->SIM1_CLK, out mt_set_gpio_dir(GPIO3, GPIO_DIR_IN); //GPIO3->SIM1_SIO, in #if 0 tmp = *((volatile unsigned int *)0x10005300); //GPIO_MODE0 //set GPIO as sim mode: GPIO0=SIM2_SCLK, GPIO1=SIM2_SIO, GPIO2=SIM1_SCLK, GPIO3=SIM1_SIO *((volatile unsigned int *)0x10005300) = tmp|(1<<0)|(1<<4)|(1<<8)|(1<<12); //set GPIO dir: SCLK=output, SIO=input *((volatile unsigned int *)0x10005004) = (1<<0)|(1<<2); //GPIO_DIR0_SET: GPIO0 & GPIO2 *((volatile unsigned int *)0x10005008) = (1<<1)|(1<<3); //GPIO_DIR0_CLR: GPIO1 & GPIO3 #endif #if 0 // MD uart gpio mt_set_gpio_mode_chip(77, 4); mt_set_gpio_mode_chip(78, 4); mt_set_gpio_mode_chip(44, 1); mt_set_gpio_mode_chip(45, 1); mt_set_gpio_mode_chip(46, 1); mt_set_gpio_mode_chip(47, 1); mt_set_gpio_mode_chip(48, 1); mt_set_gpio_mode_chip(49, 1); #endif break; case 1: // Put MD2 gpio configure code here break; } return; } static void md_emi_remapping(unsigned int boot_md_id) { unsigned int md_img_start_addr = 0; unsigned int md_emi_remapping_addr = 0; switch(boot_md_id) { case 0: // MD1 md_img_start_addr = img_addr_tbl[MD1_IMG] - 0x80000000; md_emi_remapping_addr = 0x10001300; // MD1 BANK0_MAP0 break; case 1: // MD2 md_img_start_addr = img_addr_tbl[MD2_IMG] - 0x80000000; md_emi_remapping_addr = 0x10001310; // MD2 BANK0_MAP0 break; default: break; } printf(" ---> Map 0x00000000 to %x for MD%d\n", md_img_start_addr+0x80000000, boot_md_id+1); *((volatile unsigned int*)md_emi_remapping_addr) = ((md_img_start_addr >> 24) | 1) & 0xFF; // For MD1 BANK0_MAP0 } static void md_power_up_mtcmos(unsigned int boot_md_id) { volatile unsigned int loop = 10000; loop =10000; while(loop-->0); switch(boot_md_id) { case 0://MD 1 //MD MTCMOS power on sequence *((volatile unsigned int *)0x10006284) |= 0x00000004; //SPM_MD1_PWR_CON |= PWR_ON_BIT loop = 10000; //delay 1us while(loop-->0); *((volatile unsigned int *)0x10006284) |= 0x00000008; //SPM_MD1_PWR_CON |= PWR_ON_S_BIT loop = 30000; //delay 3us while(loop-->0); //!(SPM_PWR_STATUS & 0x1) || !(SPM_PWR_STATUS_S & 0x1) while(!(*((volatile unsigned int *)0x1000660c)&0x1)|| !(*((volatile unsigned int *)0x10006610)&0x1)); //SRAM PDN *((volatile unsigned int *)0x10006284) &= ~(1<<8); //SPM_MD1_PWR_CON &= ~SRAM_PDN_BIT *((volatile unsigned int *)0x10006284) &= ~(1<<4); //SPM_MD1_PWR_CON &= ~PWR_CLK_DIS_BIT *((volatile unsigned int *)0x10006284) &= ~(1<<1); //SPM_MD1_PWR_CON &= ~PWR_ISO_BIT *((volatile unsigned int *)0x10006284) |= (1<<4); //SPM_MD1_PWR_CON |= PWR_CLK_DIS_BIT *((volatile unsigned int *)0x10006284) |= (1<<0); //SPM_MD1_PWR_CON |= PWR_RST_B_BIT *((volatile unsigned int *)0x10006284) &= ~(1<<4);//SPM_MD1_PWR_CON &= ~PWR_CLK_DIS_BIT //release bus protection *((volatile unsigned int *)0x10001220) &= ~((1<<10)|(1<<9)|(1<<8)|(1<<7)); //TOPAXI_PORT_STA1&=(~0x780) while(*((volatile unsigned int *)0x10001220)&((1<<10)|(1<<9)|(1<<8)|(1<<7))); break; case 1:// MD2 break; } } static void md_common_setting(int boot_md_id) { switch(boot_md_id) { case 0: // Put special setting here if needed //; ## Disable WDT //print "Disable MD1 WDT" printf("Disable MD1 WDT\n"); *((volatile unsigned int*)0x20050000) = 0x2200; //printf("setting md BPI GPIO-v1\n"); //*((volatile unsigned int*)0x10005410) &= 0x00111111; //*((volatile unsigned int*)0x10005410) |= 0x11000000; //*((volatile unsigned int*)0x10005400) &= 0x00000011; //*((volatile unsigned int*)0x10005400) |= 0x11111100; break; } } static void md_boot_up(unsigned int boot_md_id, unsigned int is_meta_mode) { switch(boot_md_id){ case 0:// For MD1 if(is_meta_mode) // Put META Register setting here *((volatile unsigned int*)0x20000010) |= 0x1; // Bit0, Meta mode flag, this need sync with MD init owner // Set boot slave to let MD to run *((volatile unsigned int*)0x2019379C) = 0x3567C766; // Key Register *((volatile unsigned int*)0x20190000) = 0x0; // Vector Register *((volatile unsigned int*)0x20195488) = 0xA3B66175; // Slave En Register break; case 1:// For MD2 break; default: break; } } int md_jtag_config(int boot_md_id) { // Add Jtag setting here return 0; } int get_input(void) { return 0; } void apply_env_setting(int case_id) { printf("Apply case:%d setting for dummy AP!\n", case_id); } void md_wdt_init(void); void dummy_ap_entry(void) { unsigned int is_meta_mode = 0; int md_check_tbl[] = {1<<MD1_IMG, 1<<MD2_IMG}; int i=0; int get_val; volatile unsigned int count; volatile unsigned int count1; // Disable WDT *(volatile unsigned int *)(0x10007000) = 0x22000000; printf("Welcome to use dummy AP!\n"); get_val = get_input(); apply_env_setting(get_val); // 0, Parse header info printf("Parsing image info!\n"); //parse_img_header(img_header_array); //<<<------ parse_img_header((unsigned int*)g_boot_arg->part_info, (unsigned int)g_boot_arg->part_num); printf("Begin to configure MD run env!\n"); for(i=0; i<MAX_MD_NUM; i++) { if(img_load_flag & md_check_tbl[i]) { printf("MD%d Enabled\n", i+1); // 1, Setup special GPIO request (RF/SIM/UART ... etc) //printf("Step 1: Configure special GPIO request!\n"); //md_gpio_config(i); // 2, Configure EMI remapping setting printf("Step 2: Configure EMI remapping...\n"); md_emi_remapping(i); // 3, Power up MD MTCMOS //printf("Step 3: Power up MD!\n"); //md_power_up_mtcmos(i); // 4, Configure DAP for ICE to connect to MD printf("Step 4: Configure DAP for ICE to connect to MD!\n"); md_jtag_config(i); // 5, Check boot Mode is_meta_mode = meta_detection(); printf("Step 5: Notify MD enter %s mode!\n", is_meta_mode ? "META" : "NORMAL"); // 6, MD register setting printf("Step 6: MD Common setting!\n"); md_common_setting(i); // 7, Boot up MD printf("Step 7: MD%d boot up with meta(%d)!\n", i+1, is_meta_mode); md_boot_up(i, is_meta_mode); printf("\nmd%d boot up done!!\n", i + 1); } } printf("All dummy AP config done, enter while(1), Yeah!!\n"); md_wdt_init(); count = 1; while(count--) { count1 = 0x80000000; while(count1--); } printf("Write MD WDT SWRST\n"); *((volatile unsigned int *)0x2005001C) = 0x1209; count = 1; while(count--) { count1 = 0x08000000; while(count1--); } printf("Read back STA:%x!!\n", *((volatile unsigned int*)0x2005000C)); while(1); } // EXT functions #include <sys/types.h> #include <debug.h> #include <err.h> #include <reg.h> #include <platform/mt_typedefs.h> #include <platform/mt_reg_base.h> #include <platform/mt_irq.h> #include <sys/types.h> #define GIC_PRIVATE_SIGNALS (32) #define MT_MD_WDT1_IRQ_ID (GIC_PRIVATE_SIGNALS + 179) void md_wdt_irq_handler(unsigned int irq) { printf("Get MD WDT irq, STA:%x!!\n", *((volatile unsigned int*)0x2005000C)); } void dummy_ap_irq_handler(unsigned int irq) { switch(irq){ case MT_MD_WDT1_IRQ_ID: md_wdt_irq_handler(MT_MD_WDT1_IRQ_ID); mt_irq_ack(MT_MD_WDT1_IRQ_ID); mt_irq_unmask(MT_MD_WDT1_IRQ_ID); break; default: break; } } void md_wdt_init(void) { mt_irq_set_sens(MT_MD_WDT1_IRQ_ID, MT65xx_EDGE_SENSITIVE); mt_irq_set_polarity(MT_MD_WDT1_IRQ_ID, MT65xx_POLARITY_LOW); mt_irq_unmask(MT_MD_WDT1_IRQ_ID); }
26.804706
113
0.670734
[ "vector" ]