hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
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
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
26409973a0eba8771b6b9d6b1a81367271d434f6
9,936
h
C
src/webnn/native/dml/GraphDML.h
wangli69087/webnn-native
8fc751ee87dd797137a6443a28b8dd34d0a4d692
[ "Apache-2.0" ]
null
null
null
src/webnn/native/dml/GraphDML.h
wangli69087/webnn-native
8fc751ee87dd797137a6443a28b8dd34d0a4d692
[ "Apache-2.0" ]
null
null
null
src/webnn/native/dml/GraphDML.h
wangli69087/webnn-native
8fc751ee87dd797137a6443a28b8dd34d0a4d692
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The WebNN-native Authors // // 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 WEBNN_NATIVE_DML_MODEL_DML_H_ #define WEBNN_NATIVE_DML_MODEL_DML_H_ #define DML_TARGET_VERSION_USE_LATEST 1 #include <dxgi1_4.h> #include <dxgi1_6.h> #include <wrl\client.h> #include <unordered_map> #include <unordered_set> #include "DirectML.h" #include "webnn/native/Graph.h" #include "webnn/native/Operand.h" #include "webnn/native/Operator.h" #include "webnn/native/dml/ContextDML.h" #include "webnn/native/ops/BatchNorm.h" #include "webnn/native/ops/Binary.h" #include "webnn/native/ops/Clamp.h" #include "webnn/native/ops/Concat.h" #include "webnn/native/ops/Constant.h" #include "webnn/native/ops/Conv2d.h" #include "webnn/native/ops/Gemm.h" #include "webnn/native/ops/Gru.h" #include "webnn/native/ops/Input.h" #include "webnn/native/ops/InstanceNorm.h" #include "webnn/native/ops/LeakyRelu.h" #include "webnn/native/ops/Pad.h" #include "webnn/native/ops/Pool2d.h" #include "webnn/native/ops/Reduce.h" #include "webnn/native/ops/Resample2d.h" #include "webnn/native/ops/Reshape.h" #include "webnn/native/ops/Slice.h" #include "webnn/native/ops/Split.h" #include "webnn/native/ops/Squeeze.h" #include "webnn/native/ops/Transpose.h" #include "webnn/native/ops/Unary.h" namespace webnn::native { namespace dml { using namespace Microsoft::WRL; // Represent the DirectML tensor description. struct DmlTensorDesc { std::vector<UINT> dimensions = {}; std::vector<UINT> strides = {}; // Describes a tensor that will be stored in a Direct3D 12 buffer resource. DML_BUFFER_TENSOR_DESC bufferDesc = {}; }; // Represent the information of the graph's edges. struct EdgeInfoBase { virtual ~EdgeInfoBase() = default; DML_TENSOR_DESC outputTensorDESC = {}; std::string name = ""; bool isInputEdge = false; }; // Only represent the information of the input edges. struct InputEdgeInfo final : public EdgeInfoBase { ~InputEdgeInfo() override = default; // Indicate the index of the graph's input. size_t inputIndex = 0; void const* buffer = nullptr; size_t byteLength = 0; // Indicate if the input is from constant buffer which need to be // uploaded in the stage of initialization. bool isConstantInput = false; }; // Represent the information of the intermediate edges and output edges. struct EdgeInfo final : public EdgeInfoBase { ~EdgeInfo() override = default; // Indicate the index of the intermediate node from which this edge was produced. uint32_t nodeIndex = 0; // Indicate the index of the intermediate node' output from which this edge was produced. uint32_t outputNodeIndex = 0; }; class Graph : public GraphBase { public: explicit Graph(Context* context); ~Graph() override = default; virtual MaybeError AddConstant(const op::Constant* constant) override; virtual MaybeError AddInput(const op::Input* input) override; virtual MaybeError AddOutput(std::string_view name, const OperandBase* output) override; virtual MaybeError AddBatchNorm(const op::BatchNorm* batchNorm) override; virtual MaybeError AddBinary(const op::Binary* binary) override; virtual MaybeError AddConv2d(const op::Conv2d* conv2d) override; virtual MaybeError AddConvTranspose2d(const op::ConvTranspose2d* convTranspose2d) override; virtual MaybeError AddPad(const op::Pad* pad) override; virtual MaybeError AddPool2d(const op::Pool2d* pool2d) override; virtual MaybeError AddReduce(const op::Reduce* reduce) override; virtual MaybeError AddResample2d(const op::Resample2d* resample2d) override; virtual MaybeError AddReshape(const op::Reshape* reshape) override; virtual MaybeError AddSlice(const op::Slice* slice) override; virtual MaybeError AddSplit(const op::Split* split) override; virtual MaybeError AddSqueeze(const op::Squeeze* squeeze) override; virtual MaybeError AddTranspose(const op::Transpose* transpose) override; virtual MaybeError AddUnary(const op::Unary* unary) override; virtual MaybeError AddGemm(const op::Gemm* Gemm) override; virtual MaybeError AddGru(const op::Gru* Gru) override; virtual MaybeError AddConcat(const op::Concat* concat) override; virtual MaybeError AddClamp(const op::Clamp* clamp) override; virtual MaybeError AddInstanceNorm(const op::InstanceNorm* instanceNorm) override; virtual MaybeError Finish() override; void AddEdgesToThisNode(std::vector<std::shared_ptr<EdgeInfoBase>> inputNodes); void FillUploadResourceAndInputBindings( uint64_t uploadResourceSize, std::vector<DML_BUFFER_BINDING>& inputBufferBinding, std::unordered_map<std::string, Input> namedInputs = {}); MaybeError createConstantInput(DML_TENSOR_DESC& inputTensorDESC, void const* value, size_t size, const std::vector<UINT>& dmlTensorDims, const std::vector<UINT>& strides = {}, DML_TENSOR_DATA_TYPE dataType = DML_TENSOR_DATA_TYPE_FLOAT32, DML_TENSOR_FLAGS tensorFlag = DML_TENSOR_FLAG_OWNED_BY_DML); std::shared_ptr<EdgeInfoBase> Clamp(const op::ClampBase* clamp, std::shared_ptr<EdgeInfoBase> inputEdge); MaybeError HardSwish(std::shared_ptr<EdgeInfoBase>& inputEdge, const std::vector<UINT>& inputDims); MaybeError EmulateFusedOperator(FusionOperatorBase* activation, std::shared_ptr<EdgeInfoBase>& inputEdge, const std::vector<UINT>& inputDims); MaybeError TransposeOutputToNhwc(std::shared_ptr<EdgeInfoBase>& inputEdge, const std::vector<UINT>& nchwOutputDims); private: MaybeError CompileImpl() override; MaybeError ComputeImpl(NamedInputsBase* inputs, NamedOutputsBase* outputs) override; // Represents a DirectML device, which is used to create operators, binding tables, command // recorders, and other objects. ComPtr<IDMLDevice> mDevice; // The IDMLDevice1 interface inherits from IDMLDevice. ComPtr<IDMLDevice1> mDevice1; // Represents a virtual adapter; it is used to create command allocators, command lists, // command queues, fences, resources, pipeline state objects, heaps, root signatures, // samplers, and many resource views. ComPtr<ID3D12Device> mD3D12Device; ComPtr<IDMLCommandRecorder> mCommandRecorder; ComPtr<ID3D12CommandQueue> mCommandQueue; ComPtr<ID3D12CommandAllocator> mCommandAllocator; ComPtr<ID3D12GraphicsCommandList> mCommandList; ComPtr<IDMLBindingTable> mBindingTable; ComPtr<ID3D12DescriptorHeap> mDescriptorHeap; ComPtr<ID3D12Resource> mUploadResource; ComPtr<ID3D12Resource> mInputResource; ComPtr<ID3D12Resource> mOutputResource; ComPtr<ID3D12Resource> mReadBackResource; ComPtr<ID3D12Resource> mTemporaryResource; ComPtr<ID3D12Resource> mPersistentResource; uint64_t mCommonInputsResourceSize = 0; uint64_t mOutputsResourceSize = 0; UINT64 mTemporaryResourceSize = 0; UINT64 mPersistentResourceSize = 0; // Describe a graph of DirectML operators used to compile a combined, optimized operator. std::vector<std::shared_ptr<InputEdgeInfo>> mInputs; std::vector<EdgeInfo> mOutputs; std::vector<DML_GRAPH_NODE_DESC> mIntermediateNodes; std::vector<DML_GRAPH_EDGE_DESC> mInputEdges; std::vector<DML_GRAPH_EDGE_DESC> mOutputEdges; std::vector<DML_GRAPH_EDGE_DESC> mIntermediateEdges; // IDMLCompiledOperator represents the DirectML graph's output which need to be initialized // by IDMLOperatorInitializer. ComPtr<IDMLCompiledOperator> mCompiledOperator; DML_BINDING_TABLE_DESC mBindingTableDesc; std::map<const OperandBase*, std::shared_ptr<EdgeInfoBase>> mGraphEdgesMap; // Keep intermediate nodes here to avoid releasing too early. std::map<uint32_t, ComPtr<IDMLOperator>> mIntermediateNodesMap; // Keep the input tensors description here to avoid releasing too early. std::vector<std::shared_ptr<DmlTensorDesc>> mDmlTensorsDesc; // Keep the descriptions of nodes and edges here to avoid releasing too early. std::vector<std::unique_ptr<DML_OPERATOR_GRAPH_NODE_DESC>> mIntermediateNodesDesc; std::vector<std::unique_ptr<DML_INPUT_GRAPH_EDGE_DESC>> mInputEdgesDesc; std::vector<std::unique_ptr<DML_OUTPUT_GRAPH_EDGE_DESC>> mOutputEdgesDesc; std::vector<std::unique_ptr<DML_INTERMEDIATE_GRAPH_EDGE_DESC>> mIntermediateEdgesDesc; std::unordered_set<const OperandBase*> mConstantSet; std::vector<std::unique_ptr<char>> mConstantsBuffer; }; }} // namespace webnn::native::dml #endif // WEBNN_NATIVE_DML_MODEL_DML_H_
48
100
0.69213
83cef2e4fc72202b960a00c0eb52b5a952234963
1,046
h
C
Reliant/Classes/OCSReliantExcludingPropertyProvider.h
appfoundry/Reliant
cbb2429446eba0b3c47004155db6c89702511f06
[ "MIT" ]
36
2015-01-12T16:43:07.000Z
2021-06-30T03:31:12.000Z
Reliant/Classes/OCSReliantExcludingPropertyProvider.h
appfoundry/Reliant
cbb2429446eba0b3c47004155db6c89702511f06
[ "MIT" ]
17
2015-11-26T13:06:10.000Z
2016-06-03T09:37:53.000Z
Reliant/Classes/OCSReliantExcludingPropertyProvider.h
appfoundry/Reliant
cbb2429446eba0b3c47004155db6c89702511f06
[ "MIT" ]
8
2015-02-18T07:53:08.000Z
2018-04-27T11:45:19.000Z
// // OCSReliantExcludingPropertyProvider.h // Reliant // // Created by Michael Seghers on 27/10/13. // // #import <Foundation/Foundation.h> /** Mark your object to conform to this protocol to make sure reliant does not try to inject properties which where not meant for injection. This protocol is adopted by NSObject, UIResponder and UIViewController categories out of the box. REMARK: Normally you should not need to adopt this protocol, as reliant will only try to inject properties with a name known by the injecting context. Only if you have a property named the same as an object in this context which should be ignored for injection, should you adopt this protocol. */ @protocol OCSReliantExcludingPropertyProvider <NSObject> /** Returns YES if the property with the given name should be ignored by reliant. Returns NO if reliant can inject the property. @param name the name of the property which is passed in by Reliant to test if it should be ignored. */ + (BOOL)ocsReliantShouldIgnorePropertyWithName:(NSString *) name; @end
36.068966
136
0.782983
afd86838d8af992d768574151b921939e6da6120
4,360
c
C
base/w32_sound - Copy.c
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
1
2016-12-28T05:46:24.000Z
2016-12-28T05:46:24.000Z
base/w32_sound - Copy.c
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
null
null
null
base/w32_sound - Copy.c
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
null
null
null
#include <stdio.h> #include <bteifgl.h> #ifdef _WIN32 #include <windows.h> #include <mmsystem.h> #define WAV_BUFFERS 16 #define WAV_MASK (WAV_BUFFERS-1) #define WAV_BUFFER_SIZE 0x1000 #define SECONDARY_BUFFER_SIZE 0x10000 HWAVEOUT hWaveOut; DWORD gSndBufSize; HANDLE hData; HPSTR lpData, lpData2; HGLOBAL hWaveHdr; LPWAVEHDR lpWaveHdr; static int sample16, samples; static int snd_sent, snd_completed; static short *snd_rover; BTEIFGL_API int SoundDev_DeInit() { int i; waveOutReset(hWaveOut); if(lpWaveHdr) { for(i=0; i<WAV_BUFFERS; i++) waveOutUnprepareHeader(hWaveOut, lpWaveHdr+i, sizeof(WAVEHDR)); } waveOutClose(hWaveOut); if(hWaveHdr) { GlobalUnlock(hWaveHdr); GlobalFree(hWaveHdr); } if(hData) { GlobalUnlock(hData); GlobalFree(hData); } return(0); } BTEIFGL_API int SoundDev_Init() { WAVEFORMATEX format; int i, j; HRESULT hr; short *buf; snd_sent=0; snd_completed=0; memset(&format, 0, sizeof(format)); format.wFormatTag=WAVE_FORMAT_PCM; format.nChannels=1; format.wBitsPerSample=16; format.nSamplesPerSec=44100; format.nBlockAlign=format.nChannels*format.wBitsPerSample/8; format.cbSize=0; format.nAvgBytesPerSec=format.nSamplesPerSec*format.nBlockAlign; /* Open a waveform device for output using window callback. */ while((hr=waveOutOpen((LPHWAVEOUT)&hWaveOut, WAVE_MAPPER, &format, 0, 0L, CALLBACK_NULL))!=MMSYSERR_NOERROR) { printf("waveOutOpen failed\n"); return(-1); } gSndBufSize=WAV_BUFFERS*WAV_BUFFER_SIZE; hData=GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, gSndBufSize); if(!hData) { printf("Sound: Out of memory.\n"); SoundDev_DeInit(); return(-1); } lpData=GlobalLock(hData); if(!lpData) { printf("Sound: Failed to lock.\n"); SoundDev_DeInit(); return(-1); } memset(lpData, 0, gSndBufSize); hWaveHdr=GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, (DWORD) sizeof(WAVEHDR)*WAV_BUFFERS); if(hWaveHdr==NULL) { printf("Sound: Failed to Alloc header.\n"); SoundDev_DeInit(); return(-1); } lpWaveHdr =(LPWAVEHDR) GlobalLock(hWaveHdr); if(lpWaveHdr==NULL) { printf("Sound: Failed to lock header.\n"); SoundDev_DeInit(); return(-1); } memset(lpWaveHdr, 0, sizeof(WAVEHDR)*WAV_BUFFERS); /* After allocation, set up and prepare headers. */ for(i=0; i<WAV_BUFFERS; i++) { lpWaveHdr[i].dwBufferLength=WAV_BUFFER_SIZE; lpWaveHdr[i].lpData=lpData+i*WAV_BUFFER_SIZE; if(waveOutPrepareHeader(hWaveOut, lpWaveHdr+i, sizeof(WAVEHDR)) != MMSYSERR_NOERROR) { printf("Sound: failed to prepare wave headers\n"); SoundDev_DeInit(); return(-1); } } samples=gSndBufSize/(16/8); sample16 =(16/8)-1; return(0); } BTEIFGL_API int SoundDev_GetDMAPos() { MMTIME tm; int i, s; s=snd_sent*WAV_BUFFER_SIZE; s>>=sample16; s&=(samples-1); return(s); } BTEIFGL_API void SoundDev_Submit() { LPWAVEHDR h; int wResult; while(1) { if(snd_completed==snd_sent) { // printf("Sound overrun\n"); break; } if(!(lpWaveHdr[snd_completed&WAV_MASK].dwFlags&WHDR_DONE)) break; snd_completed++; // this buffer has been played } while(((snd_sent-snd_completed)>>sample16)<4) { h=lpWaveHdr+(snd_sent&WAV_MASK); snd_sent++; wResult=waveOutWrite(hWaveOut, h, sizeof(WAVEHDR)); if(wResult!=MMSYSERR_NOERROR) { printf("Failed to write block to device\n"); SoundDev_DeInit(); return; } } } BTEIFGL_API int SoundDev_PaintSamples(short *buffer, int cnt) { int l; short *buf, *rover; // printf("Writing %d samples\n", cnt); buf=(short *)lpData; rover=snd_rover; while(((rover-buf)+cnt)>=samples) { l=samples-(rover-buf); memcpy(rover, buffer, l*sizeof(short)); rover=buf; buffer+=l; cnt-=l; } if(cnt>0)memcpy(rover, buffer, cnt*sizeof(short)); return(0); } BTEIFGL_API int SoundDev_WriteSamples(short *buffer, int cnt) { int i, l; short *buf, *dma; static short *ldma; // printf("Writing %d samples\n", cnt); buf=(short *)lpData; dma=buf+SoundDev_GetDMAPos(); if(!snd_rover)snd_rover=dma; if(abs(snd_rover-dma)>(44100/10) && (dma>ldma)) { // printf("Sound sync %d\n", snd_rover-dma); snd_rover=dma; } ldma=dma; SoundDev_PaintSamples(buffer, cnt); snd_rover+=cnt; while((snd_rover-buf)>=samples) snd_rover-=samples; SoundDev_PaintSamples(buffer, cnt); SoundDev_Submit(); return(0); } #endif
17.370518
68
0.693578
9f1cbdaf1fdfb24ca4eb219ea9f3f89d5a35374b
1,039
h
C
Twitter-Dumped/7.60.6/TFNKeyboardDismissalContainerViewDelegate-Protocol.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
1
2019-10-15T09:26:49.000Z
2019-10-15T09:26:49.000Z
Twitter-Dumped/7.52/TFNKeyboardDismissalContainerViewDelegate-Protocol.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
null
null
null
Twitter-Dumped/7.52/TFNKeyboardDismissalContainerViewDelegate-Protocol.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
1
2019-11-17T06:06:49.000Z
2019-11-17T06:06:49.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <T1Twitter/NSObject-Protocol.h> @class TFNKeyboardDismissalContainerView; @protocol TFNKeyboardDismissalContainerViewDelegate <NSObject> @optional - (void)keyboardDismissalContainerView:(TFNKeyboardDismissalContainerView *)arg1 didEndDraggingWithVelocity:(struct CGPoint)arg2 state:(unsigned long long)arg3; - (void)keyboardDismissalContainerView:(TFNKeyboardDismissalContainerView *)arg1 didChangeDraggingWithTranslation:(struct CGPoint)arg2; - (void)keyboardDismissalContainerViewDidBeginDragging:(TFNKeyboardDismissalContainerView *)arg1; - (_Bool)keyboardDismissalContainerView:(TFNKeyboardDismissalContainerView *)arg1 shouldBeginDraggingAtLocation:(struct CGPoint)arg2 velocity:(struct CGPoint)arg3; - (void)keyboardDismissalContainerView:(TFNKeyboardDismissalContainerView *)arg1 keyboardDidChangeFrameInView:(struct CGRect)arg2; @end
49.47619
163
0.829644
37b9f402f79ae3a7927efe327ea47fc8250c5a2b
298
h
C
HM2/HM2/Classes/Main/Catogra/NSString+HMExtension.h
jql244109084/HM
fca3c146c7acf481ebcea5929533a6e1e28c628b
[ "Apache-2.0" ]
null
null
null
HM2/HM2/Classes/Main/Catogra/NSString+HMExtension.h
jql244109084/HM
fca3c146c7acf481ebcea5929533a6e1e28c628b
[ "Apache-2.0" ]
null
null
null
HM2/HM2/Classes/Main/Catogra/NSString+HMExtension.h
jql244109084/HM
fca3c146c7acf481ebcea5929533a6e1e28c628b
[ "Apache-2.0" ]
null
null
null
// // NSString+HMExtension.h // HM2 // // Created by 焦起龙 on 17/1/5. // Copyright © 2017年 JqlLove. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (HMExtension) - (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW; - (CGSize)sizeWithFont:(UIFont *)font; @end
19.866667
57
0.697987
9b1025ff6148fa0210625d97917fda6fdcc7b77e
7,803
h
C
components/character_sounds.h
ZamfirYonchev/simple_game_engine
1a93244534c67673a7ab62a2df0acb2938b4c6a0
[ "MIT" ]
null
null
null
components/character_sounds.h
ZamfirYonchev/simple_game_engine
1a93244534c67673a7ab62a2df0acb2938b4c6a0
[ "MIT" ]
null
null
null
components/character_sounds.h
ZamfirYonchev/simple_game_engine
1a93244534c67673a7ab62a2df0acb2938b4c6a0
[ "MIT" ]
null
null
null
/* * character_sounds.h * * Created on: Nov 22, 2020 * Author: zamfi */ #ifndef COMPONENTS_CHARACTER_SOUNDS_H_ #define COMPONENTS_CHARACTER_SOUNDS_H_ #include "../types.h" #include "collision_enums.h" template<typename ControlT, typename MovementT, typename CollisionT, typename HealthT> class CharacterSounds { public: enum class State { IDLE, WALK, JUMP, FALL, ATTACK, HIT, DEAD} ; constexpr static Time LONG_IDLE_TIMEOUT = 5000; CharacterSounds ( const SoundID idle_id , const SoundID walk_id , const SoundID jump_id , const SoundID fall_id , const SoundID land_id , const SoundID attack_id , const SoundID hit_id , const SoundID dead_id , const double volume , const EntityID self_id , ComponentAccess<const ControlT> control_accessor , ComponentAccess<const MovementT> movement_accessor , ComponentAccess<const CollisionT> collision_accessor , ComponentAccess<const HealthT> health_accessor ) : m_self_id(self_id) , m_play_new_sound(false) , m_current_sound_id(-1) , m_idle_id(idle_id) , m_walk_id(walk_id) , m_jump_id(jump_id) , m_fall_id(fall_id) , m_land_id(land_id) , m_attack_id(attack_id) , m_hit_id(hit_id) , m_dead_id(dead_id) , m_volume(volume) , m_state(State::IDLE) , m_control_accessor{std::move(control_accessor)} , m_movement_accessor{std::move(movement_accessor)} , m_collision_accessor{std::move(collision_accessor)} , m_health_accessor{std::move(health_accessor)} {} template<typename ExtractorF, typename SelfIDObtainerF> CharacterSounds ( ExtractorF&& extract , const SelfIDObtainerF& obtain_self_id , ComponentAccess<const ControlT> control_accessor , ComponentAccess<const MovementT> movement_accessor , ComponentAccess<const CollisionT> collision_accessor , ComponentAccess<const HealthT> health_accessor ) : CharacterSounds { extract() , extract() , extract() , extract() , extract() , extract() , extract() , extract() , extract() , obtain_self_id() , std::move(control_accessor) , std::move(movement_accessor) , std::move(collision_accessor) , std::move(health_accessor) } {} template<typename InserterF> void obtain(InserterF&& insert) const { insert("UseCharacterSounds"); insert(m_idle_id); insert(m_walk_id); insert(m_jump_id); insert(m_fall_id); insert(m_land_id); insert(m_attack_id); insert(m_hit_id); insert(m_dead_id); insert(m_volume); } void set_new_state(const State new_state) { m_play_new_sound = true; m_state = new_state; switch(new_state) { case State::IDLE : m_current_sound_id = m_idle_id; break; case State::WALK : m_current_sound_id = m_walk_id; break; case State::JUMP : m_current_sound_id = m_jump_id; break; case State::FALL : m_current_sound_id = m_fall_id; break; case State::ATTACK : m_current_sound_id = m_attack_id; break; case State::HIT : m_current_sound_id = m_hit_id; break; case State::DEAD : m_current_sound_id = m_dead_id; break; default: m_current_sound_id = -1; break; } } void update(const Time time_diff) { m_play_new_sound = false; const auto& control = m_control_accessor(m_self_id); const auto& movement = m_movement_accessor(m_self_id); const auto& collision = m_collision_accessor(m_self_id); const auto& health = m_health_accessor(m_self_id); switch(m_state) { case State::IDLE: if(health.alive() == false) set_new_state(State::DEAD); else if(health.stunned()) set_new_state(State::HIT); else if(control.decision_attack()) set_new_state(State::ATTACK); else if(collision.standing_on()!=SurfaceType::GROUND && (control.decision_vertical() > 0)) set_new_state(State::JUMP); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_walk() != 0)) set_new_state(State::WALK); else if(collision.standing_on()==SurfaceType::AIR && movement.vy() < -1) set_new_state(State::FALL); break; case State::WALK: if(health.alive() == false) set_new_state(State::DEAD); else if(health.stunned()) set_new_state(State::HIT); else if(control.decision_attack()) set_new_state(State::ATTACK); else if(collision.standing_on()!=SurfaceType::GROUND && (control.decision_vertical() > 0)) set_new_state(State::JUMP); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_walk() == 0)) set_new_state(State::IDLE); else if(collision.standing_on()==SurfaceType::AIR && movement.vy() < -1) set_new_state(State::FALL); break; case State::JUMP: if(health.alive() == false) set_new_state(State::DEAD); else if(health.stunned()) set_new_state(State::HIT); else if(control.decision_attack()) set_new_state(State::ATTACK); else if(collision.standing_on()==SurfaceType::GROUND && control.decision_walk() != 0) set_new_state(State::WALK); else if(collision.standing_on()==SurfaceType::GROUND && control.decision_walk() == 0) set_new_state(State::IDLE); else if(collision.standing_on()==SurfaceType::AIR && movement.vy() < -1) set_new_state(State::FALL); break; case State::FALL: if(health.alive() == false) set_new_state(State::DEAD); else if(health.stunned()) set_new_state(State::HIT); else if(control.decision_attack()) set_new_state(State::ATTACK); else if(collision.standing_on()==SurfaceType::GROUND && control.decision_walk() != 0) set_new_state(State::WALK); else if(collision.standing_on()==SurfaceType::GROUND && control.decision_walk() == 0) set_new_state(State::IDLE); break; case State::ATTACK: if(health.alive() == false) set_new_state(State::DEAD); else if(health.stunned()) set_new_state(State::HIT); else if(collision.standing_on()==SurfaceType::AIR && movement.vy() < -1) set_new_state(State::FALL); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_vertical() > 0)) set_new_state(State::JUMP); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_walk() != 0)) set_new_state(State::WALK); else set_new_state(State::IDLE); break; case State::HIT: if(health.alive() == false) set_new_state(State::DEAD); else if(control.decision_attack()) set_new_state(State::ATTACK); else if(collision.standing_on()==SurfaceType::AIR && movement.vy() < -1) set_new_state(State::FALL); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_vertical() > 0)) set_new_state(State::JUMP); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_walk() != 0)) set_new_state(State::WALK); else if(collision.standing_on()==SurfaceType::GROUND && (control.decision_walk() == 0)) set_new_state(State::IDLE); break; case State::DEAD: //no new state break; default: break; } } SoundID id() const { return m_current_sound_id; } bool changed() const { return m_play_new_sound; } double volume() const { return m_volume; } EntityID m_self_id; private: bool m_play_new_sound; SoundID m_current_sound_id; SoundID m_idle_id, m_walk_id, m_jump_id, m_fall_id, m_land_id, m_attack_id, m_hit_id, m_dead_id; double m_volume; State m_state; ComponentAccess<const ControlT> m_control_accessor; ComponentAccess<const MovementT> m_movement_accessor; ComponentAccess<const CollisionT> m_collision_accessor; ComponentAccess<const HealthT> m_health_accessor; }; #endif /* COMPONENTS_CHARACTER_SOUNDS_H_ */
34.374449
125
0.686018
45b8b1221f0d7d006234f4d6fdf8ca50cf7a0a13
2,732
h
C
macOS/10.13/ApplePushService.framework/APSPreferences.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
30
2016-10-09T20:13:00.000Z
2022-01-24T04:14:57.000Z
macOS/10.13/ApplePushService.framework/APSPreferences.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
null
null
null
macOS/10.13/ApplePushService.framework/APSPreferences.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
7
2017-08-29T14:41:25.000Z
2022-01-19T17:14:54.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/ApplePushService.framework/Versions/A/ApplePushService */ @interface APSPreferences : NSObject @property (nonatomic, readwrite, retain) NSDictionary *acknowledgedTokenHashes; @property (nonatomic, readwrite, retain) NSArray *activationRecordListeners; @property (nonatomic, readonly) NSString *albertName; @property (nonatomic, readwrite, retain) NSDictionary *allTokenTopics; @property (nonatomic, readwrite, retain) NSDictionary *appIds; @property (nonatomic, readwrite, retain) NSString *certificateName; @property (nonatomic, readonly) BOOL detailedLogs; @property (nonatomic, readonly) BOOL disableAPSKeepAlives; @property (nonatomic, readonly) BOOL disableFrameworkLogging; @property (nonatomic, readonly) BOOL enableTCPKeepAlives; @property (nonatomic, readwrite, retain) NSDictionary *environments; @property (nonatomic, readonly) BOOL forceAnEarlyExpiration; @property (nonatomic, readonly) NSString *keepAliveEnvironment; @property (nonatomic, readonly) NSNumber *logLevel; @property (nonatomic, readwrite, retain) NSString *machineUniqueIdentifier; @property (nonatomic, readwrite, retain) NSDictionary *persistentTopics; @property (nonatomic, readwrite, retain) NSData *platformSerial; @property (nonatomic, readonly) NSNumber *statusDumpInterval; @property (nonatomic, readwrite, retain) NSData *storageId; @property (nonatomic, readwrite, retain) NSDictionary *systemUsers; @property (nonatomic, readonly) BOOL writeLogs; + (id)preferences; - (id)acknowledgedTokenHashes; - (id)activationRecordListeners; - (id)albertName; - (id)allTokenTopics; - (id)appIds; - (id)arrayForKey:(id)arg1; - (BOOL)boolForKey:(id)arg1; - (id)certificateName; - (id)dataForKey:(id)arg1; - (BOOL)detailedLogs; - (id)dictionaryForKey:(id)arg1; - (BOOL)disableAPSKeepAlives; - (BOOL)disableFrameworkLogging; - (BOOL)enableTCPKeepAlives; - (id)environments; - (BOOL)forceAnEarlyExpiration; - (id)keepAliveEnvironment; - (id)logLevel; - (id)machineUniqueIdentifier; - (id)numberForKey:(id)arg1; - (id)objectForKey:(id)arg1 havingClass:(Class)arg2; - (id)persistentTopics; - (id)platformSerial; - (void)setAcknowledgedTokenHashes:(id)arg1; - (void)setActivationRecordListeners:(id)arg1; - (void)setAllTokenTopics:(id)arg1; - (void)setAppIds:(id)arg1; - (void)setCertificateName:(id)arg1; - (void)setEnvironments:(id)arg1; - (void)setMachineUniqueIdentifier:(id)arg1; - (void)setObject:(id)arg1 forKey:(id)arg2; - (void)setPersistentTopics:(id)arg1; - (void)setPlatformSerial:(id)arg1; - (void)setStorageId:(id)arg1; - (void)setSystemUsers:(id)arg1; - (id)statusDumpInterval; - (id)storageId; - (id)stringForKey:(id)arg1; - (id)systemUsers; - (BOOL)writeLogs; @end
37.424658
98
0.782211
10725f5c1d948bb5715aa522533c41d0c1cb0641
1,258
h
C
headers/os/interface/Point.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
headers/os/interface/Point.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
headers/os/interface/Point.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2001-2009, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. */ #ifndef _POINT_H #define _POINT_H #include <SupportDefs.h> class BRect; class BPoint { public: float x; float y; BPoint(); BPoint(float x, float y); BPoint(const BPoint& p); BPoint& operator=(const BPoint& other); void Set(float x, float y); void ConstrainTo(BRect rect); void PrintToStream() const; BPoint operator-() const; BPoint operator+(const BPoint& other) const; BPoint operator-(const BPoint& other) const; BPoint& operator+=(const BPoint& other); BPoint& operator-=(const BPoint& other); bool operator!=(const BPoint& other) const; bool operator==(const BPoint& other) const; }; extern const BPoint B_ORIGIN; // returns (0, 0) inline BPoint::BPoint() : x(0.0f), y(0.0f) { } inline BPoint::BPoint(float x, float y) : x(x), y(y) { } inline BPoint::BPoint(const BPoint& other) : x(other.x), y(other.y) { } inline BPoint& BPoint::operator=(const BPoint& other) { x = other.x; y = other.y; return *this; } inline void BPoint::Set(float x, float y) { this->x = x; this->y = y; } #endif // _POINT_H
14.134831
56
0.622417
10dd2eebb00c4fbb665c06f7380bceec1022db7f
9,117
h
C
sysroot/usr/include/gtk-2.0/gtk/gtkrecentmanager.h
219-design/sysroot_qt5.15.0_binaries_armv6zk_rpizero
c3ad917b65b970c451148391ef1c2483593702ed
[ "MIT" ]
1
2022-02-11T23:14:31.000Z
2022-02-11T23:14:31.000Z
vendor/mono/osx/include/gtk-2.0/gtk/gtkrecentmanager.h
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
null
null
null
vendor/mono/osx/include/gtk-2.0/gtk/gtkrecentmanager.h
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
1
2020-02-04T15:39:06.000Z
2020-02-04T15:39:06.000Z
/* GTK - The GIMP Toolkit * gtkrecentmanager.h: a manager for the recently used resources * * Copyright (C) 2006 Emmanuele Bassi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, */ #ifndef __GTK_RECENT_MANAGER_H__ #define __GTK_RECENT_MANAGER_H__ #if defined(GTK_DISABLE_SINGLE_INCLUDES) && !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION) #error "Only <gtk/gtk.h> can be included directly." #endif #include <gdk-pixbuf/gdk-pixbuf.h> #include <gdk/gdk.h> #include <time.h> G_BEGIN_DECLS #define GTK_TYPE_RECENT_INFO (gtk_recent_info_get_type ()) #define GTK_TYPE_RECENT_MANAGER (gtk_recent_manager_get_type ()) #define GTK_RECENT_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_RECENT_MANAGER, GtkRecentManager)) #define GTK_IS_RECENT_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_RECENT_MANAGER)) #define GTK_RECENT_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_RECENT_MANAGER, GtkRecentManagerClass)) #define GTK_IS_RECENT_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_RECENT_MANAGER)) #define GTK_RECENT_MANAGER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_RECENT_MANAGER, GtkRecentManagerClass)) typedef struct _GtkRecentInfo GtkRecentInfo; typedef struct _GtkRecentData GtkRecentData; typedef struct _GtkRecentManager GtkRecentManager; typedef struct _GtkRecentManagerClass GtkRecentManagerClass; typedef struct _GtkRecentManagerPrivate GtkRecentManagerPrivate; /** * GtkRecentData: * @display_name: a UTF-8 encoded string, containing the name of the recently * used resource to be displayed, or %NULL; * @description: a UTF-8 encoded string, containing a short description of * the resource, or %NULL; * @mime_type: the MIME type of the resource; * @app_name: the name of the application that is registering this recently * used resource; * @app_exec: command line used to launch this resource; may contain the * "&percnt;f" and "&percnt;u" escape characters which will be expanded * to the resource file path and URI respectively when the command line * is retrieved; * @groups: a vector of strings containing groups names; * @is_private: whether this resource should be displayed only by the * applications that have registered it or not. * * Meta-data to be passed to gtk_recent_manager_add_full() when * registering a recently used resource. **/ struct _GtkRecentData { gchar *display_name; gchar *description; gchar *mime_type; gchar *app_name; gchar *app_exec; gchar **groups; gboolean is_private; }; struct _GtkRecentManager { /*< private >*/ GObject parent_instance; GtkRecentManagerPrivate *GSEAL (priv); }; struct _GtkRecentManagerClass { /*< private >*/ GObjectClass parent_class; void (*changed) (GtkRecentManager *manager); /* padding for future expansion */ void (*_gtk_recent1) (void); void (*_gtk_recent2) (void); void (*_gtk_recent3) (void); void (*_gtk_recent4) (void); }; /** * GtkRecentManagerError: * @GTK_RECENT_MANAGER_ERROR_NOT_FOUND: the URI specified does not exists in * the recently used resources list. * @GTK_RECENT_MANAGER_ERROR_INVALID_URI: the URI specified is not valid. * @GTK_RECENT_MANAGER_ERROR_INVALID_ENCODING: the supplied string is not * UTF-8 encoded. * @GTK_RECENT_MANAGER_ERROR_NOT_REGISTERED: no application has registered * the specified item. * @GTK_RECENT_MANAGER_ERROR_READ: failure while reading the recently used * resources file. * @GTK_RECENT_MANAGER_ERROR_WRITE: failure while writing the recently used * resources file. * @GTK_RECENT_MANAGER_ERROR_UNKNOWN: unspecified error. * * Error codes for GtkRecentManager operations **/ typedef enum { GTK_RECENT_MANAGER_ERROR_NOT_FOUND, GTK_RECENT_MANAGER_ERROR_INVALID_URI, GTK_RECENT_MANAGER_ERROR_INVALID_ENCODING, GTK_RECENT_MANAGER_ERROR_NOT_REGISTERED, GTK_RECENT_MANAGER_ERROR_READ, GTK_RECENT_MANAGER_ERROR_WRITE, GTK_RECENT_MANAGER_ERROR_UNKNOWN } GtkRecentManagerError; #define GTK_RECENT_MANAGER_ERROR (gtk_recent_manager_error_quark ()) GQuark gtk_recent_manager_error_quark (void); GType gtk_recent_manager_get_type (void) G_GNUC_CONST; GtkRecentManager *gtk_recent_manager_new (void); GtkRecentManager *gtk_recent_manager_get_default (void); #ifndef GTK_DISABLE_DEPRECATED GtkRecentManager *gtk_recent_manager_get_for_screen (GdkScreen *screen); void gtk_recent_manager_set_screen (GtkRecentManager *manager, GdkScreen *screen); #endif gboolean gtk_recent_manager_add_item (GtkRecentManager *manager, const gchar *uri); gboolean gtk_recent_manager_add_full (GtkRecentManager *manager, const gchar *uri, const GtkRecentData *recent_data); gboolean gtk_recent_manager_remove_item (GtkRecentManager *manager, const gchar *uri, GError **error); GtkRecentInfo * gtk_recent_manager_lookup_item (GtkRecentManager *manager, const gchar *uri, GError **error); gboolean gtk_recent_manager_has_item (GtkRecentManager *manager, const gchar *uri); gboolean gtk_recent_manager_move_item (GtkRecentManager *manager, const gchar *uri, const gchar *new_uri, GError **error); void gtk_recent_manager_set_limit (GtkRecentManager *manager, gint limit); gint gtk_recent_manager_get_limit (GtkRecentManager *manager); GList * gtk_recent_manager_get_items (GtkRecentManager *manager); gint gtk_recent_manager_purge_items (GtkRecentManager *manager, GError **error); GType gtk_recent_info_get_type (void) G_GNUC_CONST; GtkRecentInfo * gtk_recent_info_ref (GtkRecentInfo *info); void gtk_recent_info_unref (GtkRecentInfo *info); const gchar * gtk_recent_info_get_uri (GtkRecentInfo *info); const gchar * gtk_recent_info_get_display_name (GtkRecentInfo *info); const gchar * gtk_recent_info_get_description (GtkRecentInfo *info); const gchar * gtk_recent_info_get_mime_type (GtkRecentInfo *info); time_t gtk_recent_info_get_added (GtkRecentInfo *info); time_t gtk_recent_info_get_modified (GtkRecentInfo *info); time_t gtk_recent_info_get_visited (GtkRecentInfo *info); gboolean gtk_recent_info_get_private_hint (GtkRecentInfo *info); gboolean gtk_recent_info_get_application_info (GtkRecentInfo *info, const gchar *app_name, const gchar **app_exec, guint *count, time_t *time_); gchar ** gtk_recent_info_get_applications (GtkRecentInfo *info, gsize *length) G_GNUC_MALLOC; gchar * gtk_recent_info_last_application (GtkRecentInfo *info) G_GNUC_MALLOC; gboolean gtk_recent_info_has_application (GtkRecentInfo *info, const gchar *app_name); gchar ** gtk_recent_info_get_groups (GtkRecentInfo *info, gsize *length) G_GNUC_MALLOC; gboolean gtk_recent_info_has_group (GtkRecentInfo *info, const gchar *group_name); GdkPixbuf * gtk_recent_info_get_icon (GtkRecentInfo *info, gint size); gchar * gtk_recent_info_get_short_name (GtkRecentInfo *info) G_GNUC_MALLOC; gchar * gtk_recent_info_get_uri_display (GtkRecentInfo *info) G_GNUC_MALLOC; gint gtk_recent_info_get_age (GtkRecentInfo *info); gboolean gtk_recent_info_is_local (GtkRecentInfo *info); gboolean gtk_recent_info_exists (GtkRecentInfo *info); gboolean gtk_recent_info_match (GtkRecentInfo *info_a, GtkRecentInfo *info_b); /* private */ void _gtk_recent_manager_sync (void); G_END_DECLS #endif /* __GTK_RECENT_MANAGER_H__ */
42.013825
125
0.693759
b7cc71af61e5c3a87bacb40e5601fa876ee40a58
827
h
C
RTEngine/Component.h
RootinTootinCoodin/RTEngine
916354d8868f6eca5675390071e3ec93df497ed3
[ "MIT" ]
null
null
null
RTEngine/Component.h
RootinTootinCoodin/RTEngine
916354d8868f6eca5675390071e3ec93df497ed3
[ "MIT" ]
null
null
null
RTEngine/Component.h
RootinTootinCoodin/RTEngine
916354d8868f6eca5675390071e3ec93df497ed3
[ "MIT" ]
null
null
null
#ifndef __COMPONENT_H__ #define __COMPONENT_H__ #include "Globals.h" class GameObject; class Component { public: Component(); Component(componentType type, GameObject* parent); Component(componentType type, GameObject* parent, uint uuid); ~Component(); virtual void ComponentStart() { }; virtual void ComponentCleanUp() {}; virtual bool UpdateComponent(float dt) { return true; }; uint GetUUID() { return uuid; }; void setUUID(uint _uuid) { uuid = _uuid; }; GameObject* getGameObject() { return gameObject; }; componentType GetComponentType() { return type; }; private: virtual bool Enable() { return true; }; virtual bool Disable() { return true; }; public: protected: bool active = true; uint uuid = 0; GameObject* gameObject = nullptr; componentType type = NO_TYPE; }; #endif // !__COMPONENT_H__
20.170732
62
0.720677
a2df352955a6f2ac7350564b4878710864e39750
25,028
c
C
src/bin/pg_autoctl/keeper_config.c
Bouke/pg_auto_failover
bd5d9f92c125561af8c0a542e79c897ce900d959
[ "PostgreSQL" ]
null
null
null
src/bin/pg_autoctl/keeper_config.c
Bouke/pg_auto_failover
bd5d9f92c125561af8c0a542e79c897ce900d959
[ "PostgreSQL" ]
null
null
null
src/bin/pg_autoctl/keeper_config.c
Bouke/pg_auto_failover
bd5d9f92c125561af8c0a542e79c897ce900d959
[ "PostgreSQL" ]
null
null
null
/* * src/bin/pg_autoctl/keeper_config.c * Keeper configuration functions * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the PostgreSQL License. * */ #include <stdbool.h> #include <unistd.h> #include "postgres_fe.h" #include "defaults.h" #include "ini_file.h" #include "keeper.h" #include "keeper_config.h" #include "log.h" #include "pgctl.h" #define OPTION_AUTOCTL_ROLE(config) \ make_strbuf_option_default("pg_autoctl", "role", NULL, true, NAMEDATALEN, \ config->role, KEEPER_ROLE) #define OPTION_AUTOCTL_MONITOR(config) \ make_strbuf_option("pg_autoctl", "monitor", "monitor", false, MAXCONNINFO, \ config->monitor_pguri) #define OPTION_AUTOCTL_FORMATION(config) \ make_strbuf_option_default("pg_autoctl", "formation", "formation", \ true, NAMEDATALEN, \ config->formation, FORMATION_DEFAULT) #define OPTION_AUTOCTL_GROUPID(config) \ make_int_option("pg_autoctl", "group", "group", false, &(config->groupId)) #define OPTION_AUTOCTL_NODENAME(config) \ make_strbuf_option("pg_autoctl", "nodename", "nodename", \ true, _POSIX_HOST_NAME_MAX, \ config->nodename) #define OPTION_AUTOCTL_NODEKIND(config) \ make_strbuf_option("pg_autoctl", "nodekind", NULL, false, NAMEDATALEN, \ config->nodeKind) #define OPTION_POSTGRESQL_PGDATA(config) \ make_strbuf_option("postgresql", "pgdata", "pgdata", true, MAXPGPATH, \ config->pgSetup.pgdata) #define OPTION_POSTGRESQL_PG_CTL(config) \ make_strbuf_option("postgresql", "pg_ctl", "pgctl", false, MAXPGPATH, \ config->pgSetup.pg_ctl) #define OPTION_POSTGRESQL_USERNAME(config) \ make_strbuf_option("postgresql", "username", "username", \ false, NAMEDATALEN, \ config->pgSetup.username) #define OPTION_POSTGRESQL_DBNAME(config) \ make_strbuf_option("postgresql", "dbname", "dbname", false, NAMEDATALEN, \ config->pgSetup.dbname) #define OPTION_POSTGRESQL_HOST(config) \ make_strbuf_option("postgresql", "host", "pghost", \ false, _POSIX_HOST_NAME_MAX, \ config->pgSetup.pghost) #define OPTION_POSTGRESQL_PORT(config) \ make_int_option("postgresql", "port", "pgport", \ true, &(config->pgSetup.pgport)) #define OPTION_POSTGRESQL_PROXY_PORT(config) \ make_int_option("postgresql", "proxyport", "proxyport", \ false, &(config->pgSetup.proxyport)) #define OPTION_POSTGRESQL_LISTEN_ADDRESSES(config) \ make_strbuf_option("postgresql", "listen_addresses", "listen", \ false, MAXPGPATH, config->pgSetup.listen_addresses) #define OPTION_REPLICATION_SLOT_NAME(config) \ make_string_option_default("replication", "slot", NULL, false, \ &config->replication_slot_name, \ REPLICATION_SLOT_NAME_DEFAULT) #define OPTION_REPLICATION_PASSWORD(config) \ make_string_option_default("replication", "password", NULL, \ false, &config->replication_password, \ REPLICATION_PASSWORD_DEFAULT) #define OPTION_REPLICATION_MAXIMUM_BACKUP_RATE(config) \ make_string_option_default("replication", "maximum_backup_rate", NULL, \ false, &config->maximum_backup_rate, \ MAXIMUM_BACKUP_RATE) #define OPTION_REPLICATION_BACKUP_DIR(config) \ make_strbuf_option("replication", "backup_directory", NULL, \ false, MAXPGPATH, config->backupDirectory) #define OPTION_TIMEOUT_NETWORK_PARTITION(config) \ make_int_option_default("timeout", "network_partition_timeout", \ NULL, false, \ &(config->network_partition_timeout), \ NETWORK_PARTITION_TIMEOUT) #define OPTION_TIMEOUT_PREPARE_PROMOTION_CATCHUP(config) \ make_int_option_default("timeout", "prepare_promotion_catchup", \ NULL, \ false, \ &(config->prepare_promotion_catchup), \ PREPARE_PROMOTION_CATCHUP_TIMEOUT) #define OPTION_TIMEOUT_PREPARE_PROMOTION_WALRECEIVER(config) \ make_int_option_default("timeout", "prepare_promotion_walreceiver", \ NULL, \ false, \ &(config->prepare_promotion_walreceiver), \ PREPARE_PROMOTION_WALRECEIVER_TIMEOUT) #define OPTION_TIMEOUT_POSTGRESQL_RESTART_FAILURE_TIMEOUT(config) \ make_int_option_default("timeout", "postgresql_restart_failure_timeout", \ NULL, \ false, \ &(config->postgresql_restart_failure_timeout), \ POSTGRESQL_FAILS_TO_START_TIMEOUT) #define OPTION_TIMEOUT_POSTGRESQL_RESTART_FAILURE_MAX_RETRIES(config) \ make_int_option_default("timeout", "postgresql_restart_failure_max_retries", \ NULL, \ false, \ &(config->postgresql_restart_failure_max_retries), \ POSTGRESQL_FAILS_TO_START_RETRIES) #define SET_INI_OPTIONS_ARRAY(config) \ { \ OPTION_AUTOCTL_ROLE(config), \ OPTION_AUTOCTL_MONITOR(config), \ OPTION_AUTOCTL_FORMATION(config), \ OPTION_AUTOCTL_GROUPID(config), \ OPTION_AUTOCTL_NODENAME(config), \ OPTION_AUTOCTL_NODEKIND(config), \ OPTION_POSTGRESQL_PGDATA(config), \ OPTION_POSTGRESQL_PG_CTL(config), \ OPTION_POSTGRESQL_USERNAME(config), \ OPTION_POSTGRESQL_DBNAME(config), \ OPTION_POSTGRESQL_HOST(config), \ OPTION_POSTGRESQL_PORT(config), \ OPTION_POSTGRESQL_PROXY_PORT(config), \ OPTION_POSTGRESQL_LISTEN_ADDRESSES(config), \ OPTION_REPLICATION_PASSWORD(config), \ OPTION_REPLICATION_SLOT_NAME(config), \ OPTION_REPLICATION_MAXIMUM_BACKUP_RATE(config), \ OPTION_REPLICATION_BACKUP_DIR(config), \ OPTION_TIMEOUT_NETWORK_PARTITION(config), \ OPTION_TIMEOUT_PREPARE_PROMOTION_CATCHUP(config), \ OPTION_TIMEOUT_PREPARE_PROMOTION_WALRECEIVER(config), \ OPTION_TIMEOUT_POSTGRESQL_RESTART_FAILURE_TIMEOUT(config), \ OPTION_TIMEOUT_POSTGRESQL_RESTART_FAILURE_MAX_RETRIES(config), \ INI_OPTION_LAST \ } static bool keeper_config_init_nodekind(KeeperConfig *config); static bool keeper_config_set_backup_directory(KeeperConfig *config); /* * keeper_config_set_pathnames_from_pgdata sets the config pathnames from its * pgSetup.pgdata field, which must have already been set when calling this * function. */ bool keeper_config_set_pathnames_from_pgdata(ConfigFilePaths *pathnames, const char *pgdata) { if (IS_EMPTY_STRING_BUFFER(pgdata)) { /* developer error */ log_error("BUG: keeper_config_set_pathnames_from_pgdata: empty pgdata"); return false; } if (!SetConfigFilePath(pathnames, pgdata)) { log_fatal("Failed to set configuration filename from PGDATA \"%s\"," " see above for details.", pgdata); return false; } if (!SetStateFilePath(pathnames, pgdata)) { log_fatal("Failed to set state filename from PGDATA \"%s\"," " see above for details.", pgdata); return false; } if (!SetPidFilePath(pathnames, pgdata)) { log_fatal("Failed to set pid filename from PGDATA \"%s\"," " see above for details.", pgdata); return false; } return true; } /* * keeper_config_init initialises a KeeperConfig with the default values. */ void keeper_config_init(KeeperConfig *config, bool missingPgdataIsOk, bool pgIsNotRunningIsOk) { PostgresSetup pgSetup = { 0 }; IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); log_trace("keeper_config_init"); if (!ini_validate_options(keeperOptions)) { log_error("Please review your setup options per above messages"); exit(EXIT_CODE_BAD_CONFIG); } if (!keeper_config_init_nodekind(config)) { /* errors have already been logged. */ log_error("Please review your setup options per above messages"); exit(EXIT_CODE_BAD_CONFIG); } if (!pg_setup_init(&pgSetup, &(config->pgSetup), missingPgdataIsOk, pgIsNotRunningIsOk)) { log_error("Please fix your PostgreSQL setup per above messages"); exit(EXIT_CODE_BAD_CONFIG); } /* * Keep the whole set of values discovered in pg_setup_init from the * configuration file */ memcpy(&(config->pgSetup), &pgSetup, sizeof(PostgresSetup)); /* * Compute the backupDirectory from pgdata, or check the one given in the * configuration file already. */ if (!keeper_config_set_backup_directory(config)) { /* errors have already been logged */ exit(EXIT_CODE_BAD_CONFIG); } /* set our configuration and state file pathnames */ if (!SetConfigFilePath(&(config->pathnames), config->pgSetup.pgdata)) { log_error("Failed to initialize Keeper's config, see above"); exit(EXIT_CODE_BAD_CONFIG); } if (!SetStateFilePath(&(config->pathnames), config->pgSetup.pgdata)) { log_error("Failed to initialize Keeper's config, see above"); exit(EXIT_CODE_BAD_CONFIG); } } /* * keeper_config_read_file overrides values in given KeeperConfig with whatever * values are read from given configuration filename. */ bool keeper_config_read_file(KeeperConfig *config, bool missingPgdataIsOk, bool pgIsNotRunningIsOk, bool monitorDisabledIsOk) { if (!keeper_config_read_file_skip_pgsetup(config, monitorDisabledIsOk)) { /* errors have already been logged. */ return false; } return keeper_config_pgsetup_init(config, missingPgdataIsOk, pgIsNotRunningIsOk); } /* * keeper_config_read_file_skip_pgsetup overrides values in given KeeperConfig * with whatever values are read from given configuration filename. */ bool keeper_config_read_file_skip_pgsetup(KeeperConfig *config, bool monitorDisabledIsOk) { const char *filename = config->pathnames.config; IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); log_debug("Reading configuration from %s", filename); if (!read_ini_file(filename, keeperOptions)) { log_error("Failed to parse configuration file \"%s\"", filename); return false; } /* take care of the special value for disabled monitor setup */ if (PG_AUTOCTL_MONITOR_IS_DISABLED(config)) { config->monitorDisabled = true; if (!monitorDisabledIsOk) { log_error("Monitor is disabled in the configuration"); return false; } } if (!keeper_config_init_nodekind(config)) { /* errors have already been logged. */ return false; } return true; } /* * keeper_config_read_file_skip_pgsetup overrides values in given KeeperConfig * with whatever values are read from given configuration filename. */ bool keeper_config_pgsetup_init(KeeperConfig *config, bool missingPgdataIsOk, bool pgIsNotRunningIsOk) { PostgresSetup pgSetup = { 0 }; log_trace("keeper_config_pgsetup_init"); if (!pg_setup_init(&pgSetup, &config->pgSetup, missingPgdataIsOk, pgIsNotRunningIsOk)) { return false; } /* * Keep the whole set of values discovered in pg_setup_init from the * configuration file */ memcpy(&(config->pgSetup), &pgSetup, sizeof(PostgresSetup)); return true; } /* * keeper_config_write_file writes the current values in given KeeperConfig to * filename. */ bool keeper_config_write_file(KeeperConfig *config) { const char *filePath = config->pathnames.config; bool success = false; FILE *fileStream = NULL; log_trace("keeper_config_write_file \"%s\"", filePath); fileStream = fopen(filePath, "w"); if (fileStream == NULL) { log_error("Failed to open file \"%s\": %s", filePath, strerror(errno)); return false; } success = keeper_config_write(fileStream, config); if (fclose(fileStream) == EOF) { log_error("Failed to write file \"%s\"", filePath); return false; } return success; } /* * keeper_config_write write the current config to given STREAM. */ bool keeper_config_write(FILE *stream, KeeperConfig *config) { IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); return write_ini_to_stream(stream, keeperOptions); } /* * keeper_config_log_settings outputs a DEBUG line per each config parameter in * the given KeeperConfig. */ void keeper_config_log_settings(KeeperConfig config) { log_debug("pg_autoctl.monitor: %s", config.monitor_pguri); log_debug("pg_autoctl.formation: %s", config.formation); log_debug("postgresql.nodename: %s", config.nodename); log_debug("postgresql.nodekind: %s", config.nodeKind); log_debug("postgresql.pgdata: %s", config.pgSetup.pgdata); log_debug("postgresql.pg_ctl: %s", config.pgSetup.pg_ctl); log_debug("postgresql.version: %s", config.pgSetup.pg_version); log_debug("postgresql.username: %s", config.pgSetup.username); log_debug("postgresql.dbname: %s", config.pgSetup.dbname); log_debug("postgresql.host: %s", config.pgSetup.pghost); log_debug("postgresql.port: %d", config.pgSetup.pgport); log_debug("replication.replication_slot_name: %s", config.replication_slot_name); log_debug("replication.replication_password: %s", config.replication_password); log_debug("replication.maximum_backup_rate: %s", config.maximum_backup_rate); } /* * keeper_config_get_setting returns the current value of the given option * "path" (thats a section.option string). The value is returned in the * pre-allocated value buffer of size size. */ bool keeper_config_get_setting(KeeperConfig *config, const char *path, char *value, size_t size) { const char *filename = config->pathnames.config; IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); return ini_get_setting(filename, keeperOptions, path, value, size); } /* * keeper_config_set_setting sets the setting identified by "path" * (section.option) to the given value. The value is passed in as a string, * which is going to be parsed if necessary. */ bool keeper_config_set_setting(KeeperConfig *config, const char *path, char *value) { const char *filename = config->pathnames.config; IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); log_trace("keeper_config_set_setting"); if (ini_set_setting(filename, keeperOptions, path, value)) { PostgresSetup pgSetup = { 0 }; bool missing_pgdata_is_ok = true; bool pg_is_not_running_is_ok = true; /* * Before merging given options, validate them as much as we can. * The ini level functions validate the syntax (strings, integers, * etc), not that the values themselves then make sense. */ if (pg_setup_init(&pgSetup, &config->pgSetup, missing_pgdata_is_ok, pg_is_not_running_is_ok)) { memcpy(&(config->pgSetup), &pgSetup, sizeof(PostgresSetup)); return true; } } return false; } /* * keeper_config_merge_options merges any option setup in options into config. * Its main use is to override configuration file settings with command line * options. */ bool keeper_config_merge_options(KeeperConfig *config, KeeperConfig *options) { IniOption keeperConfigOptions[] = SET_INI_OPTIONS_ARRAY(config); IniOption keeperOptionsOptions[] = SET_INI_OPTIONS_ARRAY(options); log_trace("keeper_config_merge_options"); if (ini_merge(keeperConfigOptions, keeperOptionsOptions)) { PostgresSetup pgSetup = { 0 }; bool missing_pgdata_is_ok = true; bool pg_is_not_running_is_ok = true; /* * Before merging given options, validate them as much as we can. The * ini level functions validate the syntax (strings, integers, etc), * not that the values themselves then make sense. */ if (!pg_setup_init(&pgSetup, &config->pgSetup, missing_pgdata_is_ok, pg_is_not_running_is_ok)) { return false; } /* * Keep the whole set of values discovered in pg_setup_init from the * configuration file */ memcpy(&(config->pgSetup), &pgSetup, sizeof(PostgresSetup)); return keeper_config_write_file(config); } return false; } /* * keeper_config_set_groupId sets the groupId in the configuration file. */ bool keeper_config_set_groupId(KeeperConfig *config, int groupId) { IniOption *option; IniOption keeperOptions[] = SET_INI_OPTIONS_ARRAY(config); option = lookup_ini_option(keeperOptions, "pg_autoctl", "group"); if (option == NULL) { log_error( "BUG: keeper_config_set_groupId: lookup failed for pg_autoctl.group"); return false; } *(option->intValue) = groupId; return keeper_config_write_file(config); } /* * keeper_config_destroy frees memory that may be dynamically allocated. */ void keeper_config_destroy(KeeperConfig *config) { if (config->replication_slot_name != NULL) { free(config->replication_slot_name); } if (config->maximum_backup_rate != NULL) { free(config->maximum_backup_rate); } if (config->replication_password != NULL) { free(config->replication_password); } } /* * keeper_config_accept_new returns true when we can accept to RELOAD our * current config into the new one that's been editing. */ #define strneq(x, y) \ ((x != NULL) && (y != NULL) && ( strcmp(x, y) != 0)) bool keeper_config_accept_new(KeeperConfig *config, KeeperConfig *newConfig) { /* some elements are not supposed to change on a reload */ if (strneq(newConfig->pgSetup.pgdata, config->pgSetup.pgdata)) { log_error("Attempt to change postgresql.pgdata from \"%s\" to \"%s\"", config->pgSetup.pgdata, newConfig->pgSetup.pgdata); return false; } if (strneq(newConfig->replication_slot_name, config->replication_slot_name)) { log_error("Attempt to change replication.slot from \"%s\" to \"%s\"", config->replication_slot_name, newConfig->replication_slot_name); return false; } /* * Changing the monitor URI. Well it might just be about using a new IP * address, e.g. switching to IPv6, or maybe the monitor has moved to * another hostname. * * We don't check if we are still registered on the new monitor, only that * we can connect. The node_active calls are going to fail it we then * aren't registered anymore. */ if (strneq(newConfig->monitor_pguri, config->monitor_pguri)) { Monitor monitor = { 0 }; if (!monitor_init(&monitor, newConfig->monitor_pguri)) { log_fatal("Failed to contact the monitor because its URL is invalid, " "see above for details"); return false; } strlcpy(config->monitor_pguri, newConfig->monitor_pguri, MAXCONNINFO); } /* * We don't support changing formation, group, or nodename mid-flight: we * might have to register again to the monitor to make that work, and in * that case an admin should certainly be doing some offline steps, maybe * even having to `pg_autoctl create` all over again. */ if (strneq(newConfig->formation, config->formation)) { log_warn("pg_autoctl doesn't know how to change formation at run-time, " "continuing with formation \"%s\".", config->formation); } /* * Changing the nodename seems ok, our registration is checked against * formation/groupId/nodeId anyway. The nodename is used so that other * nodes in the network may contact us. Again, it might be a change of * public IP address, e.g. switching to IPv6. */ if (strneq(newConfig->nodename, config->nodename)) { log_info("Reloading configuration: nodename is now \"%s\"; " "used to be \"%s\"", newConfig->nodename, config->nodename); strlcpy(config->nodename, newConfig->nodename, _POSIX_HOST_NAME_MAX); } /* * Changing the replication password? Sure. */ if (strneq(newConfig->replication_password, config->replication_password)) { log_info("Reloading configuration: replication password has changed"); /* note: strneq checks args are not NULL, it's safe to proceed */ free(config->replication_password); config->replication_password = strdup(newConfig->replication_password); } /* * Changing replication.maximum_backup_rate. */ if (strneq(newConfig->maximum_backup_rate, config->maximum_backup_rate)) { log_info("Reloading configuration: " "replication.maximum_backup_rate is now \"%s\"; " "used to be \"%s\"" , newConfig->maximum_backup_rate, config->maximum_backup_rate); /* note: strneq checks args are not NULL, it's safe to proceed */ free(config->maximum_backup_rate); config->maximum_backup_rate = strdup(newConfig->maximum_backup_rate); } /* * And now the timeouts. Of course we support changing them at run-time. */ if (newConfig->network_partition_timeout != config->network_partition_timeout) { log_info("Reloading configuration: timeout.network_partition_timeout " "is now %d; used to be %d", newConfig->network_partition_timeout, config->network_partition_timeout); config->network_partition_timeout = newConfig->network_partition_timeout; } if (newConfig->prepare_promotion_catchup != config->prepare_promotion_catchup) { log_info("Reloading configuration: timeout.prepare_promotion_catchup " "is now %d; used to be %d", newConfig->prepare_promotion_catchup, config->prepare_promotion_catchup); config->prepare_promotion_catchup = newConfig->prepare_promotion_catchup; } if (newConfig->prepare_promotion_walreceiver != config->prepare_promotion_walreceiver) { log_info( "Reloading configuration: timeout.prepare_promotion_walreceiver " "is now %d; used to be %d", newConfig->prepare_promotion_walreceiver, config->prepare_promotion_walreceiver); config->prepare_promotion_walreceiver = newConfig->prepare_promotion_walreceiver; } if (newConfig->postgresql_restart_failure_timeout != config->postgresql_restart_failure_timeout) { log_info( "Reloading configuration: timeout.postgresql_restart_failure_timeout " "is now %d; used to be %d", newConfig->postgresql_restart_failure_timeout, config->postgresql_restart_failure_timeout); config->postgresql_restart_failure_timeout = newConfig->postgresql_restart_failure_timeout; } if (newConfig->postgresql_restart_failure_max_retries != config->postgresql_restart_failure_max_retries) { log_info( "Reloading configuration: retries.postgresql_restart_failure_max_retries " "is now %d; used to be %d", newConfig->postgresql_restart_failure_max_retries, config->postgresql_restart_failure_max_retries); config->postgresql_restart_failure_max_retries = newConfig->postgresql_restart_failure_max_retries; } return true; } /* * keeper_config_init_nodekind initializes the config->nodeKind and * config->pgSetup.pgKind values from the configuration file or command line * options. * * We didn't implement the PgInstanceKind datatype in our INI primitives, so we * need to now to check the configuration values and then transform * config->nodeKind into config->pgSetup.pgKind. */ static bool keeper_config_init_nodekind(KeeperConfig *config) { if (IS_EMPTY_STRING_BUFFER(config->nodeKind)) { /* * If the configuration file lacks the pg_autoctl.nodekind key, it * means we're going to use the default: "standalone". */ strlcpy(config->nodeKind, "standalone", NAMEDATALEN); config->pgSetup.pgKind = NODE_KIND_STANDALONE; } else { config->pgSetup.pgKind = nodeKindFromString(config->nodeKind); /* * Now, NODE_KIND_UNKNOWN signals we failed to recognize selected node * kind, which is an error. */ if (config->pgSetup.pgKind == NODE_KIND_UNKNOWN) { /* we already logged about it */ return false; } } return true; } /* * keeper_config_set_backup_directory sets the pg_basebackup target directory * to ${PGDATA}/../backup/${nodename} by default. Adding the local nodename * makes it possible to run several instances of Postgres and pg_autoctl on the * same host, which is nice for development and testing scenarios. */ static bool keeper_config_set_backup_directory(KeeperConfig *config) { char absoluteBackupDirectory[PATH_MAX]; /* create the temporary backup directory at $pgdata/../backup */ if (IS_EMPTY_STRING_BUFFER(config->backupDirectory)) { char *pgdata = config->pgSetup.pgdata; char subdirs[MAXPGPATH]; snprintf(subdirs, MAXPGPATH, "backup/%s", config->nodename); path_in_same_directory(pgdata, subdirs, config->backupDirectory); } /* * The best way to make sure we are allowed to create the backup directory * is to just go ahead and create it now. */ log_debug("mkdir -p \"%s\"", config->backupDirectory); if (!ensure_empty_dir(config->backupDirectory, 0700)) { log_fatal("Failed to create the backup directory \"%s\", " "see above for details", config->backupDirectory); return false; } /* Now get the realpath() of the directory we just created */ if (!realpath(config->backupDirectory, absoluteBackupDirectory)) { /* non-fatal error, just keep the computed or given directory path */ log_warn("Failed to get the realpath of backup directory \"%s\": %s", config->backupDirectory, strerror(errno)); return true; } if (strcmp(config->backupDirectory, absoluteBackupDirectory) != 0) { strlcpy(config->backupDirectory, absoluteBackupDirectory, MAXPGPATH); } return true; } /* * keeper_config_update_with_absolute_pgdata verifies that the pgdata path is * an absolute one If not, the config->pgSetup is updated and we rewrite the * config file */ bool keeper_config_update_with_absolute_pgdata(KeeperConfig *config) { PostgresSetup pgSetup = config->pgSetup; if (pg_setup_set_absolute_pgdata(&pgSetup)) { strlcpy(config->pgSetup.pgdata, pgSetup.pgdata, MAXPGPATH); if (!keeper_config_write_file(config)) { /* errors have already been logged */ return false; } } return true; }
28.734788
79
0.736495
d3ec0b3488bcb256bf59d14ffeaf37e513670ea6
3,278
c
C
ex27/logfind.5/logfind.c
tom-huntington/learn-c-the-hard-way-lectures
45703363ecabc6cdbc32143965adc32b3cae2b2f
[ "MIT" ]
1,052
2015-06-08T01:48:24.000Z
2022-03-31T16:12:22.000Z
ex27/logfind.5/logfind.c
dkorzhevin/learn-c-the-hard-way-lectures
45703363ecabc6cdbc32143965adc32b3cae2b2f
[ "MIT" ]
15
2015-11-29T16:16:37.000Z
2020-10-15T23:05:24.000Z
ex27/logfind.5/logfind.c
dkorzhevin/learn-c-the-hard-way-lectures
45703363ecabc6cdbc32143965adc32b3cae2b2f
[ "MIT" ]
532
2015-06-08T10:38:45.000Z
2022-03-24T11:48:10.000Z
#define NDEBUG #include "dbg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glob.h> #include <assert.h> const size_t MAX_LINE = 1024; int list_files(glob_t *pglob) { char *line = calloc(MAX_LINE, 1); FILE *file = fopen(".logfind", "r"); int glob_flags = GLOB_TILDE; int i = 0; int rc = -1; check(pglob != NULL, "Invalid glob_t given."); check_mem(line); check(file, "Failed to open .logfind. Make that first."); while(fgets(line, MAX_LINE-1, file) != NULL) { size_t line_length = strnlen(line, MAX_LINE - 1); assert(line_length < MAX_LINE && "Got a line length too long."); line[line_length] = '\0'; // drop the \n ending debug("Globbing %s", line); rc = glob(line, glob_flags, NULL, pglob); check(rc == 0 || rc == GLOB_NOMATCH, "Failed to glob."); // dumb work around to a stupid design in glob if(glob_flags == GLOB_TILDE) glob_flags |= GLOB_APPEND; } for(i = 0; i < pglob->gl_pathc; i++) { debug("Matched file: %s", pglob->gl_pathv[i]); } rc = 0; // all good error: // fallthrough if(line) free(line); return rc; } int found_it(int use_or, int found_count, int search_len) { debug("use_or: %d, found_count: %d, search_len: %d", use_or, found_count, search_len); if(use_or && found_count > 0) { return 1; } else if(!use_or && found_count == search_len) { return 1; } else { return 0; } } int scan_file(const char *filename, int use_or, int search_len, char *search_for[]) { char *line = calloc(MAX_LINE, 1); FILE *file = fopen(filename, "r"); int found_count = 0; int i = 0; check_mem(line); check(file, "Failed to open file: %s", filename); // read each line of the file and search that line for the contents while(fgets(line, MAX_LINE-1, file) != NULL) { for(i = 0; i < search_len; i++) { if(strcasestr(line, search_for[i]) != NULL) { debug("file: %s, line: %s, search: %s", filename, line, search_for[i]); found_count++; } } if(found_it(use_or, found_count, search_len)) { printf("%s\n", filename); break; } else { found_count = 0; } } free(line); fclose(file); return 0; error: if(line) free(line); if(file) fclose(file); return -1; } int parse_args(int *use_or, int *argc, char **argv[]) { (*argc)--; (*argv)++; if(strcmp((*argv)[0], "-o") == 0) { *use_or = 1; (*argc)--; // skip the -o (*argv)++; check(*argc > 1, "You need words after -o."); } else { *use_or = 0; } return 0; error: return -1; } int main(int argc, char *argv[]) { int i = 0; int use_or = 1; glob_t files_found; check(argc > 1, "USAGE: logfind [-o] words"); check(parse_args(&use_or, &argc, &argv) == 0, "USAGE: logfind [-o] words"); check(list_files(&files_found) == 0, "Failed to list files."); for(i = 0; i < files_found.gl_pathc; i++) { scan_file(files_found.gl_pathv[i], use_or, argc, argv); } globfree(&files_found); return 0; error: return 1; }
22.763889
90
0.554301
0398c4e8f7d4209ab529b4492fede36ac04e3f56
1,479
h
C
src/client/impl/cqtag/client_reader_init_cqtag.h
jinq0123/grpc_cb_core
f57e2886e51578f0afe1cfa6522b3899df747595
[ "Apache-2.0" ]
8
2018-06-19T09:34:59.000Z
2021-08-09T11:32:41.000Z
src/client/impl/cqtag/client_reader_init_cqtag.h
jinq0123/grpc_cb_core
f57e2886e51578f0afe1cfa6522b3899df747595
[ "Apache-2.0" ]
2
2019-02-28T10:02:16.000Z
2020-03-30T09:33:15.000Z
src/client/impl/cqtag/client_reader_init_cqtag.h
jinq0123/grpc_cb_core
f57e2886e51578f0afe1cfa6522b3899df747595
[ "Apache-2.0" ]
4
2018-06-19T09:35:00.000Z
2021-08-09T11:32:42.000Z
// Licensed under the Apache License, Version 2.0. // Author: Jin Qing (http://blog.csdn.net/jq0123) #ifndef GRPC_CB_CORE_CLIENT_CLIENT_READER_INIT_CQTAG_H #define GRPC_CB_CORE_CLIENT_CLIENT_READER_INIT_CQTAG_H #include <string> #include <grpc/support/port_platform.h> // for GRPC_MUST_USE_RESULT #include <grpc_cb_core/common/support/config.h> // for GRPC_FINAL #include "common/impl/call.h" // for StartBatch() #include "common/impl/call_op_data.h" // for CodSendInitMd #include "common/impl/call_operations.h" // for CallOperations #include "common/impl/cqtag/call_cqtag.h" // for CallCqTag namespace grpc_cb_core { class ClientReaderInitCqTag GRPC_FINAL : public CallCqTag { public: inline explicit ClientReaderInitCqTag(const CallSptr& call_sptr) : CallCqTag(call_sptr) {} inline bool Start(const std::string& request) GRPC_MUST_USE_RESULT; private: CodSendMsg cod_send_msg_; CodSendInitMd cod_send_init_md_; CodRecvInitMd cod_recv_init_md_; }; // class ClientReaderInitCqTag bool ClientReaderInitCqTag::Start(const std::string& request) { CallOperations ops; ops.SendMsg(request, cod_send_msg_); // Todo: Fill send_init_md_array_ -> FillMetadataVector() ops.SendInitMd(cod_send_init_md_); ops.RecvInitMd(cod_recv_init_md_); ops.ClientSendClose(); return GetCallSptr()->StartBatch(ops, this); } } // namespace grpc_cb_core #endif // GRPC_CB_CORE_CLIENT_CLIENT_READER_INIT_CQTAG_H
33.613636
70
0.759973
861095b58d643fc3d6ce986ccc5a35511d23e064
591
h
C
Class/DSHBarrageChannel.h
568071718/DSHBarrageView
4bf8361d80a3005e1f41a3ddb1ec98f5abd90862
[ "MIT" ]
9
2019-02-09T06:28:21.000Z
2020-09-21T11:12:23.000Z
Class/DSHBarrageChannel.h
568071718/DSHBarrageView
4bf8361d80a3005e1f41a3ddb1ec98f5abd90862
[ "MIT" ]
null
null
null
Class/DSHBarrageChannel.h
568071718/DSHBarrageView
4bf8361d80a3005e1f41a3ddb1ec98f5abd90862
[ "MIT" ]
1
2020-01-02T07:40:41.000Z
2020-01-02T07:40:41.000Z
// // DSHBarrageChannel.h // DSHBarrageView // // Created by 路 on 2019/2/28. // Copyright © 2019年 路. All rights reserved. // 弹幕通道 (private) #import <UIKit/UIKit.h> @class DSHBarrageViewCell; @interface DSHBarrageChannel : NSObject /// 通道标识 @property (assign ,nonatomic ,readonly) NSInteger channelIndex; /// 通道在 DSHBarrageView 上对应的 y 坐标 @property (assign ,nonatomic ,readonly) CGFloat y; /// 获取当前通道中所有的弹幕 cell @property (strong ,nonatomic ,readonly) NSHashTable <DSHBarrageViewCell *>*cells; /// 记录最后一个添加到该通道的弹幕 cell @property (weak ,nonatomic) DSHBarrageViewCell *lastCell; @end
22.730769
81
0.739425
eac6486b05671c34319d715dc684468686a71bb7
6,058
h
C
iPhoneOS9.3.sdk/System/Library/Frameworks/HealthKit.framework/Headers/HKDevice.h
onezens/sdks
a194d40f2ef4c4a00d8d3d1b3a2d7a9a110449b7
[ "MIT" ]
416
2016-08-20T03:40:59.000Z
2022-03-30T14:27:47.000Z
iPhoneOS9.3.sdk/System/Library/Frameworks/HealthKit.framework/Headers/HKDevice.h
tobygrand/sdks
d43e7efaa664af3f92e6a4b306ee56a8e7a3eef6
[ "MIT" ]
41
2016-08-22T14:41:42.000Z
2022-02-25T11:38:16.000Z
iPhoneOS9.3.sdk/System/Library/Frameworks/HealthKit.framework/Headers/HKDevice.h
tobygrand/sdks
d43e7efaa664af3f92e6a4b306ee56a8e7a3eef6
[ "MIT" ]
173
2016-08-28T15:09:18.000Z
2022-03-23T15:42:52.000Z
// // HKDevice.h // HealthKit // // Copyright © 2015 Apple. All rights reserved. // #import <HealthKit/HKDefines.h> NS_ASSUME_NONNULL_BEGIN /*! @constant HKDevicePropertyKeyName @abstract Used with predicateForObjectsWithDeviceProperty to specify a device name. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyName NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyManufacturer @abstract Used with predicateForObjectsWithDeviceProperty to specify a device manufacturer. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyManufacturer NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyModel @abstract Used with predicateForObjectsWithDeviceProperty to specify a device model. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyModel NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyHardwareVersion @abstract Used with predicateForObjectsWithDeviceProperty to specify a hardware version. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyHardwareVersion NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyFirmwareVersion @abstract Used with predicateForObjectsWithDeviceProperty to specify a firmware version. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyFirmwareVersion NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeySoftwareVersion @abstract Used with predicateForObjectsWithDeviceProperty to specify a software version. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeySoftwareVersion NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyLocalIdentifier @abstract Used with predicateForObjectsWithDeviceProperty to specify a local identifier. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyLocalIdentifier NS_AVAILABLE_IOS(9_0); /*! @constant HKDevicePropertyKeyUDIDeviceIdentifier @abstract Used with predicateForObjectsWithDeviceProperty to specify a UDI device identifier. @discussion The expected value type is an NSString. */ HK_EXTERN NSString * const HKDevicePropertyKeyUDIDeviceIdentifier NS_AVAILABLE_IOS(9_0); HK_CLASS_AVAILABLE_IOS(9_0) @interface HKDevice : NSObject <NSSecureCoding, NSCopying> /*! @property name @abstract The name of the receiver. @discussion The user-facing name, such as the one displayed in the Bluetooth Settings for a BLE device. */ @property (readonly) NSString *name; /*! @property manufacturer @abstract The manufacturer of the receiver. */ @property (readonly, nullable) NSString *manufacturer; /*! @property model @abstract The model of the receiver. */ @property (readonly, nullable) NSString *model; /*! @property hardwareVersion @abstract The hardware revision of the receiver. */ @property (readonly, nullable) NSString *hardwareVersion; /*! @property firmwareVersion @abstract The firmware revision of the receiver. */ @property (readonly, nullable) NSString *firmwareVersion; /*! @property softwareVersion @abstract The software revision of the receiver. */ @property (readonly, nullable) NSString *softwareVersion; /*! @property localIdentifier @abstract A unique identifier for the receiver. @discussion This property is available to clients for a local identifier. For example, Bluetooth peripherals managed by HealthKit use this for the CoreBluetooth UUID which is valid only on the local device and thus distinguish the same Bluetooth peripheral used between multiple devices. */ @property (readonly, nullable) NSString *localIdentifier; /*! @property UDIDeviceIdentifier @abstract Represents the device identifier portion of a device's FDA UDI (Unique Device Identifier). @discussion The device identifier can be used to reference the FDA's GUDID (Globally Unique Device Identifier Database). Note that for user privacy concerns this field should not be used to persist the production identifier portion of the device UDI. HealthKit clients should manage the production identifier independently, if needed. See http://www.fda.gov/MedicalDevices/DeviceRegulationandGuidance/UniqueDeviceIdentification/ for more information. */ @property (readonly, nullable) NSString *UDIDeviceIdentifier; /*! @method initWithName:manufacturer:model:hardwareVersion:firmwareVersion:softwareVersion:localIdentifier:UDIDeviceIdentifier: @abstract Initialize a new HKDevice with the specified values. @discussion This allows initialization of an HKDevice object based on the information provided. */ - (instancetype)initWithName:(NSString * __nullable)name manufacturer:(NSString * __nullable)manufacturer model:(NSString * __nullable)model hardwareVersion:(NSString * __nullable)hardwareVersion firmwareVersion:(NSString * __nullable)firmwareVersion softwareVersion:(NSString * __nullable)softwareVersion localIdentifier:(NSString * __nullable)localIdentifier UDIDeviceIdentifier:(NSString * __nullable)UDIDeviceIdentifier; - (instancetype)init NS_UNAVAILABLE; /*! @method localDevice @abstract Returns a device representing the host. @discussion If an app chooses to save samples that were retrieved from the local device, e.g. an HKWorkout with a totalDistance HKQuantity gathered from CoreLocation GPS distances, then this would be an appropriate HKDevice to use. */ + (HKDevice *)localDevice; @end NS_ASSUME_NONNULL_END
37.395062
132
0.744305
caa9168c17adf7c6d7a85a52d703b9abf889530f
3,523
h
C
src/xapian/matcher/matchtimeout.h
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
370
2016-03-14T12:19:08.000Z
2022-03-25T02:07:29.000Z
src/xapian/matcher/matchtimeout.h
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
34
2015-11-30T19:06:40.000Z
2022-02-26T03:46:58.000Z
src/xapian/matcher/matchtimeout.h
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
31
2015-02-13T22:27:34.000Z
2022-03-25T02:07:34.000Z
/** @file matchtimeout.h * @brief Time limits for the matcher */ /* Copyright (C) 2013,2014,2015,2016,2017 Olly Betts * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ #ifndef XAPIAN_INCLUDED_MATCHTIMEOUT_H #define XAPIAN_INCLUDED_MATCHTIMEOUT_H #ifndef PACKAGE # error config.h must be included first in each C++ source file #endif #ifdef HAVE_TIMER_CREATE #include "xapian/common/realtime.h" #include <signal.h> #include <time.h> #include "xapian/common/safeunistd.h" // For _POSIX_* feature test macros. extern "C" { static void set_timeout_flag(union sigval sv) { *(reinterpret_cast<volatile bool*>(sv.sival_ptr)) = true; } } // The monotonic clock is the better basis for timeouts, but not always // available. #ifndef _POSIX_MONOTONIC_CLOCK const clockid_t TIMEOUT_CLOCK = CLOCK_REALTIME; #elif defined __sun // Solaris defines CLOCK_MONOTONIC, but "man timer_create" doesn't mention it // and when using it timer_create() fails with "EPERM" (perhaps you need to be // root to use it? I can't test that). // // Solaris defines _POSIX_MONOTONIC_CLOCK so we need to special case. const clockid_t TIMEOUT_CLOCK = CLOCK_REALTIME; #elif defined __CYGWIN__ // https://cygwin.com/cygwin-api/std-notes.html currently (2016-05-13) says: // // clock_nanosleep currently supports only CLOCK_REALTIME and // CLOCK_MONOTONIC. clock_setres, clock_settime, and timer_create // currently support only CLOCK_REALTIME. // // So CLOCK_MONOTONIC is defined, but not supported by timer_create(). const clockid_t TIMEOUT_CLOCK = CLOCK_REALTIME; #else const clockid_t TIMEOUT_CLOCK = CLOCK_MONOTONIC; #endif class TimeOut { struct sigevent sev; timer_t timerid; volatile bool expired; TimeOut(const TimeOut&) = delete; TimeOut& operator=(const TimeOut&) = delete; public: explicit TimeOut(double limit) : expired(false) { if (limit > 0) { sev.sigev_notify = SIGEV_THREAD; sev.sigev_notify_function = set_timeout_flag; sev.sigev_notify_attributes = NULL; sev.sigev_value.sival_ptr = static_cast<void*>(const_cast<bool*>(&expired)); if (usual(timer_create(TIMEOUT_CLOCK, &sev, &timerid) == 0)) { struct itimerspec interval; interval.it_interval.tv_sec = 0; interval.it_interval.tv_nsec = 0; RealTime::to_timespec(limit, &interval.it_value); if (usual(timer_settime(timerid, 0, &interval, NULL) == 0)) { // Timeout successfully set. return; } timer_delete(timerid); } } sev.sigev_notify = SIGEV_NONE; } ~TimeOut() { if (sev.sigev_notify != SIGEV_NONE) { timer_delete(timerid); sev.sigev_notify = SIGEV_NONE; } } bool timed_out() const { return expired; } }; #else class TimeOut { public: explicit TimeOut(double) { } bool timed_out() const { return false; } }; #endif #endif // XAPIAN_INCLUDED_MATCHTIMEOUT_H
29.115702
78
0.727505
1b658b387b573ac6d11e7b752c3e33ccf11bfe85
5,156
h
C
cores/nRF5/SDK/components/device/nrf5340_network_peripherals.h
honnet/arduino-nRF5-with-nRF24-radio
65e7703681ea8fbca3b3e7cf2527aceb191f872e
[ "Linux-OpenIB" ]
669
2016-03-28T16:04:39.000Z
2022-03-30T09:57:42.000Z
cores/nRF5/SDK/components/device/nrf5340_network_peripherals.h
honnet/arduino-nRF5-with-nRF24-radio
65e7703681ea8fbca3b3e7cf2527aceb191f872e
[ "Linux-OpenIB" ]
448
2016-03-29T02:31:15.000Z
2022-03-26T10:26:12.000Z
cores/nRF5/SDK/components/device/nrf5340_network_peripherals.h
honnet/arduino-nRF5-with-nRF24-radio
65e7703681ea8fbca3b3e7cf2527aceb191f872e
[ "Linux-OpenIB" ]
290
2016-04-10T23:03:33.000Z
2022-02-22T17:39:16.000Z
/* Copyright (c) 2010 - 2020, Nordic Semiconductor ASA 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 Nordic Semiconductor ASA 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 NORDIC SEMICONDUCTOR ASA 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 _NRF5340_NETWORK_PERIPHERALS_H #define _NRF5340_NETWORK_PERIPHERALS_H /* Clock Peripheral */ #define CLOCK_PRESENT #define CLOCK_COUNT 1 /* Power Peripheral */ #define POWER_PRESENT #define POWER_COUNT 1 /* Non-Volatile Memory Controller */ #define NVMC_PRESENT #define NVMC_COUNT 1 #define NVMC_FEATURE_CACHE_PRESENT /* Voltage request peripheral */ #define VREQCTRL_PRESENT #define VREQCTRL_COUNT 1 /* Volatile Memory Controller Peripheral */ #define VMC_PRESENT #define VMC_COUNT 1 #define VMC_FEATURE_RAM_REGISTERS_PRESENT #define VMC_FEATURE_RAM_REGISTERS_COUNT 4 /* Systick timer */ #define SYSTICK_PRESENT #define SYSTICK_COUNT 1 /* Inter-Processor Communication */ #define IPC_PRESENT #define IPC_COUNT 1 #define IPC_CH_NUM 16 #define IPC_CONF_NUM 16 #define IPC_GPMEM_NUM 2 /* GPIO */ #define GPIO_PRESENT #define GPIO_COUNT 2 #define P0_PIN_NUM 32 #define P1_PIN_NUM 16 #define P0_FEATURE_PINS_PRESENT 0xFFFFFFFFUL #define P1_FEATURE_PINS_PRESENT 0x0000FFFFUL /* ACL */ #define ACL_PRESENT #define ACL_REGIONS_COUNT 8 /* Radio */ #define RADIO_PRESENT #define RADIO_COUNT 1 #define RADIO_EASYDMA_MAXCNT_SIZE 9 #define RADIO_FEATURE_IEEE_802_15_4_PRESENT #define RADIO_TXPOWER_TXPOWER_Max RADIO_TXPOWER_TXPOWER_0dBm /* Accelerated Address Resolver */ #define AAR_PRESENT #define AAR_COUNT 1 #define AAR_MAX_IRK_NUM 16 /* AES Electronic CodeBook mode encryption */ #define ECB_PRESENT #define ECB_COUNT 1 /* AES CCM mode encryption */ #define CCM_PRESENT #define CCM_COUNT 1 /* Distributed Peripheral to Peripheral Interconnect */ #define DPPI_PRESENT #define DPPI_COUNT 1 #define DPPI_CH_NUM 16 #define DPPI_GROUP_NUM 6 /* Event Generator Unit */ #define EGU_PRESENT #define EGU_COUNT 1 #define EGU0_CH_NUM 16 /* Timer/Counter */ #define TIMER_PRESENT #define TIMER_COUNT 3 #define TIMER0_MAX_SIZE 32 #define TIMER1_MAX_SIZE 32 #define TIMER2_MAX_SIZE 32 #define TIMER0_CC_NUM 8 #define TIMER1_CC_NUM 8 #define TIMER2_CC_NUM 8 /* Real Time Counter */ #define RTC_PRESENT #define RTC_COUNT 2 #define RTC0_CC_NUM 4 #define RTC1_CC_NUM 4 /* RNG */ #define RNG_PRESENT #define RNG_COUNT 1 /* Watchdog Timer */ #define WDT_PRESENT #define WDT_COUNT 1 /* Temperature Sensor */ #define TEMP_PRESENT #define TEMP_COUNT 1 /* Universal Asynchronous Receiver-Transmitter with DMA */ #define UARTE_PRESENT #define UARTE_COUNT 1 #define UARTE0_EASYDMA_MAXCNT_SIZE 16 /* Serial Peripheral Interface Master with DMA */ #define SPIM_PRESENT #define SPIM_COUNT 1 #define SPIM0_MAX_DATARATE 8 #define SPIM0_FEATURE_HARDWARE_CSN_PRESENT 0 #define SPIM0_FEATURE_DCX_PRESENT 0 #define SPIM0_FEATURE_RXDELAY_PRESENT 0 #define SPIM0_EASYDMA_MAXCNT_SIZE 16 /* Serial Peripheral Interface Slave with DMA*/ #define SPIS_PRESENT #define SPIS_COUNT 1 #define SPIS0_EASYDMA_MAXCNT_SIZE 16 /* Two Wire Interface Master with DMA */ #define TWIM_PRESENT #define TWIM_COUNT 1 #define TWIM0_EASYDMA_MAXCNT_SIZE 16 /* Two Wire Interface Slave with DMA */ #define TWIS_PRESENT #define TWIS_COUNT 1 #define TWIS0_EASYDMA_MAXCNT_SIZE 16 /* GPIO Tasks and Events */ #define GPIOTE_PRESENT #define GPIOTE_COUNT 1 #define GPIOTE_CH_NUM 8 #define GPIOTE_FEATURE_SET_PRESENT #define GPIOTE_FEATURE_CLR_PRESENT /* Software Interrupts */ #define SWI_PRESENT #define SWI_COUNT 4 /* Mutex*/ #define MUTEX_PRESENT #define MUTEX_COUNT 1 #endif // _NRF5340_NETWORK_PERIPHERALS_H
24.320755
79
0.770753
9b3140bbb1b3ebfe1714492790f9ed66046a9cb8
4,827
h
C
exp1/include/convex_hull.h
bhshp/advanced-algorithm
20b6109f0843b024be4698fb12f0616fa4266ae1
[ "MIT" ]
null
null
null
exp1/include/convex_hull.h
bhshp/advanced-algorithm
20b6109f0843b024be4698fb12f0616fa4266ae1
[ "MIT" ]
null
null
null
exp1/include/convex_hull.h
bhshp/advanced-algorithm
20b6109f0843b024be4698fb12f0616fa4266ae1
[ "MIT" ]
null
null
null
#pragma once #ifndef CONVEX_HULL_H_ #define CONVEX_HULL_H_ #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <iterator> #include <vector> #include "point2d.h" #include "triangle.h" using set_type = std::vector<point2d>; using function_type = std::function<set_type(set_type)>; set_type enumerate_convex_hull(set_type v); set_type graham_scan(set_type v); set_type divide_and_conquer(set_type v); // Implementation inline set_type enumerate_convex_hull(set_type v) { int n = v.size(); std::vector<bool> vis(n, true); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { for (int l = k + 1; l < n; l++) { if (triangle{v[j], v[k], v[l]}.in(v[i])) { vis[i] = false; } if (triangle{v[i], v[k], v[l]}.in(v[j])) { vis[j] = false; } if (triangle{v[i], v[j], v[l]}.in(v[k])) { vis[k] = false; } if (triangle{v[i], v[j], v[k]}.in(v[l])) { vis[l] = false; } } } } } set_type result; for (int i = 0; i < n; i++) { if (vis[i]) { result.push_back(v[i]); } } set_type::iterator minimum_pos = std::min_element(result.begin(), result.end()); point2d minimum = *minimum_pos; if (minimum_pos != result.begin() && minimum_pos != result.end()) { std::swap(*minimum_pos, *result.begin()); } std::sort(result.begin() + 1, result.end(), [&minimum](const point2d &a, const point2d &b) -> bool { return ((a - minimum) ^ (b - minimum)) >= 0; }); return result; } inline set_type graham_scan(set_type v) { if (v.size() < 3) { return v; } set_type::iterator minimum_pos = std::min_element(v.begin(), v.end()); point2d minimum = *minimum_pos; if (minimum_pos != v.begin() && minimum_pos != v.end()) { std::swap(*minimum_pos, *v.begin()); } std::sort(v.begin() + 1, v.end(), [&minimum](const point2d &a, const point2d &b) -> bool { return ((a - minimum) ^ (b - minimum)) >= 0; }); set_type res; for (size_t i = 0; i < v.size(); i++) { if (i >= 3) { while (!res.empty() && ((v[i] - *(res.rbegin() + 1)) ^ (res.back() - *(res.rbegin() + 1))) > 0) { res.pop_back(); } } res.push_back(v[i]); } return res; } inline set_type divide_and_conquer(set_type v) { std::sort(v.begin(), v.end()); function_type impl = [&impl](set_type v) -> set_type { if (v.size() < 3) { return v; } else if (v.size() == 3) { if (((v[1] - v[0]) ^ (v[2] - v[0])) < 0) { std::swap(v[1], v[2]); } return v; } int mid = v.size() / 2; set_type left = impl(set_type(v.begin(), v.begin() + mid)), right = impl(set_type(v.begin() + mid, v.end())); point2d left_most = left[0]; auto cmp = [&left_most](const point2d &a, const point2d &b) -> bool { return ((a - left_most) ^ (b - left_most)) >= 0; }; auto [min_iterator, max_iterator] = std::minmax_element(right.begin(), right.end(), cmp); set_type counter_clockwise, clockwise; auto it = min_iterator; while (it != max_iterator) { counter_clockwise.push_back(*it); if (++it == right.end()) { it = right.begin(); } } while (it != min_iterator) { clockwise.push_back(*it); if (++it == right.end()) { it = right.begin(); } } std::reverse(clockwise.begin(), clockwise.end()); set_type s{left[0]}, temp; std::merge(left.begin() + 1, left.end(), counter_clockwise.begin(), counter_clockwise.end(), std::back_inserter(temp), cmp); std::merge(temp.begin(), temp.end(), clockwise.begin(), clockwise.end(), std::back_inserter(s), cmp); set_type res; for (size_t i = 0; i < s.size(); i++) { if (i >= 3) { while (s.size() >= 2 && ((s[i] - *(res.rbegin() + 1)) ^ (res.back() - *(res.rbegin() + 1))) > 0) { res.pop_back(); } } res.push_back(s[i]); } return res; }; return impl(v); } #endif // CONVEX_HULL_H_
31.756579
80
0.45577
af95d48bf0082c17ee8687db405503f2ca37a311
277
h
C
Arkanoid/src/game.h
5Daydreams/CppAssignement
2b3662c81f6ecafb05d9a909bf2a869f256e5d9d
[ "Apache-2.0" ]
null
null
null
Arkanoid/src/game.h
5Daydreams/CppAssignement
2b3662c81f6ecafb05d9a909bf2a869f256e5d9d
[ "Apache-2.0" ]
null
null
null
Arkanoid/src/game.h
5Daydreams/CppAssignement
2b3662c81f6ecafb05d9a909bf2a869f256e5d9d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include "player.h" #include "Library/Ball.h" #include "Library/Block.h" extern const int BLOCK_ROW_SIZE; extern const int BLOCK_COL_SIZE; extern bool resetAvailable; extern Player player; extern std::vector<Ball> balls; extern Block blocks[];
19.785714
32
0.776173
bbbab1ec0d035fa59d68d0df7663c1ced421e98b
8,052
h
C
Chapter3/SmallWindows/Window.h
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
34
2016-10-03T01:39:25.000Z
2022-03-01T03:21:41.000Z
Empty Project/SmallWindows/Window.h
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
null
null
null
Empty Project/SmallWindows/Window.h
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
31
2016-09-02T08:56:01.000Z
2022-03-12T20:15:21.000Z
namespace SmallWindows { extern map<HWND,Window*> WindowMap; enum WindowStyle {NoStyle = 0, Border = WS_BORDER, ThickFrame = WS_THICKFRAME, Caption = WS_CAPTION, Child = WS_CHILD, ClipChildren = WS_CLIPCHILDREN, ClipSibling = WS_CLIPSIBLINGS, Disabled = WS_DISABLED, DialogFrame = WS_DLGFRAME, Group = WS_GROUP, HScroll = WS_HSCROLL, Minimize = WS_MINIMIZE, Maximize = WS_MAXIMIZE, MaximizeBox = WS_MAXIMIZEBOX, MinimizeBox = WS_MINIMIZEBOX, Overlapped = WS_OVERLAPPED, OverlappedWindow = WS_OVERLAPPEDWINDOW, Popup = WS_POPUP,PopupWindow = WS_POPUPWINDOW, SystemMenu = WS_SYSMENU, Tabulatorstop = WS_TABSTOP, Thickframe = WS_THICKFRAME, Tiled = WS_TILED, Visible = WS_VISIBLE, VScroll = WS_VSCROLL}; enum WindowShow {Restore = SW_RESTORE, Default = SW_SHOWDEFAULT, Maximized = SW_SHOWMAXIMIZED, Minimized = SW_SHOWMINIMIZED, MinNoActive = SW_SHOWMINNOACTIVE, NoActive = SW_SHOWNA, NoActivate = SW_SHOWNOACTIVATE, Normal = SW_SHOWNORMAL, Show = SW_SHOW, Hide = SW_HIDE}; enum MouseButton {NoButton = 0x00, LeftButton = 0x01, MiddleButton = 0x02, RightButton = 0x04}; enum WheelDirection {WheelUp, WheelDown}; enum CoordinateSystem {LogicalWithScroll, LogicalWithoutScroll, PreviewCoordinate}; enum ButtonGroup {Ok = MB_OK, OkCancel = MB_OKCANCEL, YesNo = MB_YESNO, YesNoCancel = MB_YESNOCANCEL, RetryCancel = MB_RETRYCANCEL, CancelTryContinue = MB_CANCELTRYCONTINUE, AbortRetryIgnore = MB_ABORTRETRYIGNORE}; enum Icon {NoIcon = 0, Information = MB_ICONINFORMATION, Stop = MB_ICONSTOP, Warning = MB_ICONWARNING, Question = MB_ICONQUESTION}; enum Answer {OkAnswer = IDOK, Cancel = IDCANCEL, Yes = IDYES, No = IDNO, Retry = IDRETRY, Continue = IDCONTINUE, Abort = IDABORT, Ignore = IDIGNORE} const; enum DrawMode {Paint, Print}; class Application; class Window { public: Window(CoordinateSystem system, Size pageSize = ZeroSize, Window* parentPtr = nullptr, WindowStyle style = OverlappedWindow, WindowStyle extendedStyle = NoStyle, WindowShow windowShow = Normal, Point topLeft = ZeroPoint, Size windowSize=ZeroSize); protected: Window(Window* parentPtr = nullptr); Window(String className, CoordinateSystem system, Size pageSize = ZeroSize, Window* parentPtr = nullptr, WindowStyle style = OverlappedWindow, WindowStyle extendedStyle = NoStyle, WindowShow windowShow = Normal, Point windowTopLeft = ZeroPoint, Size windowSize = ZeroSize); void PrepareDeviceContext(HDC deviceContextHandle) const; public: virtual ~Window(); void ShowWindow(bool visible); void EnableWindow(bool enable); virtual void OnSize(Size windowSize) {/* Empty. */} virtual void OnMove(Point topLeft) {/* Empty. */ } virtual void OnHelp() {/* Empty. */} HWND WindowHandle() const {return windowHandle;} HWND& WindowHandle() {return windowHandle;} Window* ParentWindowPtr() const {return parentPtr;} Window*& ParentWindowPtr() {return parentPtr;} void SetHeader(String headerText); double GetZoom() const {return zoom;} void SetZoom(double z) {zoom = z;} void SetTimer(int timerId, unsigned int interval); void DropTimer(int timerId); virtual void OnTimer(int timerId) {/* Empty. */} void SetFocus() const; bool HasFocus() const; virtual void OnGainFocus() {/* Empty. */} virtual void OnLoseFocus() {/* Empty. */} virtual void OnMouseDown(MouseButton mouseButtons, Point mousePoint, bool shiftPressed, bool controlPressed) {/* Empty. */} virtual void OnMouseUp(MouseButton mouseButtons, Point mousePoint, bool shiftPressed, bool controlPressed) {/* Empty. */} virtual void OnMouseMove(MouseButton mouseButtons, Point mousePoint, bool shiftPressed, bool controlPressed) {/* Empty. */} virtual void OnDoubleClick(MouseButton mouseButtons, Point mousePoint, bool shiftPressed, bool controlPressed) {/* Empty. */} virtual void OnMouseWheel(WheelDirection direction, bool shiftPressed, bool controlPressed) {/* Empty. */} virtual void OnTouchDown(vector<Point> pointList); virtual void OnTouchMove(vector<Point> pointList); virtual void OnTouchUp(vector<Point> pointList); virtual bool OnKeyDown(WORD key, bool shiftPressed, bool controlPressed) {return false;} virtual void OnChar(TCHAR tChar) {/* Empty. */} virtual bool OnKeyUp(WORD key, bool shiftPressed, bool controlPressed) {return false;} void Invalidate(bool clear = true) const; void Invalidate(Rect areaRect, bool clear = true) const; void UpdateWindow(); virtual void OnPaint(Graphics& graphics) const {OnDraw(graphics, Paint);} virtual void OnPrint(Graphics& graphics, int page, int copy, int totalPages) const {OnDraw(graphics, Print);} virtual void OnDraw(Graphics& graphics, DrawMode drawMode) const {/* Empty. */} virtual bool TryClose() {return true;} virtual void OnClose(); virtual void OnDestroy() {/* Empty. */} protected: Point DeviceToLogical(Point point) const; Rect DeviceToLogical(Rect rect) const; Size DeviceToLogical(Size size) const; Point LogicalToDevice(Point point) const; Rect LogicalToDevice(Rect rect) const; Size LogicalToDevice(Size size) const; public: Point GetWindowDevicePosition() const; void SetWindowDevicePosition(Point topLeft); Size GetWindowDeviceSize() const; void SetWindowDeviceSize(Size windowSize); Size GetClientDeviceSize() const; Rect GetWindowDeviceRect() const; void SetWindowDeviceRect(Rect windowRect); Size GetWindowSize() const; void SetWindowSize(Size windowSize); Point GetWindowPosition() const; void SetWindowPosition(Point topLeft); Size GetClientSize() const; Rect GetWindowRect() const; void SetWindowRect(Rect windowRect) ; private: TEXTMETRIC CreateTextMetric(Font font) const; public: int GetCharacterAverageWidth(Font font) const; int GetCharacterHeight(Font font) const; int GetCharacterAscent(Font font) const; int GetCharacterWidth(Font font, TCHAR tChar) const; Answer MessageBox(String message, String caption = TEXT("Error"), ButtonGroup buttonGroup = Ok, Icon icon = NoIcon, bool help = false) const; protected: const Size pageSize; HWND windowHandle; Window* parentPtr; private: CoordinateSystem system; double zoom = 1.0; friend LRESULT CALLBACK WindowProc(HWND windowHandle, UINT message, WPARAM wordParam, LPARAM longParam); }; extern map<HWND,Window*> WindowMap; };
37.981132
66
0.595132
6f299bd650f917b16c2944977d0db814ec3343da
3,498
h
C
Engine/Core/ScriptCompiler.h
resul4e/Runtime-Recompiled-CPP
ef0c8918782b67a431cf7dc0e9a2f2770f8bed67
[ "Apache-2.0" ]
1
2020-05-28T07:56:58.000Z
2020-05-28T07:56:58.000Z
Engine/Core/ScriptCompiler.h
resul4e/Runtime-Recompiled-CPP
ef0c8918782b67a431cf7dc0e9a2f2770f8bed67
[ "Apache-2.0" ]
null
null
null
Engine/Core/ScriptCompiler.h
resul4e/Runtime-Recompiled-CPP
ef0c8918782b67a431cf7dc0e9a2f2770f8bed67
[ "Apache-2.0" ]
null
null
null
#pragma once #if defined(WIN32) || defined(_WIN32) #include <Windows.h> #endif #include <memory> #include <unordered_map> #include "FileSystem.h" #include "Handle.h" #include "ForwardDecl.h" #include "ConfigDirectories.h" class Script; class Storage; class SharedLibrary; /** * \brief Used to compile, link and load the DLLs for a particular Script */ class ScriptCompiler { public: ScriptCompiler(std::shared_ptr<Script> aScript, std::shared_ptr<ConfigDirectories> aDirectories); ~ScriptCompiler(); /** * \brief Compiles all of the scripts. * * First checks if the file is out of date to speed up compilation time * after the first compile. * If the file is out of date calls CompileInternal() * * Internally calls CompileInternal(); * \see GetInclude() * \see CompileInternal(); * \see Unload(); */ void Compile(); /** * \brief loads the DLL and all of the functions we need to be able to use the script * * Internally calls LoadSharedObjectInternal(). * \see LoadSharedObjectInternal() */ void LoadSharedObject(); /** * \brief Checks if the DLL is older than the cpp file. If it is older the Script needs a recompile. * \return True if the DLL is younger than the saved cpp file. False if the DLL is older than the saved cpp file. */ bool CheckIfSharedObjectIsUpToDate(); /** * \brief recompiles and relinks the script * \see Recompile() * \see Relink(); */ void ReloadScript(); /** * \brief Gets the last exception thrown in Compile() and resets it. * \return The last error or nullptr */ static std::exception_ptr PopCompilerError(); private: ///\brief Unloads all of the data of the old Script void Unload(); ///\brief Calls the batch file to compile all of the scripts and sets the dependencies of each script void CompileInternal(); ///\brief loads the dll and the functions the script needs void LoadSharedObjectInternal(); /** * \brief formats the output of /showincludes command in the .py file to only output the includes we are interested in. * \param[in] in One line of the output f _popen. * \param[out] outPath The path of the include. * \return If an include is found, outPath is only valid if this is true. */ bool GetInclude(std::string in, RCP::fs::path& outPath); /** * \brief Calls Compile with the isRecompiling flag turned true */ void Recompile(); /** * \brief Calls the LinkInternal method * \see LinkInternal */ void Relink(); /** * \brief Switches the outdated Objects for new ones and populates it with the serialized data after reloading has finished. */ void SwapRunningObjects(); /** * \brief Gets all of the scripts that include this script. They will have to also be recompiled, so that everything is up-to-date. * \param aAllIncluded All of the scripts that include the current script */ void GetIncludedScripts(std::unordered_map<std::string, std::shared_ptr<Script>>& aAllIncluded); //variables public: private: friend class ScriptLoader; ///pointer to the script parent. std::shared_ptr<Script> script; ///used to check if script is up to date. time_t lastScriptWriteTime = 0; ///dll handle. std::unique_ptr<SharedLibrary> sharedLibrary; ///This object stores all of the data the user doesn't want to lose during recompile. Storage* storage; ///the handle to the core logger LoggerHandle loggerHandle; std::shared_ptr<ConfigDirectories> directories; //the pointer to an exception static std::exception_ptr expptr; };
28.209677
131
0.720126
9d3d5188c6a71a0f789f2b5f4182d4bafc8a5f4a
140
c
C
src/libunixonacid/unixmessage_sender_x.c
hanhlinux/skalibs
e8407224cf8d625f6348ae03d2d60ed4823b69a8
[ "ISC" ]
84
2015-02-28T12:04:25.000Z
2022-03-29T07:49:27.000Z
src/libunixonacid/unixmessage_sender_x.c
hanhlinux/skalibs
e8407224cf8d625f6348ae03d2d60ed4823b69a8
[ "ISC" ]
3
2016-12-20T13:17:56.000Z
2021-04-11T12:45:20.000Z
src/libunixonacid/unixmessage_sender_x.c
hanhlinux/skalibs
e8407224cf8d625f6348ae03d2d60ed4823b69a8
[ "ISC" ]
30
2015-11-03T05:40:52.000Z
2021-12-28T03:36:40.000Z
/* ISC license. */ /* MT-unsafe */ #include <skalibs/unixmessage.h> unixmessage_sender unixmessage_sender_x_ = UNIXMESSAGE_SENDER_ZERO ;
17.5
68
0.757143
3ef59a47c57180422e81b485e347a58b6992823b
2,922
c
C
src/mppa_dl_sym.c
kalray/libmppadl
c6711e4b75e03278c8698fe435ba3286f87a8a9e
[ "MIT" ]
null
null
null
src/mppa_dl_sym.c
kalray/libmppadl
c6711e4b75e03278c8698fe435ba3286f87a8a9e
[ "MIT" ]
null
null
null
src/mppa_dl_sym.c
kalray/libmppadl
c6711e4b75e03278c8698fe435ba3286f87a8a9e
[ "MIT" ]
null
null
null
/** * Copyright (C) 2018 Kalray SA. */ #include "mppa_dl_sym.h" void *mppa_dl_sym_lookup2(mppa_dl_handle_t *hdl, const char *symbol) { MPPA_DL_LOG(1, "> mppa_dl_sym_lookup2(%p, %s)\n", hdl, symbol); ElfKVX_Sym sym; size_t bndx; size_t symndx; /* bucket index */ bndx = elf_hash(symbol) % hdl->nbucket; if (hdl->nchain < bndx || hdl->nbucket < bndx) { mppa_dl_errno(E_SYM_OUT); return NULL; } /* symbol index is given by the bucket table */ symndx = hdl->bucket[bndx]; sym = hdl->symtab[symndx]; /* check if symbol pointed by symndx is equal to needed symbol */ while (strcmp(symbol, &hdl->strtab[sym.st_name]) != 0) { /* update symbol index with chain table */ symndx = hdl->chain[symndx]; if (symndx == 0) { mppa_dl_errno(E_END_CHAIN); MPPA_DL_LOG(1, "< mppa_dl_sym_lookup2(%p, %s) -> NULL\n", hdl, symbol); return NULL; } sym = hdl->symtab[symndx]; } /* ELF is a shared object file, so sym.st_value holds the symbol address */ if (sym.st_shndx != SHN_UNDEF && hdl->type == ET_DYN) { MPPA_DL_LOG(2, ">> symbol found at offset 0x%lx\n", sym.st_value); ElfKVX_Addr ret = ((ElfKVX_Addr)hdl->addr + sym.st_value); MPPA_DL_LOG(1, "< mppa_dl_sym_lookup2(%p, %s) -> %lx\n", hdl, symbol, (long)ret); return (void*)ret; } MPPA_DL_LOG(1, "< mppa_dl_sym_lookup2(%p, %s) -> NO_SYM\n", hdl, symbol); mppa_dl_errno(E_NO_SYM); return NULL; } void *mppa_dl_sym_lookup(mppa_dl_handle_t *hdl, const char* symbol, int local) { MPPA_DL_LOG(1, "> mppa_dl_sym_lookup(%p, %s, local=%d)\n", hdl, symbol, local); void *sym; mppa_dl_handle_t *lookat; /* search symbol globally */ if (local == 0) { /* symbol search start at first parent of the current handle. */ lookat = hdl->parent; /* look in the tail of handle list */ while (lookat != NULL) { if (lookat->availability == MPPA_DL_GLOBAL) { sym = mppa_dl_sym_lookup2(lookat, symbol); if (sym != NULL || (sym == NULL && mppa_dl_errno_get_status() == E_NONE)) { MPPA_DL_LOG(1, "< mppa_dl_sym_lookup()\n"); return sym; } else { lookat = lookat->parent; } } else { lookat = lookat->parent; } } } /* look in the head of the handle list (or local search only) */ sym = mppa_dl_sym_lookup2(hdl, symbol); if (sym != NULL || (sym == NULL && mppa_dl_errno_get_status() == E_NONE)) return sym; MPPA_DL_LOG(1, "< mppa_dl_sym_lookup(%p, %s, local=%d)\n", hdl, symbol, local); return NULL; } void *mppa_dl_sym_lookup_local(struct mppa_dl_handle *hdl, const char *sym_name) { ElfKVX_Sym *sym; unsigned int i; if (hdl->sht_strtab == NULL || hdl->sht_symtab_syms == NULL) return NULL; for (i = 0; i < hdl->sht_symtab_nb_syms; i++) { sym = &hdl->sht_symtab_syms[i]; if (!strcmp(sym_name, &hdl->sht_strtab[sym->st_name])) return hdl->addr + sym->st_value; } return NULL; }
23.756098
78
0.634497
12be86c39a44b2a19813c1fc0224f3081cd6c0ec
50
h
C
src/Pixic runtime/src/library/include/core/typedefs/container/Containers.h
Seriy-MLGamer/Pixic
1000298bcd9d445bb82bf449c57f89bf4033529b
[ "MIT" ]
null
null
null
src/Pixic runtime/src/library/include/core/typedefs/container/Containers.h
Seriy-MLGamer/Pixic
1000298bcd9d445bb82bf449c57f89bf4033529b
[ "MIT" ]
null
null
null
src/Pixic runtime/src/library/include/core/typedefs/container/Containers.h
Seriy-MLGamer/Pixic
1000298bcd9d445bb82bf449c57f89bf4033529b
[ "MIT" ]
null
null
null
#pragma once typedef union Containers Containers;
16.666667
36
0.84
5c56b84aaefdf0da85d23c2e052800a288690942
75,120
c
C
ramcachefs.c
swillner/ramcachefs
42a9238a10669cef3c185182fc69060cd31dd904
[ "MIT" ]
null
null
null
ramcachefs.c
swillner/ramcachefs
42a9238a10669cef3c185182fc69060cd31dd904
[ "MIT" ]
null
null
null
ramcachefs.c
swillner/ramcachefs
42a9238a10669cef3c185182fc69060cd31dd904
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2021 Sven Willner <sven.willner@yfx.de> 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. */ #define _GNU_SOURCE #define FUSE_USE_VERSION 34 #include <assert.h> #include <dirent.h> #include <errno.h> #include <fuse_lowlevel.h> #include <inttypes.h> #include <limits.h> #include <pthread.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/file.h> #include <sys/ioctl.h> #include <sys/statvfs.h> #include <unistd.h> #ifndef DONT_USE_MMAP #include <sys/mman.h> #endif typedef char __assert_ino_t_large_enough[sizeof(fuse_ino_t) >= sizeof(uintptr_t) ? 1 : -1]; /* fuse_ino_t needs to hold a pointer */ #ifdef DEBUG #define debug(...) fuse_log(FUSE_LOG_DEBUG, __VA_ARGS__) #else #define debug(...) #endif static const double RAMCACHEFS_TIMEOUT = 86400.0; enum { RAMCACHEFS_TRIGGER_PERSIST = _IO('E', 0), }; struct ramcachefs_inode { /* the following are all protected by data->node_mutex: */ uint64_t nlookup; struct ramcachefs_inode* parent; struct ramcachefs_inode* prev; struct ramcachefs_inode* next; struct ramcachefs_inode* first_child; struct ramcachefs_inode* last_child; struct ramcachefs_inode* origin; /* which original file is represented by this content+info */ struct ramcachefs_inode* orig_moved_to; /* where the original content+info of orig_name has been moved to */ /* ALWAYS inode->origin->orig_moved_to == inode && inode->orig_moved_to->origin == inode */ char* orig_name; /* NULL if only in memory yet */ char* name; /* NULL if orig_name was deleted or moved to orig_moved_to */ /* the following do not need to be protected: */ fuse_ino_t ino; /* does not change */ off_t dir_offset; /* offset in parent dir */ size_t size; /* size of content (or strlen(content) for links) */ void* content; /* file content or (null-terminated) link target */ struct timespec times[2]; /* as for utimensat: 0: atime, 1: mtime */ uid_t uid; gid_t gid; mode_t mode; dev_t dev; unsigned int changed_content : 1; unsigned int changed_mode : 1; unsigned int changed_name : 1; unsigned int changed_owner : 1; unsigned int changed_time : 1; #ifndef DONT_USE_MMAP unsigned int file_backed : 1; /* mmap is still backed by file */ #endif }; struct ramcachefs_data { struct ramcachefs_inode* root; int direct_io; int prepopulate; int orig_root_fd; int opendir_result; unsigned long block_size; fsblkcnt_t max_blocks; fsfilcnt_t max_inodes; fsblkcnt_t free_blocks; /* protected by node_mutex */ fsfilcnt_t free_inodes; /* protected by node_mutex */ int writers; /* number of current writing threads, protected by writers_mutex */ pthread_mutex_t writers_mutex; /* protects writers (number of current writing threads */ pthread_mutex_t persist_mutex; /* looks writing operations while persisting is in progress */ pthread_mutex_t node_mutex; /* protects members in ramcachefs_inode that are accessible "from the outside", e.g. from their parent directory */ #ifdef DEBUG int debug; #endif }; struct ramcachefs_file_info { size_t max_written; int orig_flags; }; struct ramcachefs_opts { char* size; int direct_io; int noautopersist; int prepopulate; int trigger_persist; unsigned long max_inodes; }; static const struct fuse_opt ramcachefs_opts[] = { {"--trigger-persist", offsetof(struct ramcachefs_opts, trigger_persist), 1}, {"-p", offsetof(struct ramcachefs_opts, trigger_persist), 1}, {"direct_io", offsetof(struct ramcachefs_opts, direct_io), 1}, {"maxinodes=%u", offsetof(struct ramcachefs_opts, max_inodes), 1}, {"noautopersist", offsetof(struct ramcachefs_opts, noautopersist), 1}, {"prepopulate", offsetof(struct ramcachefs_opts, prepopulate), 1}, {"size=%s", offsetof(struct ramcachefs_opts, size), 1}, FUSE_OPT_END // }; #ifdef DEBUG static void print_inode_simple(const char* prefix, struct ramcachefs_inode* inode) { if (prefix) { fuse_log(FUSE_LOG_DEBUG, "%s", prefix); } if (inode) { fuse_log(FUSE_LOG_DEBUG, "%lu %s", inode->ino, inode->name); if (inode->orig_name) { fuse_log(FUSE_LOG_DEBUG, " [orig_name: %s]", inode->orig_name); } } else { fuse_log(FUSE_LOG_DEBUG, "(null)"); } fuse_log(FUSE_LOG_DEBUG, "\n"); } static void print_inode(struct ramcachefs_inode* inode) { fuse_log(FUSE_LOG_DEBUG, " ino: %lu\n", inode->ino); fuse_log(FUSE_LOG_DEBUG, " name: %s\n", inode->name); fuse_log(FUSE_LOG_DEBUG, " orig_name: %s\n", inode->orig_name); fuse_log(FUSE_LOG_DEBUG, " ch_content: %d\n", inode->changed_content); fuse_log(FUSE_LOG_DEBUG, " changed_mode: %d\n", inode->changed_mode); fuse_log(FUSE_LOG_DEBUG, " changed_name: %d\n", inode->changed_name); fuse_log(FUSE_LOG_DEBUG, " changed_owner: %d\n", inode->changed_owner); fuse_log(FUSE_LOG_DEBUG, " changed_time: %d\n", inode->changed_time); fuse_log(FUSE_LOG_DEBUG, " nlookup: %lu\n", inode->nlookup); print_inode_simple(" parent: ", inode->parent); print_inode_simple(" prev: ", inode->prev); print_inode_simple(" next: ", inode->next); print_inode_simple(" first_child: ", inode->first_child); print_inode_simple(" last_child: ", inode->last_child); print_inode_simple(" origin: ", inode->origin); print_inode_simple(" orig_moved_to: ", inode->orig_moved_to); fuse_log(FUSE_LOG_DEBUG, " dir_offset: %lu\n", inode->dir_offset); fuse_log(FUSE_LOG_DEBUG, " size: %lu\n", inode->size); fuse_log(FUSE_LOG_DEBUG, " atime: %lu\n", inode->times[0]); fuse_log(FUSE_LOG_DEBUG, " mtime: %lu\n", inode->times[1]); fuse_log(FUSE_LOG_DEBUG, " uid: %d\n", inode->uid); fuse_log(FUSE_LOG_DEBUG, " gid: %d\n", inode->gid); fuse_log(FUSE_LOG_DEBUG, " mode: %d\n", inode->mode); } static void print_parent_path(struct ramcachefs_inode* inode) { if (inode->parent) { print_parent_path(inode->parent); fuse_log(FUSE_LOG_DEBUG, "%s/", inode->parent->name); } } static void print_path(struct ramcachefs_inode* inode, struct ramcachefs_inode* fallbackparent, const char* fallbackname) { if (inode) { print_parent_path(inode); fuse_log(FUSE_LOG_DEBUG, "%s(%ld)", inode->name, inode->ino); } else if (fallbackparent) { print_parent_path(fallbackparent); fuse_log(FUSE_LOG_DEBUG, "%s/%s(not found)", fallbackparent->name, fallbackname); } else { fuse_log(FUSE_LOG_DEBUG, "?/%s(not found)", fallbackname); } } static void print_tree(struct ramcachefs_inode* inode, int depth) { static const int indentwidth = 4; const int indent = depth * indentwidth; fuse_log(FUSE_LOG_DEBUG, "%*s", indent, ""); print_inode_simple("", inode); if (inode->orig_moved_to) { fuse_log(FUSE_LOG_DEBUG, "%*s orig_moved_to=", indent, ""); print_inode_simple("", inode->orig_moved_to); if (inode != inode->orig_moved_to->origin) { fuse_log(FUSE_LOG_DEBUG, "%*s ERROR orig_moved_to->origin=", indent, ""); print_inode_simple("", inode->orig_moved_to->origin); } } if (inode->origin) { fuse_log(FUSE_LOG_DEBUG, "%*s origin=", indent, ""); print_inode_simple("", inode->origin); if (inode != inode->origin->orig_moved_to) { fuse_log(FUSE_LOG_DEBUG, "%*s ERROR origin->orig_moved_to=", indent, ""); print_inode_simple("", inode->origin->orig_moved_to); } } struct ramcachefs_inode* child = inode->first_child; struct ramcachefs_inode* prev = NULL; while (child) { print_tree(child, depth + 1); if (prev != child->prev) { fuse_log(FUSE_LOG_DEBUG, "%*sERROR prev=", indent + indentwidth, ""); print_inode_simple("", child->prev); } prev = child; child = child->next; } if (prev && prev->next) { fuse_log(FUSE_LOG_DEBUG, "%*sERROR next=", indent + indentwidth, ""); print_inode_simple("", prev->next); } if (prev != inode->last_child) { fuse_log(FUSE_LOG_DEBUG, "%*sERROR last_child=", indent, ""); print_inode_simple("", inode->last_child); } } #endif static struct ramcachefs_data* get_data(fuse_req_t req) { return (struct ramcachefs_data*)fuse_req_userdata(req); } static struct ramcachefs_inode* get_inode(fuse_req_t req, fuse_ino_t ino) { if (ino == FUSE_ROOT_ID) { return get_data(req)->root; } return (struct ramcachefs_inode*)(uintptr_t)ino; } static void start_writing(struct ramcachefs_data* data) { pthread_mutex_lock(&data->writers_mutex); ++data->writers; if (data->writers == 1) { pthread_mutex_lock(&data->persist_mutex); } pthread_mutex_unlock(&data->writers_mutex); } static void stop_writing(struct ramcachefs_data* data) { pthread_mutex_lock(&data->writers_mutex); --data->writers; if (data->writers == 0) { pthread_mutex_unlock(&data->persist_mutex); } pthread_mutex_unlock(&data->writers_mutex); } static struct ramcachefs_inode* alloc_inode(const char* name, struct stat* stbuf) { struct ramcachefs_inode* inode = malloc(sizeof(struct ramcachefs_inode)); if (inode) { memset(inode, 0, sizeof(struct ramcachefs_inode)); inode->ino = (fuse_ino_t)inode; inode->nlookup = 1; if (name) { inode->name = strdup(name); if (!inode->name) { free(inode); return NULL; } } if (stbuf) { inode->mode = stbuf->st_mode; inode->uid = stbuf->st_uid; inode->gid = stbuf->st_gid; inode->size = stbuf->st_size; inode->times[0] = stbuf->st_atim; inode->times[1] = stbuf->st_mtim; inode->dev = stbuf->st_rdev; } } return inode; } static void set_parent_unsafe(struct ramcachefs_inode* inode, struct ramcachefs_inode* parent) { /* data->node_mutex must be locked */ inode->parent = parent; if (parent->first_child) { parent->last_child->next = inode; inode->prev = parent->last_child; inode->dir_offset = parent->last_child->dir_offset + 1; parent->last_child = inode; } else { inode->dir_offset = 1; parent->first_child = inode; parent->last_child = inode; } } static void remove_inode_from_parent_unsafe(struct ramcachefs_inode* child) { /* data->node_mutex must be locked */ if (child == child->parent->first_child) { child->parent->first_child = child->next; } if (child == child->parent->last_child) { child->parent->last_child = child->prev; } if (child->next) { child->next->prev = child->prev; } if (child->prev) { child->prev->next = child->next; } child->parent = NULL; child->prev = NULL; child->next = NULL; } static void free_inode(struct ramcachefs_inode* inode) { struct ramcachefs_inode* child = inode->first_child; struct ramcachefs_inode* next_child; while (child) { next_child = child->next; free_inode(child); child = next_child; } free(inode->orig_name); free(inode->name); #ifdef DONT_USE_MMAP free(inode->content); #else if (S_ISREG(inode->mode)) { if (inode->content && munmap(inode->content, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap failed: %m\n"); } } else { free(inode->content); } #endif free(inode); } static int is_dot_or_dotdot(const char* name) { return name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')); } static int cache_dir_unsafe(struct ramcachefs_data* data, struct ramcachefs_inode* dirnode, DIR* dir) { /* not thread safe */ struct ramcachefs_inode* inode; struct stat stbuf; DIR* subdir; int fd; errno = 0; struct dirent* entry; for (entry = readdir(dir); entry; entry = readdir(dir)) { if (is_dot_or_dotdot(entry->d_name)) { continue; } if (fstatat(dirfd(dir), entry->d_name, &stbuf, AT_SYMLINK_NOFOLLOW)) { fuse_log(FUSE_LOG_ERR, "can't fstatat `%s': %m\n", entry->d_name); return 1; } if (data->free_inodes == 0) { fuse_log(FUSE_LOG_ERR, "no space left\n"); return 1; } inode = alloc_inode(entry->d_name, &stbuf); if (!inode) { fuse_log(FUSE_LOG_ERR, "can't allocate memory: %m\n"); return 1; } --data->free_inodes; inode->orig_name = strdup(entry->d_name); if (!inode->orig_name) { fuse_log(FUSE_LOG_ERR, "can't allocate memory: %m\n"); goto err_out; } switch (stbuf.st_mode & S_IFMT) { case S_IFDIR: /* directory */ fd = openat(dirfd(dir), entry->d_name, O_DIRECTORY | O_NOATIME | O_RDONLY); if (fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", entry->d_name); goto err_out; } subdir = fdopendir(fd); if (!subdir) { fuse_log(FUSE_LOG_ERR, "can't open `%s' using fdopendir: %m\n", entry->d_name); goto err_out; } if (cache_dir_unsafe(data, inode, subdir)) { closedir(subdir); goto err_out; } closedir(subdir); break; case S_IFLNK: /* symbolic link */ if (inode->size > 0) { inode->content = calloc(inode->size + 1, sizeof(char)); if (!inode->content) { fuse_log(FUSE_LOG_ERR, "can't allocate memory: %m\n"); goto err_out; } ssize_t res = readlinkat(dirfd(dir), entry->d_name, inode->content, inode->size); if (res < 0) { fuse_log(FUSE_LOG_ERR, "can't read link `%s': %m\n", entry->d_name); free(inode->content); inode->content = NULL; goto err_out; } } break; case S_IFREG: /* regular file */ if (inode->size > 0) { size_t needed_size = (inode->size + data->block_size - 1) / data->block_size; if (needed_size > data->free_blocks) { fuse_log(FUSE_LOG_ERR, "no space left\n"); goto err_out; } fd = openat(dirfd(dir), entry->d_name, O_NOATIME | O_RDONLY); if (fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", entry->d_name); goto err_out; } #ifdef DONT_USE_MMAP inode->content = malloc(inode->size); if (!inode->content) { fuse_log(FUSE_LOG_ERR, "can't allocate memory: %m\n"); close(fd); goto err_out; } ssize_t res; ssize_t size = inode->size; char* buf = inode->content; while (1) { res = read(fd, buf, size); if (res < 0) { fuse_log(FUSE_LOG_ERR, "can't read from `%s': %m\n", entry->d_name); goto err_out; } if (res == size) { break; } size -= res; buf += res; } #else inode->content = mmap(NULL, inode->size, PROT_READ | PROT_WRITE, MAP_PRIVATE | (data->prepopulate ? MAP_POPULATE : 0), fd, 0); if (inode->content == MAP_FAILED) { fuse_log(FUSE_LOG_ERR, "mmap failed: %m\n"); close(fd); goto err_out; } inode->file_backed = 1; #endif close(fd); data->free_blocks -= needed_size; } break; case S_IFBLK: /* block device */ case S_IFCHR: /* character device */ case S_IFIFO: /* FIFO */ case S_IFSOCK: /* socket */ /* these are handled by stat already */ break; default: fuse_log(FUSE_LOG_ERR, "unsupported file type for `%s'\n", entry->d_name); goto err_out; } set_parent_unsafe(inode, dirnode); } if (errno) { fuse_log(FUSE_LOG_ERR, "readdir failed: %m\n"); return 1; } return 0; err_out: ++data->free_inodes; free_inode(inode); return 1; } static int resize_file_unsafe(struct ramcachefs_data* data, struct ramcachefs_inode* inode, size_t newsize) { /* must be protected by start/stop_writing(data) */ if (newsize == inode->size) { return 0; } if (newsize == 0) { #ifdef DONT_USE_MMAP free(inode->content); #else if (munmap(inode->content, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap failed: %m\n"); } #endif data->free_blocks += (inode->size + data->block_size - 1) / data->block_size; inode->content = NULL; inode->size = 0; return 0; } if (newsize > inode->size && data->free_blocks < (newsize + data->block_size - 1) / data->block_size - (inode->size + data->block_size - 1) / data->block_size) { return ENOSPC; } void* newbuf; #ifdef DONT_USE_MMAP newbuf = realloc(inode->content, newsize); if (!newbuf) { return ENOMEM; } if (newsize > inode->size) { memset(newbuf + inode->size, 0, newsize - inode->size); } #else if (inode->file_backed || !inode->content) { newbuf = mmap(NULL, newsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } else { newbuf = mremap(inode->content, inode->size, newsize, MREMAP_MAYMOVE); } if (newbuf == MAP_FAILED) { fuse_log(FUSE_LOG_ERR, "mmap or mremap failed: %m\n"); return errno; } if (inode->file_backed) { memcpy(newbuf, inode->content, inode->size < newsize ? inode->size : newsize); if (munmap(inode->content, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap failed: %m\n"); } inode->file_backed = 0; } #endif data->free_blocks += (inode->size + data->block_size - 1) / data->block_size; data->free_blocks -= (newsize + data->block_size - 1) / data->block_size; inode->content = newbuf; inode->size = newsize; return 0; } static void fill_stat(struct stat* stbuf, struct ramcachefs_inode* inode) { stbuf->st_dev = 0; /* ignored by libfuse */ stbuf->st_ino = inode->ino; stbuf->st_mode = inode->mode; stbuf->st_nlink = S_ISDIR(inode->mode) ? 2 : 1; stbuf->st_uid = inode->uid; stbuf->st_gid = inode->gid; stbuf->st_rdev = inode->dev; stbuf->st_size = inode->size; stbuf->st_blksize = 0; /* ignored by libfuse */ stbuf->st_blocks = (inode->size + 511) / 512; stbuf->st_atim = inode->times[0]; stbuf->st_mtim = inode->times[1]; } static struct ramcachefs_inode* find_child(struct ramcachefs_data* data, struct ramcachefs_inode* inode, const char* name) { pthread_mutex_lock(&data->node_mutex); struct ramcachefs_inode* child = inode->first_child; while (child) { if (child->name && strcmp(name, child->name) == 0) { goto out; } child = child->next; } out: pthread_mutex_unlock(&data->node_mutex); return child; } static int get_original_path_internal_unsafe(struct ramcachefs_inode* inode, char** out, int is_last, int came_from_origin) { if (!inode->parent) { return 0; } if (inode->origin && !came_from_origin) { /* make sure to not jump twice using origin (for swapped inodes) */ return get_original_path_internal_unsafe(inode->origin, out, is_last, 1); } int offset = get_original_path_internal_unsafe(inode->parent, out, 0, 0); int len = strlen(inode->orig_name); *out = realloc(*out, offset + len + (is_last ? 1 : 2)); memcpy(*out + offset, inode->orig_name, len + 1); if (!is_last) { (*out)[offset + len] = '/'; (*out)[offset + len + 1] = '\0'; return offset + len + 1; } return offset + len; } static char* get_original_path_unsafe(struct ramcachefs_inode* inode) { char* out = NULL; get_original_path_internal_unsafe(inode, &out, 1, 0); return out; } static int persist_internal_unsafe(struct ramcachefs_data* data, int parentfd, struct ramcachefs_inode* inode, int depth) { #ifdef DEBUG const int indent = depth * 4; fuse_log(FUSE_LOG_DEBUG, "%*s", indent, ""); print_inode_simple("", inode); #endif #ifdef DEBUG_DETAILS if (inode->orig_moved_to) { fuse_log(FUSE_LOG_DEBUG, "%*s orig_moved_to=", indent, ""); print_inode_simple("", inode->orig_moved_to); if (inode != inode->orig_moved_to->origin) { fuse_log(FUSE_LOG_DEBUG, "%*s ERROR orig_moved_to->origin=", indent, ""); print_inode_simple("", inode->orig_moved_to->origin); } } if (inode->origin) { fuse_log(FUSE_LOG_DEBUG, "%*s origin=", indent, ""); print_inode_simple("", inode->origin); if (inode != inode->origin->orig_moved_to) { fuse_log(FUSE_LOG_DEBUG, "%*s ERROR origin->orig_moved_to=", indent, ""); print_inode_simple("", inode->origin->orig_moved_to); } } #endif if (inode->orig_moved_to && inode->orig_moved_to->orig_moved_to != inode) { return 1; } if (inode->origin) { char* original_path = get_original_path_unsafe(inode); debug("%*s move %s -> %s\n", indent, "", original_path, inode->name); int exchange = inode->origin->origin == inode; if (renameat2(data->orig_root_fd, original_path, parentfd, inode->name, exchange ? RENAME_EXCHANGE : 0)) { fuse_log(FUSE_LOG_ERR, "can't move `%s' to `%s': %m\n", original_path, inode->origin->orig_name); return -1; } if (exchange) { char* tmpchar = inode->orig_name; inode->orig_name = inode->origin->orig_name; inode->origin->orig_name = tmpchar; } else { free(inode->origin->orig_name); inode->origin->orig_name = NULL; free(inode->orig_name); inode->orig_name = strdup(inode->name); } inode->changed_name = 0; free(original_path); if (!inode->origin->orig_moved_to->name) { free(inode->origin->orig_moved_to->orig_name); inode->origin->orig_moved_to->orig_name = NULL; } inode->origin->orig_moved_to = NULL; inode->origin = NULL; } else if (inode->name) { if (inode->changed_name) { debug("%*s rename %s -> %s\n", indent, "", inode->orig_name, inode->name); if (renameat2(parentfd, inode->orig_name, parentfd, inode->name, RENAME_NOREPLACE)) { fuse_log(FUSE_LOG_ERR, "can't rename `%s' to `%s': %m\n", inode->orig_name, inode->name); return -1; } free(inode->orig_name); inode->orig_name = strdup(inode->name); inode->changed_name = 0; } if (!inode->orig_name) { debug("%*s create\n", indent, ""); switch (inode->mode & S_IFMT) { case S_IFDIR: /* directory */ if (mkdirat(parentfd, inode->name, inode->mode)) { fuse_log(FUSE_LOG_ERR, "can't mkdir `%s': %m\n", inode->name); return -1; } break; case S_IFLNK: /* symbolic link */ if (symlinkat(inode->content, parentfd, inode->name)) { fuse_log(FUSE_LOG_ERR, "can't symlink `%s': %m\n", inode->name); return -1; } break; case S_IFREG: /* regular file */ inode->changed_content = 1; break; case S_IFBLK: /* block device */ case S_IFCHR: /* character device */ case S_IFSOCK: /* socket */ if (mknodat(parentfd, inode->name, inode->mode, inode->dev)) { fuse_log(FUSE_LOG_ERR, "can't mknod `%s': %m\n", inode->name); return -1; } break; case S_IFIFO: /* FIFO */ if (mkfifoat(parentfd, inode->name, inode->mode)) { fuse_log(FUSE_LOG_ERR, "can't mkfifo `%s': %m\n", inode->name); return -1; } break; fuse_log(FUSE_LOG_ERR, "can't persist socket file `%s'\n", inode->name); break; default: fuse_log(FUSE_LOG_ERR, "unsupported file type for `%s'\n", inode->name); return -1; } inode->changed_name = 0; inode->changed_mode = 0; /* either already handled my mkdirat/symlinkat/mknodat/mkfifoat or later by openat */ inode->changed_owner = 1; inode->changed_time = 1; inode->orig_name = strdup(inode->name); } #ifdef DEBUG_DETAILS if (strcmp(inode->name, inode->orig_name)) { print_inode(inode); return -1; } #endif if (inode->changed_content) { if (S_ISREG(inode->mode)) { debug("%*s write\n", indent, ""); #ifdef DONT_USE_MMAP int fd = openat(parentfd, inode->name, O_CREAT | O_TRUNC | O_WRONLY, inode->mode); if (fd >= 0) { ssize_t written; ssize_t size = inode->size; void* buf = inode->content; while (1) { errno = 0; written = write(fd, buf, size); if (written < 0) { if (errno == EINTR) { continue; } fuse_log(FUSE_LOG_ERR, "can't write to `%s': %m\n", inode->name); close(fd); return -1; } if (written == size) { break; } size -= written; buf += written; } #else int fd = openat(parentfd, inode->name, O_CREAT | O_RDWR, inode->mode); if (fd >= 0) { if (ftruncate(fd, inode->size)) { fuse_log(FUSE_LOG_ERR, "ftruncate `%s' failed: %m\n", inode->name); close(fd); return -1; } if (inode->size > 0) { void* buf = mmap(NULL, inode->size, PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fuse_log(FUSE_LOG_ERR, "mmap `%s' failed: %m\n", inode->name); close(fd); return -1; } memcpy(buf, inode->content, inode->size); if (munmap(buf, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap `%s' failed: %m\n", inode->name); close(fd); return -1; } if (munmap(inode->content, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap `%s' failed: %m\n", inode->name); close(fd); return -1; } inode->content = mmap(NULL, inode->size, PROT_READ | PROT_WRITE, MAP_PRIVATE | (data->prepopulate ? MAP_POPULATE : 0), fd, 0); if (inode->content == MAP_FAILED) { fuse_log(FUSE_LOG_ERR, "mmap `%s' failed: %m\n", inode->name); close(fd); return -1; } inode->file_backed = 1; } #endif close(fd); } else { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", inode->name); return -1; } } inode->changed_content = 0; } if (inode->changed_mode) { debug("%*s chmod\n", indent, ""); if (fchmodat(parentfd, inode->name, inode->mode, AT_SYMLINK_NOFOLLOW)) { if (errno != ENOTSUP || fchmodat(parentfd, inode->name, inode->mode, 0)) { fuse_log(FUSE_LOG_ERR, "can't chmod `%s': %m\n", inode->name); return -1; } } inode->changed_mode = 0; } if (inode->changed_owner) { debug("%*s chown\n", indent, ""); if (fchownat(parentfd, inode->name, inode->uid, inode->gid, AT_SYMLINK_NOFOLLOW)) { if (errno != ENOTSUP || fchownat(parentfd, inode->name, inode->uid, inode->gid, 0)) { fuse_log(FUSE_LOG_ERR, "can't chown `%s': %m\n", inode->name); return -1; } } inode->changed_owner = 0; } if (inode->changed_time) { debug("%*s change time\n", indent, ""); if (utimensat(parentfd, inode->name, inode->times, AT_SYMLINK_NOFOLLOW)) { fuse_log(FUSE_LOG_ERR, "can't utimensat `%s': %m\n", inode->name); return -1; } inode->changed_time = 0; } } if (inode->orig_name) { if (S_ISDIR(inode->mode)) { int res = 0; int fd = openat(parentfd, inode->orig_name, O_DIRECTORY); if (fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", inode->orig_name); return -1; } struct ramcachefs_inode* next; struct ramcachefs_inode* child = inode->first_child; while (child) { res |= persist_internal_unsafe(data, fd, child, depth + 1); if (res < 0) { close(fd); return res; } next = child->next; if (!child->name && !child->orig_name && !child->orig_moved_to && !child->origin) { debug("%*s removing inode\n", indent, ""); remove_inode_from_parent_unsafe(child); ++data->free_inodes; free_inode(child); } child = next; } close(fd); } if (!inode->name) { debug("%*s delete\n", indent, ""); if (unlinkat(parentfd, inode->orig_name, S_ISDIR(inode->mode) ? AT_REMOVEDIR : 0)) { fuse_log(FUSE_LOG_ERR, "can't rename `%s' to `%s': %m\n", inode->orig_name, inode->name); return -1; } free(inode->orig_name); inode->orig_name = NULL; } } return 0; } static int persist(struct ramcachefs_data* data) { debug("persisting...\n"); pthread_mutex_lock(&data->persist_mutex); pthread_mutex_lock(&data->node_mutex); #ifdef DEBUG_DETAILS fuse_log(FUSE_LOG_DEBUG, "\nbefore persisting:\n"); print_tree(data->root, 0); #endif int res = 1; int dir = openat(data->orig_root_fd, ".", O_DIRECTORY); if (dir < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", data->root->orig_name); res = -1; goto out1; } struct ramcachefs_inode* next; struct ramcachefs_inode* child; while (res) { #ifdef DEBUG_DETAILS fuse_log(FUSE_LOG_DEBUG, "\npersisting round:\n"); #endif res = 0; child = data->root->first_child; while (child) { res |= persist_internal_unsafe(data, dir, child, 1); if (res < 0) { goto out2; } next = child->next; if (!child->name && !child->orig_name && !child->orig_moved_to && !child->origin) { debug(" removing inode\n"); remove_inode_from_parent_unsafe(child); ++data->free_inodes; free_inode(child); } child = next; } } if (data->root->changed_mode) { debug(" chmod\n"); if (fchmod(dir, data->root->mode)) { fuse_log(FUSE_LOG_ERR, "can't chmod `%s': %m\n", data->root->orig_name); res = -1; goto out2; } data->root->changed_mode = 0; } if (data->root->changed_owner) { debug(" chown\n"); if (fchown(dir, data->root->uid, data->root->gid)) { fuse_log(FUSE_LOG_ERR, "can't chown `%s': %m\n", data->root->orig_name); res = -1; goto out2; } data->root->changed_owner = 0; } if (data->root->changed_time) { debug(" change time\n"); if (futimens(dir, data->root->times)) { fuse_log(FUSE_LOG_ERR, "can't utimensat `%s': %m\n", data->root->orig_name); res = -1; goto out2; } data->root->changed_time = 0; } out2: close(dir); out1: #ifdef DEBUG_DETAILS fuse_log(FUSE_LOG_DEBUG, "\nafter persisting:\n"); print_tree(data->root, 0); fuse_log(FUSE_LOG_DEBUG, "\n"); #endif pthread_mutex_unlock(&data->node_mutex); pthread_mutex_unlock(&data->persist_mutex); return res < 0 ? 1 : 0; } static void forget_inode_unsafe(struct ramcachefs_data* data, struct ramcachefs_inode* inode, uint64_t nlookup) { /* data->node_mutex must be locked */ if (nlookup < inode->nlookup) { inode->nlookup -= nlookup; } else { if (inode->origin) { /* this inode represents an original file, mark this as deleted as well */ inode->origin->orig_moved_to = NULL; inode->origin = NULL; } if (inode->nlookup) { inode->nlookup = 0; free(inode->name); inode->name = NULL; if (S_ISREG(inode->mode)) { data->free_blocks += (inode->size + data->block_size - 1) / data->block_size; } #ifdef DONT_USE_MMAP free(inode->content); #else if (S_ISREG(inode->mode)) { if (inode->content && munmap(inode->content, inode->size)) { fuse_log(FUSE_LOG_ERR, "munmap failed: %m\n"); } } else { free(inode->content); } #endif inode->content = NULL; inode->size = 0; } if (!inode->orig_name) { if (inode->prev || inode->next || inode->first_child) { fuse_log(FUSE_LOG_ERR, "error: trying to forget inode %lu which is still linked\n", inode->ino); } else { ++data->free_inodes; free_inode(inode); } } } } static void interchange_inodes_unsafe(struct ramcachefs_inode* i, struct ramcachefs_inode* j) { /* data->node_mutex must be locked */ /* interchange node positions keeping their dir_offset, orig_moved_to, name, and orig_name in place */ struct ramcachefs_inode* tmpnode; char* tmpname; off_t tmpoff; tmpnode = i->orig_moved_to; i->orig_moved_to = j->orig_moved_to; j->orig_moved_to = tmpnode; tmpname = i->name; i->name = j->name; j->name = tmpname; tmpname = i->orig_name; i->orig_name = j->orig_name; j->orig_name = tmpname; tmpoff = i->dir_offset; i->dir_offset = j->dir_offset; j->dir_offset = tmpoff; if (i->parent != j->parent) { tmpnode = i->parent; i->parent = j->parent; j->parent = tmpnode; if (i->parent) { if (i->parent->first_child == j) { i->parent->first_child = i; } if (i->parent->last_child == j) { i->parent->last_child = i; } } if (j->parent) { if (j->parent->first_child == i) { j->parent->first_child = j; } if (j->parent->last_child == i) { j->parent->last_child = j; } } } else { if (i->parent) { if (i->parent->first_child == j) { i->parent->first_child = i; } else if (j->parent->first_child == i) { j->parent->first_child = j; } if (i->parent->last_child == j) { i->parent->last_child = i; } else if (j->parent->last_child == i) { j->parent->last_child = j; } } } if (i->prev == j) { /* then also j->next == i */ tmpnode = j->prev; j->prev = i; i->prev = tmpnode; tmpnode = i->next; i->next = j; j->next = tmpnode; if (i->prev) { i->prev->next = i; } if (j->next) { j->next->prev = j; } } else if (j->prev == i) { /* then also i->next == j */ tmpnode = i->prev; i->prev = j; j->prev = tmpnode; tmpnode = j->next; j->next = i; i->next = tmpnode; if (i->next) { i->next->prev = i; } if (j->prev) { j->prev->next = j; } } else { tmpnode = i->prev; i->prev = j->prev; j->prev = tmpnode; tmpnode = i->next; i->next = j->next; j->next = tmpnode; if (i->prev) { i->prev->next = i; } if (i->next) { i->next->prev = i; } if (j->prev) { j->prev->next = j; } if (j->next) { j->next->prev = j; } } if (i->orig_moved_to) { i->orig_moved_to->origin = i; } else if (i->orig_name && !j->origin) { /* if i->orig_name && j->origin then i->orig_name has already been overwritten */ i->orig_moved_to = j; j->origin = i; } if (j->orig_moved_to) { j->orig_moved_to->origin = j; } else if (j->orig_name && !i->origin) { /* if j->orig_name && i->origin then j->orig_name has already been overwritten */ j->orig_moved_to = i; i->origin = j; } } static struct ramcachefs_file_info* new_file_info(struct fuse_file_info* fi) { struct ramcachefs_file_info* rfi = malloc(sizeof(struct ramcachefs_file_info)); if (rfi) { rfi->max_written = 0; rfi->orig_flags = fi->flags; fi->fh = (uint64_t)rfi; } return rfi; } static void mark_inode_removed_unsafe(struct ramcachefs_data* data, struct ramcachefs_inode* inode) { /* data->node_mutex must be locked */ free(inode->name); inode->name = NULL; if (inode->origin) { /* this inode represents an original file, mark that as deleted as well */ inode->origin->orig_moved_to = NULL; inode->origin = NULL; } if (!inode->orig_name) { remove_inode_from_parent_unsafe(inode); } forget_inode_unsafe(data, inode, 1); } static void remove_file_or_dir(fuse_req_t req, fuse_ino_t parent, const char* name, int rmdir) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* parentnode = get_inode(req, parent); struct ramcachefs_inode* child = find_child(data, parentnode, name); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " remove_file_or_dir "); print_path(child, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if (!child) { fuse_reply_err(req, ENOENT); return; } start_writing(data); pthread_mutex_lock(&data->node_mutex); int res = 0; if (rmdir && child->first_child) { res = ENOTEMPTY; } else { mark_inode_removed_unsafe(data, child); } pthread_mutex_unlock(&data->node_mutex); stop_writing(data); fuse_reply_err(req, res); } static void ramcachefs_copy_file_range(fuse_req_t req, fuse_ino_t ino_in, off_t off_in, struct fuse_file_info* UNUSED_fi_in, fuse_ino_t ino_out, off_t off_out, struct fuse_file_info* fi_out, size_t len, int UNUSED_flags) { (void)UNUSED_fi_in; (void)UNUSED_flags; struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode_in = get_inode(req, ino_in); struct ramcachefs_inode* inode_out = get_inode(req, ino_out); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " remove_file_or_dir "); print_path(inode_in, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, " to "); print_path(inode_out, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if (off_in + len > inode_in->size) { fuse_reply_err(req, EINVAL); return; } start_writing(data); if (off_out + len > inode_out->size) { pthread_mutex_lock(&data->node_mutex); int res = resize_file_unsafe(data, inode_out, off_out + len); pthread_mutex_unlock(&data->node_mutex); if (res) { stop_writing(data); fuse_reply_err(req, res); return; } } inode_out->changed_content = 1; if (inode_out->mode & (S_ISUID | S_ISGID)) { inode_out->changed_mode = 1; inode_out->mode &= ~(S_ISUID | S_ISGID); } memcpy(inode_out->content + off_out, inode_in->content + off_in, len); stop_writing(data); struct ramcachefs_file_info* rfi = (struct ramcachefs_file_info*)fi_out->fh; if (off_out + len > rfi->max_written) { rfi->max_written = off_out + len; } fuse_reply_write(req, len); } static int mkinode(fuse_req_t req, struct ramcachefs_inode* parentnode, struct ramcachefs_inode* inode, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); const struct fuse_ctx* ctx = fuse_req_ctx(req); if (ctx) { inode->uid = ctx->uid; inode->gid = ctx->gid; } clock_gettime(CLOCK_REALTIME, &inode->times[0]); clock_gettime(CLOCK_REALTIME, &inode->times[1]); struct fuse_entry_param entry = { .ino = inode->ino, .attr_timeout = RAMCACHEFS_TIMEOUT, .entry_timeout = RAMCACHEFS_TIMEOUT, .generation = 0, }; fill_stat(&entry.attr, inode); pthread_mutex_lock(&data->node_mutex); if (data->free_inodes == 0) { fuse_reply_err(req, ENOSPC); free_inode(inode); pthread_mutex_unlock(&data->node_mutex); return 1; } int res; if (fi) { res = fuse_reply_create(req, &entry, fi); } else { res = fuse_reply_entry(req, &entry); } if (res) { free_inode(inode); pthread_mutex_unlock(&data->node_mutex); return 1; } --data->free_inodes; ++inode->nlookup; set_parent_unsafe(inode, parentnode); pthread_mutex_unlock(&data->node_mutex); return 0; } static void ramcachefs_create(fuse_req_t req, fuse_ino_t parent, const char* name, mode_t mode, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* parentnode = get_inode(req, parent); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " create "); print_path(NULL, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif struct ramcachefs_file_info* rfi = new_file_info(fi); if (!rfi) { fuse_reply_err(req, ENOMEM); return; } struct ramcachefs_inode* inode = alloc_inode(name, NULL); if (!inode) { fuse_reply_err(req, ENOMEM); free(rfi); fi->fh = 0; return; } inode->mode = mode; if (data->direct_io || (fi->flags & O_DIRECT)) { fi->direct_io = 1; } if (mkinode(req, parentnode, inode, fi)) { free(rfi); fi->fh = 0; } } static void ramcachefs_forget(fuse_req_t req, fuse_ino_t ino, uint64_t nlookup) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " forget "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif pthread_mutex_lock(&data->node_mutex); forget_inode_unsafe(data, inode, nlookup); pthread_mutex_unlock(&data->node_mutex); fuse_reply_none(req); } static void ramcachefs_forget_multi(fuse_req_t req, size_t count, struct fuse_forget_data* forgets) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode; pthread_mutex_lock(&data->node_mutex); size_t i; for (i = 0; i < count; ++i) { inode = get_inode(req, forgets[i].ino); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " forget_multi "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif forget_inode_unsafe(data, inode, forgets[i].nlookup); } pthread_mutex_unlock(&data->node_mutex); fuse_reply_none(req); } static void ramcachefs_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* UNUSED_fi) { (void)UNUSED_fi; struct stat stbuf; struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " getattr "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif fill_stat(&stbuf, inode); fuse_reply_attr(req, &stbuf, RAMCACHEFS_TIMEOUT); } static void ramcachefs_init(void* userdata, struct fuse_conn_info* conn) { struct ramcachefs_data* data = userdata; /* FUSE docs on FUSE_CAP_ASYNC_DIO: * * Indicates that the filesystem supports asynchronous direct I/O submission. * * If this capability is not requested/available, the kernel will ensure that * there is at most one pending read and one pending write request per direct * I/O file-handle at any time. */ conn->want &= ~FUSE_CAP_ASYNC_DIO; /* FUSE docs on FUSE_CAP_NO_OPENDIR_SUPPORT: * * Indicates support for zero-message opendirs. If this flag is set in * the `capable` field of the `fuse_conn_info` structure, then the filesystem * may return `ENOSYS` from the opendir() handler to indicate success. Further * opendir and releasedir messages will be handled in the kernel. (If this * flag is not set, returning ENOSYS will be treated as an error and signalled * to the caller.) */ if (conn->capable & FUSE_CAP_NO_OPENDIR_SUPPORT) { data->opendir_result = ENOSYS; } if (conn->capable & FUSE_CAP_SPLICE_WRITE) { conn->want |= FUSE_CAP_SPLICE_WRITE; } if (conn->capable & FUSE_CAP_SPLICE_READ) { conn->want |= FUSE_CAP_SPLICE_READ; } if (conn->capable & FUSE_CAP_SPLICE_MOVE) { conn->want |= FUSE_CAP_SPLICE_MOVE; } } static void ramcachefs_ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void* UNUSED_arg, struct fuse_file_info* UNUSED_fi, unsigned flags, const void* UNUSED_in_buf, size_t UNUSED_in_bufsz, size_t UNUSED_out_bufsz) { (void)UNUSED_arg; (void)UNUSED_fi; (void)UNUSED_in_buf; (void)UNUSED_in_bufsz; (void)UNUSED_out_bufsz; if (flags & FUSE_IOCTL_COMPAT) { fuse_reply_err(req, ENOSYS); return; } #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { struct ramcachefs_inode* inode = get_inode(req, ino); fuse_log(FUSE_LOG_DEBUG, " ioctl "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif switch (cmd) { case RAMCACHEFS_TRIGGER_PERSIST: fuse_reply_ioctl(req, ino == FUSE_ROOT_ID ? persist(get_data(req)) : -1, NULL, 0); return; } fuse_reply_err(req, EINVAL); } static void ramcachefs_lookup(fuse_req_t req, fuse_ino_t parent, const char* name) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* parentnode = get_inode(req, parent); struct ramcachefs_inode* child = find_child(data, parentnode, name); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " lookup "); print_path(child, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if (!child) { fuse_reply_err(req, ENOENT); return; } struct fuse_entry_param entry = { .ino = child->ino, .attr_timeout = RAMCACHEFS_TIMEOUT, .entry_timeout = RAMCACHEFS_TIMEOUT, .generation = 0, }; fill_stat(&entry.attr, child); pthread_mutex_lock(&data->node_mutex); if (!fuse_reply_entry(req, &entry)) { ++child->nlookup; } pthread_mutex_unlock(&data->node_mutex); } static void ramcachefs_mkdir(fuse_req_t req, fuse_ino_t parent, const char* name, mode_t mode) { struct ramcachefs_inode* parentnode = get_inode(req, parent); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " mkdir "); print_path(NULL, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif struct ramcachefs_inode* inode = alloc_inode(name, NULL); if (!inode) { fuse_reply_err(req, ENOMEM); return; } inode->mode = mode | S_IFDIR; mkinode(req, parentnode, inode, NULL); } static void ramcachefs_mknod(fuse_req_t req, fuse_ino_t parent, const char* name, mode_t mode, dev_t rdev) { struct ramcachefs_inode* parentnode = get_inode(req, parent); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " mknod "); print_path(NULL, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif struct ramcachefs_inode* inode = alloc_inode(name, NULL); if (!inode) { fuse_reply_err(req, ENOMEM); return; } inode->mode = mode; inode->dev = rdev; mkinode(req, parentnode, inode, NULL); } static void ramcachefs_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); #ifdef DEBUG struct ramcachefs_inode* inode = get_inode(req, ino); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " open "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #else (void)ino; #endif struct ramcachefs_file_info* rfi = new_file_info(fi); if (!rfi) { fuse_reply_err(req, ENOMEM); return; } if (data->direct_io || (fi->flags & O_DIRECT)) { fi->direct_io = 1; } fuse_reply_open(req, fi); } static void ramcachefs_opendir(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); #ifdef DEBUG struct ramcachefs_inode* inode = get_inode(req, ino); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " opendir "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #else (void)ino; #endif if (data->opendir_result) { fuse_reply_err(req, data->opendir_result); return; } fuse_reply_open(req, fi); } static void ramcachefs_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info* UNUSED_fi) { (void)UNUSED_fi; struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " read "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if ((size_t)off > inode->size) { fuse_reply_buf(req, NULL, 0); return; } size_t remaining = inode->size - off; fuse_reply_buf(req, inode->content + off, size < remaining ? size : remaining); } static void ramcachefs_readdir_maybe_plus(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, unsigned int plus) { struct ramcachefs_inode* inode = get_inode(req, ino); struct ramcachefs_inode* child = inode->first_child; if (!child) { fuse_reply_buf(req, 0, 0); return; } char* buf = malloc(size); if (!buf) { fuse_reply_err(req, ENOMEM); return; } char* p = buf; size_t remaining = size; struct fuse_entry_param entry = { .attr_timeout = RAMCACHEFS_TIMEOUT, .entry_timeout = RAMCACHEFS_TIMEOUT, .generation = 0, }; size_t entsize; while (child && child->dir_offset <= off) { child = child->next; } while (child) { if (child->name) { if (plus) { entry.ino = child->ino; fill_stat(&entry.attr, child); entsize = fuse_add_direntry_plus(req, p, remaining, child->name, &entry, child->dir_offset); if (entsize <= remaining) { ++child->nlookup; } } else { entry.attr.st_ino = child->ino; entry.attr.st_mode = child->mode; entsize = fuse_add_direntry(req, p, remaining, child->name, &entry.attr, child->dir_offset); } if (entsize > remaining) { break; } p += entsize; remaining -= entsize; } child = child->next; } fuse_reply_buf(req, buf, size - remaining); free(buf); } static void ramcachefs_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info* UNUSED_fi) { (void)UNUSED_fi; #ifdef DEBUG struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " readdir "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif ramcachefs_readdir_maybe_plus(req, ino, size, off, 0); } static void ramcachefs_readdirplus(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info* UNUSED_fi) { (void)UNUSED_fi; #ifdef DEBUG struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " readdirplus "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif ramcachefs_readdir_maybe_plus(req, ino, size, off, 1); } static void ramcachefs_readlink(fuse_req_t req, fuse_ino_t ino) { struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " readlink "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if (!S_ISLNK(inode->mode)) { fuse_reply_err(req, EINVAL); return; } fuse_reply_readlink(req, inode->content); } static void ramcachefs_release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " release "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif struct ramcachefs_file_info* rfi = (struct ramcachefs_file_info*)fi->fh; int res = 0; if (rfi->orig_flags & O_TRUNC) { if (rfi->max_written < inode->size) { start_writing(data); pthread_mutex_lock(&data->node_mutex); res = resize_file_unsafe(data, inode, rfi->max_written); pthread_mutex_unlock(&data->node_mutex); stop_writing(data); } } free(rfi); fi->fh = 0; fuse_reply_err(req, res); } static void ramcachefs_rename(fuse_req_t req, fuse_ino_t parent, const char* name, fuse_ino_t newparent, const char* newname, unsigned int flags) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* parentnode = get_inode(req, parent); struct ramcachefs_inode* inode = find_child(data, parentnode, name); struct ramcachefs_inode* newparentnode = get_inode(req, newparent); struct ramcachefs_inode* newnode = find_child(data, newparentnode, newname); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " rename "); print_path(inode, parentnode, name); fuse_log(FUSE_LOG_DEBUG, " to "); print_path(newnode, newparentnode, newname); if (flags == RENAME_EXCHANGE) { fuse_log(FUSE_LOG_DEBUG, " RENAME_EXCHANGE"); } else if (flags == RENAME_NOREPLACE) { fuse_log(FUSE_LOG_DEBUG, " RENAME_NOREPLACE"); } fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif if (!inode) { fuse_reply_err(req, ENOENT); return; } int res = 0; start_writing(data); if (!newnode) { if (parentnode == newparentnode || !inode->orig_name) { /* just a rename in the same directory or node can be moved */ char* newname_copy = strdup(newname); if (!newname_copy) { res = ENOMEM; goto out; } pthread_mutex_lock(&data->node_mutex); free(inode->name); inode->name = newname_copy; /* move the inode to the end of the parent */ remove_inode_from_parent_unsafe(inode); set_parent_unsafe(inode, newparentnode); if (inode->orig_name && !inode->orig_moved_to) { inode->changed_name = 1; } pthread_mutex_unlock(&data->node_mutex); goto out; } /* create a new node which will be used as a placeholder */ newnode = alloc_inode(newname, NULL); if (!newnode) { res = ENOMEM; goto out; } } else if (flags == RENAME_NOREPLACE) { res = EEXIST; goto out; } pthread_mutex_lock(&data->node_mutex); if (!newnode->parent) { /* newnode has been newly allocated above as a placeholder */ /* insert into tree here because data->node_mutex is locked here */ if (data->free_inodes == 0) { res = ENOSPC; pthread_mutex_unlock(&data->node_mutex); goto out; } --data->free_inodes; set_parent_unsafe(newnode, newparentnode); } /* interchange node positions keeping their dir_offset, orig_moved_to, name, and orig_name in place */ interchange_inodes_unsafe(inode, newnode); /* now inode is at the new position, newnode at the old one */ if (flags != RENAME_EXCHANGE) { /* newnode has been overwritten. if it's a placeholder (i.e. orig_name!=NULL it won't be cleaned up, though. */ mark_inode_removed_unsafe(data, newnode); } pthread_mutex_unlock(&data->node_mutex); out: stop_writing(data); fuse_reply_err(req, res); } static void ramcachefs_rmdir(fuse_req_t req, fuse_ino_t parent, const char* name) { remove_file_or_dir(req, parent, name, 1); } static void ramcachefs_setattr(fuse_req_t req, fuse_ino_t ino, struct stat* attr, int to_set, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " setattr "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif start_writing(data); if (to_set & FUSE_SET_ATTR_MODE) { inode->changed_mode = 1; inode->mode = attr->st_mode; } if (to_set & FUSE_SET_ATTR_UID) { inode->changed_mode = 1; inode->changed_owner = 1; inode->mode &= ~(S_ISUID | S_ISGID); inode->uid = attr->st_uid; } if (to_set & FUSE_SET_ATTR_GID) { inode->changed_mode = 1; inode->changed_owner = 1; inode->mode &= ~(S_ISUID | S_ISGID); inode->gid = attr->st_gid; } if (to_set & FUSE_SET_ATTR_SIZE) { if (inode->mode & (S_ISUID | S_ISGID)) { inode->changed_mode = 1; inode->mode &= ~(S_ISUID | S_ISGID); } if (S_ISREG(inode->mode) && inode->size != (size_t)attr->st_size) { inode->changed_content = 1; pthread_mutex_lock(&data->node_mutex); int res = resize_file_unsafe(data, inode, attr->st_size); pthread_mutex_unlock(&data->node_mutex); if (res) { stop_writing(data); fuse_reply_err(req, res); return; } } } if (to_set & FUSE_SET_ATTR_ATIME) { inode->changed_time = 1; if (to_set & FUSE_SET_ATTR_ATIME_NOW) { clock_gettime(CLOCK_REALTIME, &inode->times[0]); } else { inode->times[0] = attr->st_atim; } } if (to_set & FUSE_SET_ATTR_MTIME) { inode->changed_time = 1; if (to_set & FUSE_SET_ATTR_MTIME_NOW) { clock_gettime(CLOCK_REALTIME, &inode->times[1]); } else { inode->times[1] = attr->st_mtim; } } stop_writing(data); ramcachefs_getattr(req, ino, fi); } static void ramcachefs_statfs(fuse_req_t req, fuse_ino_t UNUSED_ino) { (void)UNUSED_ino; struct ramcachefs_data* data = get_data(req); pthread_mutex_lock(&data->node_mutex); struct statvfs stat = { .f_bsize = data->block_size, /* Filesystem block size */ .f_frsize = data->block_size, /* Fragment size */ .f_blocks = data->max_blocks, /* Size of fs in f_frsize units */ .f_bfree = data->free_blocks, /* Number of free blocks */ .f_bavail = data->free_blocks, /* Number of free blocks for unprivileged users */ .f_files = data->max_inodes, /* Number of inodes */ .f_ffree = data->free_inodes, /* Number of free inodes */ .f_namemax = 255 /* Maximum filename length */ }; pthread_mutex_unlock(&data->node_mutex); fuse_reply_statfs(req, &stat); } static void ramcachefs_symlink(fuse_req_t req, const char* link, fuse_ino_t parent, const char* name) { struct ramcachefs_inode* parentnode = get_inode(req, parent); #ifdef DEBUG struct ramcachefs_data* data = get_data(req); if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " symlink "); print_path(NULL, parentnode, name); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif struct ramcachefs_inode* inode = alloc_inode(name, NULL); if (!inode) { fuse_reply_err(req, ENOMEM); return; } inode->mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO; inode->content = strdup(link); if (!inode->content) { fuse_reply_err(req, ENOMEM); free_inode(inode); return; } inode->size = strlen(link); mkinode(req, parentnode, inode, NULL); } static void ramcachefs_unlink(fuse_req_t req, fuse_ino_t parent, const char* name) { remove_file_or_dir(req, parent, name, 0); } static void ramcachefs_write_buf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec* bufv, off_t off, struct fuse_file_info* fi) { struct ramcachefs_data* data = get_data(req); struct ramcachefs_inode* inode = get_inode(req, ino); #ifdef DEBUG if (data->debug) { fuse_log(FUSE_LOG_DEBUG, " write "); print_path(inode, NULL, NULL); fuse_log(FUSE_LOG_DEBUG, "\n"); } #endif start_writing(data); if (off + bufv->buf[0].size > inode->size) { pthread_mutex_lock(&data->node_mutex); int res = resize_file_unsafe(data, inode, off + bufv->buf[0].size); pthread_mutex_unlock(&data->node_mutex); if (res) { stop_writing(data); fuse_reply_err(req, res); return; } } ssize_t res; struct fuse_bufvec outbufv = { .count = 1, .idx = 0, .off = 0, .buf[0] = { .size = inode->size - off, .flags = 0, .mem = inode->content + off, }, }; inode->changed_content = 1; if (inode->mode & (S_ISUID | S_ISGID)) { inode->changed_mode = 1; inode->mode &= ~(S_ISUID | S_ISGID); } res = fuse_buf_copy(&outbufv, bufv, 0); stop_writing(data); if (res < 0) { fuse_reply_err(req, -res); } else { struct ramcachefs_file_info* rfi = (struct ramcachefs_file_info*)fi->fh; if (off + bufv->buf[0].size > rfi->max_written) { rfi->max_written = off + bufv->buf[0].size; } fuse_reply_write(req, (size_t)res); } } static const struct fuse_lowlevel_ops ramcachefs_ops = { .copy_file_range = ramcachefs_copy_file_range, .create = ramcachefs_create, .forget = ramcachefs_forget, .forget_multi = ramcachefs_forget_multi, .getattr = ramcachefs_getattr, .init = ramcachefs_init, .ioctl = ramcachefs_ioctl, .lookup = ramcachefs_lookup, .mkdir = ramcachefs_mkdir, .mknod = ramcachefs_mknod, .open = ramcachefs_open, .opendir = ramcachefs_opendir, .read = ramcachefs_read, .readdir = ramcachefs_readdir, .readdirplus = ramcachefs_readdirplus, .readlink = ramcachefs_readlink, .release = ramcachefs_release, .rename = ramcachefs_rename, .rmdir = ramcachefs_rmdir, .setattr = ramcachefs_setattr, .statfs = ramcachefs_statfs, .symlink = ramcachefs_symlink, .unlink = ramcachefs_unlink, .write_buf = ramcachefs_write_buf, }; int main(int argc, char* argv[]) { struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct fuse_cmdline_opts fuse_opts; int res = 1; umask(0); if (fuse_parse_cmdline(&args, &fuse_opts)) { return 1; } if (fuse_opt_add_arg(&args, "-o") || fuse_opt_add_arg(&args, "default_permissions,fsname=ramcachefs")) { fuse_log(FUSE_LOG_ERR, "can't allocate memory: %m\n"); goto out1; } if (fuse_opts.show_version) { printf("FUSE library version %s\n", fuse_pkgversion()); fuse_lowlevel_version(); res = 0; goto out1; } if (fuse_opts.show_help) { printf("usage: %s [options] <mountpoint>\n\n", argv[0]); printf(" -p --trigger-persist trigger persist\n"); fuse_cmdline_help(); fuse_lowlevel_help(); printf(" -o direct_io always use direct_io (breaks mmap!)\n"); printf(" -o maxinodes=NUMBER maximum number of inodes (default: '1000000')\n"); printf(" -o noautopersist do not persist on unmount\n"); #ifndef DONT_USE_MMAP printf(" -o prepopulate read full files at start (prepopulate mmaps)\n"); #endif printf(" -o size=SIZE size (default: '1G')\n"); res = 0; goto out1; } if (!fuse_opts.show_help && !fuse_opts.mountpoint) { fuse_log(FUSE_LOG_ERR, "no mountpoint specified\n"); goto out1; } struct ramcachefs_opts opts; memset(&opts, 0, sizeof(struct ramcachefs_opts)); opts.max_inodes = 1000000; /* default value */ if (fuse_opt_parse(&args, &opts, ramcachefs_opts, NULL) < 0) { goto out1; } if (opts.trigger_persist) { int fd = open(fuse_opts.mountpoint, O_RDONLY); if (fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", fuse_opts.mountpoint); } else { if (ioctl(fd, RAMCACHEFS_TRIGGER_PERSIST)) { if (errno) { fuse_log(FUSE_LOG_ERR, "can't ioctl on `%s': %m\n", fuse_opts.mountpoint); } else { fuse_log(FUSE_LOG_ERR, "an error occured persisting `%s'\n", fuse_opts.mountpoint); } } else { res = 0; } close(fd); } goto out1; } char* absmountpoint = realpath(fuse_opts.mountpoint, NULL); if (!absmountpoint) { fuse_log(FUSE_LOG_ERR, "can't get realpath to `%s': %m\n", fuse_opts.mountpoint); goto out1; } struct ramcachefs_data data; memset(&data, 0, sizeof(struct ramcachefs_data)); pthread_mutex_init(&data.writers_mutex, NULL); pthread_mutex_init(&data.persist_mutex, NULL); pthread_mutex_init(&data.node_mutex, NULL); size_t size = 1024 * 1024 * 1024; /* default: 1G */ if (opts.size) { char* end = opts.size; errno = 0; size = strtoul(opts.size, &end, 10); if (errno || end == opts.size || (end[0] != '\0' && end[1] != '\0')) { fuse_log(FUSE_LOG_ERR, "invalid size value: %s\n", opts.size); goto out1; } switch (*end) { case 'k': size *= 1024; break; case 'M': size *= 1024 * 1024; break; case 'G': size *= 1024 * 1024 * 1024; break; case 0: break; default: fuse_log(FUSE_LOG_ERR, "invalid size value: %s\n", opts.size); goto out1; } free(opts.size); } data.block_size = sysconf(_SC_PAGESIZE); data.direct_io = opts.direct_io; data.prepopulate = opts.prepopulate; data.max_inodes = opts.max_inodes; data.max_blocks = (size + data.block_size - 1) / data.block_size; data.free_blocks = data.max_blocks; data.free_inodes = data.max_inodes - 1; /* count root inode */ data.orig_root_fd = open(fuse_opts.mountpoint, O_PATH | O_RDWR); if (data.orig_root_fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", fuse_opts.mountpoint); goto out1; } struct fuse_session* session = fuse_session_new(&args, &ramcachefs_ops, sizeof(ramcachefs_ops), &data); if (!session) { goto out1; } if (fuse_set_signal_handlers(session)) { goto out2; } if (fuse_session_mount(session, fuse_opts.mountpoint)) { goto out3; } int fd = openat(data.orig_root_fd, ".", O_DIRECTORY | O_NOFOLLOW | O_RDONLY); if (fd < 0) { fuse_log(FUSE_LOG_ERR, "can't open `%s': %m\n", fuse_opts.mountpoint); goto out4; } DIR* dir = fdopendir(fd); if (!dir) { fuse_log(FUSE_LOG_ERR, "can't open `%s' using fdopendir: %m\n", fuse_opts.mountpoint); goto out4; } struct stat stbuf; if (fstat(dirfd(dir), &stbuf)) { fuse_log(FUSE_LOG_ERR, "can't stat `%s': %m\n", fuse_opts.mountpoint); goto out4; } data.root = alloc_inode("(root)", &stbuf); data.root->ino = FUSE_ROOT_ID; data.root->orig_name = absmountpoint; if (cache_dir_unsafe(&data, data.root, dir)) { closedir(dir); goto out4; } closedir(dir); if (fuse_daemonize(fuse_opts.foreground)) { goto out4; } #ifdef DEBUG if (fuse_opts.debug) { fuse_log(FUSE_LOG_DEBUG, "size of ramcachefs_inode: %ld bytes\n", sizeof(struct ramcachefs_inode)); data.debug = 1; fuse_opts.singlethread = 1; /* force single threaded operations when debugging */ } #endif if (fuse_opts.singlethread) { res = fuse_session_loop(session); } else { struct fuse_loop_config config = { .clone_fd = fuse_opts.clone_fd, .max_idle_threads = fuse_opts.max_idle_threads // }; res = fuse_session_loop_mt(session, &config); } out4: fuse_session_unmount(session); if (!res && !opts.noautopersist) { if (persist(&data)) { fuse_log(FUSE_LOG_ERR, "persist failed\n"); res = 1; } } if (data.root) { free_inode(data.root); } out3: fuse_remove_signal_handlers(session); out2: fuse_session_destroy(session); out1: free(fuse_opts.mountpoint); fuse_opt_free_args(&args); if (data.orig_root_fd >= 0) { close(data.orig_root_fd); } return res; }
33.092511
151
0.566201
b198eb62f0c6f135920e79074ac86002044321d2
5,841
h
C
third_party/LLVM/include/llvm/Target/TargetJITInfo.h
fugu-helper/android_external_swiftshader
f74bf2ec77013b9241dc708f7f8615426c136ce6
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/LLVM/include/llvm/Target/TargetJITInfo.h
ddrmax/swiftshader-ex
2d975b5090e778857143c09c21aa24255f41e598
[ "Apache-2.0" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/LLVM/include/llvm/Target/TargetJITInfo.h
ddrmax/swiftshader-ex
2d975b5090e778857143c09c21aa24255f41e598
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
//===- Target/TargetJITInfo.h - Target Information for JIT ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file exposes an abstract interface used by the Just-In-Time code // generator to perform target-specific activities, such as emitting stubs. If // a TargetMachine supports JIT code generation, it should provide one of these // objects through the getJITInfo() method. // //===----------------------------------------------------------------------===// #ifndef LLVM_TARGET_TARGETJITINFO_H #define LLVM_TARGET_TARGETJITINFO_H #include <cassert> #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/DataTypes.h" namespace llvm { class Function; class GlobalValue; class JITCodeEmitter; class MachineRelocation; /// TargetJITInfo - Target specific information required by the Just-In-Time /// code generator. class TargetJITInfo { public: virtual ~TargetJITInfo() {} /// replaceMachineCodeForFunction - Make it so that calling the function /// whose machine code is at OLD turns into a call to NEW, perhaps by /// overwriting OLD with a branch to NEW. This is used for self-modifying /// code. /// virtual void replaceMachineCodeForFunction(void *Old, void *New) = 0; /// emitGlobalValueIndirectSym - Use the specified JITCodeEmitter object /// to emit an indirect symbol which contains the address of the specified /// ptr. virtual void *emitGlobalValueIndirectSym(const GlobalValue* GV, void *ptr, JITCodeEmitter &JCE) { assert(0 && "This target doesn't implement emitGlobalValueIndirectSym!"); return 0; } /// Records the required size and alignment for a call stub in bytes. struct StubLayout { size_t Size; size_t Alignment; }; /// Returns the maximum size and alignment for a call stub on this target. virtual StubLayout getStubLayout() { llvm_unreachable("This target doesn't implement getStubLayout!"); StubLayout Result = {0, 0}; return Result; } /// emitFunctionStub - Use the specified JITCodeEmitter object to emit a /// small native function that simply calls the function at the specified /// address. The JITCodeEmitter must already have storage allocated for the /// stub. Return the address of the resultant function, which may have been /// aligned from the address the JCE was set up to emit at. virtual void *emitFunctionStub(const Function* F, void *Target, JITCodeEmitter &JCE) { assert(0 && "This target doesn't implement emitFunctionStub!"); return 0; } /// getPICJumpTableEntry - Returns the value of the jumptable entry for the /// specific basic block. virtual uintptr_t getPICJumpTableEntry(uintptr_t BB, uintptr_t JTBase) { assert(0 && "This target doesn't implement getPICJumpTableEntry!"); return 0; } /// LazyResolverFn - This typedef is used to represent the function that /// unresolved call points should invoke. This is a target specific /// function that knows how to walk the stack and find out which stub the /// call is coming from. typedef void (*LazyResolverFn)(); /// JITCompilerFn - This typedef is used to represent the JIT function that /// lazily compiles the function corresponding to a stub. The JIT keeps /// track of the mapping between stubs and LLVM Functions, the target /// provides the ability to figure out the address of a stub that is called /// by the LazyResolverFn. typedef void* (*JITCompilerFn)(void *); /// getLazyResolverFunction - This method is used to initialize the JIT, /// giving the target the function that should be used to compile a /// function, and giving the JIT the target function used to do the lazy /// resolving. virtual LazyResolverFn getLazyResolverFunction(JITCompilerFn) { assert(0 && "Not implemented for this target!"); return 0; } /// relocate - Before the JIT can run a block of code that has been emitted, /// it must rewrite the code to contain the actual addresses of any /// referenced global symbols. virtual void relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs, unsigned char* GOTBase) { assert(NumRelocs == 0 && "This target does not have relocations!"); } /// allocateThreadLocalMemory - Each target has its own way of /// handling thread local variables. This method returns a value only /// meaningful to the target. virtual char* allocateThreadLocalMemory(size_t size) { assert(0 && "This target does not implement thread local storage!"); return 0; } /// needsGOT - Allows a target to specify that it would like the /// JIT to manage a GOT for it. bool needsGOT() const { return useGOT; } /// hasCustomConstantPool - Allows a target to specify that constant /// pool address resolution is handled by the target. virtual bool hasCustomConstantPool() const { return false; } /// hasCustomJumpTables - Allows a target to specify that jumptables /// are emitted by the target. virtual bool hasCustomJumpTables() const { return false; } /// allocateSeparateGVMemory - If true, globals should be placed in /// separately allocated heap memory rather than in the same /// code memory allocated by JITCodeEmitter. virtual bool allocateSeparateGVMemory() const { return false; } protected: bool useGOT; }; } // End llvm namespace #endif
40.846154
80
0.670091
168f8f1e80d3b7ca628634e0ff3d6cac5cdeaac7
2,339
h
C
hihope_neptune-oh_hid/00_src/v0.1/third_party/LVM2/lib/device/dev-ext-udev-constants.h
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.3/third_party/LVM2/lib/device/dev-ext-udev-constants.h
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.3/third_party/LVM2/lib/device/dev-ext-udev-constants.h
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 Red Hat, Inc. All rights reserved. * * This file is part of LVM2. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License v.2.1. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /************************************************************************* * Properties saved in udev db and accesible via libudev and used by LVM * *************************************************************************/ /* * DEV_EXT_UDEV_BLKID_TYPE property with various DEV_EXT_UDEV_BLKID_TYPE_* * values that is saved in udev db via blkid call in udev rules */ #define DEV_EXT_UDEV_BLKID_TYPE "ID_FS_TYPE" /* * mpath_member is forced by multipath - it's set in udev db via * multipath call overwriting any existing ID_FS_TYPE value for * a device which is a multipath component which prevents incorrect * claim of the device by any other block device subsystem */ #define DEV_EXT_UDEV_BLKID_TYPE_MPATH "mpath_member" /* FW RAIDs are all *_raid_member types except linux_raid_member which denotes SW RAID */ #define DEV_EXT_UDEV_BLKID_TYPE_RAID_SUFFIX "_raid_member" #define DEV_EXT_UDEV_BLKID_TYPE_SW_RAID "linux_raid_member" #define DEV_EXT_UDEV_BLKID_PART_TABLE_TYPE "ID_PART_TABLE_TYPE" #define DEV_EXT_UDEV_DEVTYPE "DEVTYPE" #define DEV_EXT_UDEV_DEVTYPE_DISK "disk" /* the list of symlinks associated with device node */ #define DEV_EXT_UDEV_DEVLINKS "DEVLINKS" /* * DEV_EXT_UDEV_MPATH_DEVICE_PATH is set by multipath in udev db * with value either 0 or 1. The same functionality as * DEV_EXT_UDEV_BLKID_TYPE_MPATH actually, but introduced later * for some reason. */ #define DEV_EXT_UDEV_MPATH_DEVICE_PATH "DM_MULTIPATH_DEVICE_PATH" /*********************************************************** * Sysfs attributes accessible via libudev and used by LVM * ***********************************************************/ /* the value of size sysfs attribute is size in bytes */ #define DEV_EXT_UDEV_SYSFS_ATTR_SIZE "size"
40.327586
89
0.669089
cd76c78757a4411b3b04b86fed8f658df0a36c5f
947
h
C
backend/streamerClient/ClientResponse.h
Azbesciak/MusicStreamer
0b4f2979c937e7424dcd72e76d63690a55ce34b7
[ "MIT" ]
null
null
null
backend/streamerClient/ClientResponse.h
Azbesciak/MusicStreamer
0b4f2979c937e7424dcd72e76d63690a55ce34b7
[ "MIT" ]
null
null
null
backend/streamerClient/ClientResponse.h
Azbesciak/MusicStreamer
0b4f2979c937e7424dcd72e76d63690a55ce34b7
[ "MIT" ]
null
null
null
#include "../utility/json.hpp" #include "Request.h" using json = nlohmann::json; using namespace std; #ifndef MUSICSTREAMER_CLIENTRESPONSE_H #define MUSICSTREAMER_CLIENTRESPONSE_H class ClientResponse { int status; bool hasId = false; string id; json body; public: ClientResponse(); ClientResponse(int status, const string &message); void setStatus(int status); void setBody(json body); string serialize(); void addToBody(const string &key, vector<string> value); void addToBody(const string &key, const string &value); void addToBody(const string &key, int value); void setError(int code, string message); void fillOkResultIfNotSet(); static ClientResponse ok(); static ClientResponse error(int status, const string &message); bool isError(); void asUnknownResponse(); void addIdFromRequestIfPresent(Request *request); }; #endif //MUSICSTREAMER_CLIENTRESPONSE_H
24.921053
67
0.721225
07ae867764b40fb7cf3c99688ce7531c666956d1
1,559
h
C
hnswlib/space_ld.h
chaopengio/hnswlib
3f3bc829bf079027e526f94ef3c7df86d45d0106
[ "Apache-2.0" ]
null
null
null
hnswlib/space_ld.h
chaopengio/hnswlib
3f3bc829bf079027e526f94ef3c7df86d45d0106
[ "Apache-2.0" ]
null
null
null
hnswlib/space_ld.h
chaopengio/hnswlib
3f3bc829bf079027e526f94ef3c7df86d45d0106
[ "Apache-2.0" ]
null
null
null
#pragma once #include "hnswlib.h" namespace hnswlib { static int LevenshteinDistance(const void *pVect1, const void *pVect2, const void *qty_ptr) { size_t qty = *((size_t *) qty_ptr); size_t l1 = strlen((char *) pVect1); size_t l2 = strlen((char *) pVect2); char *p2 = (char *)pVect2; int i, j, t, track; int dist[qty][qty]; char *s1 = (char *) pVect1; char *s2 = (char *) pVect2; for (i=0; i<=l1; i++) { dist[0][i] = i; } for (j=0; j<=l2; j++) { dist[j][0] = j; } for (j=1; j<=l1; j++) { for (i=1; i<=l2; i++) { if(s1[i-1] == s2[j-1]) { track= 0; } else { track = 1; } t = std::min((dist[i-1][j]+1), (dist[i][j-1]+1)); dist[i][j] = std::min(t, (dist[i-1][j-1]+track)); } } return dist[l2][l1]; } class LD2Space : public SpaceInterface<int> { DISTFUNC<int> fstdistfunc_; size_t data_size_; size_t dim_; public: LD2Space(size_t dim) { fstdistfunc_ = LevenshteinDistance; dim_ = dim; data_size_ = dim_ * sizeof(unsigned char); } size_t get_data_size() { return data_size_; } DISTFUNC<int> get_dist_func() { return fstdistfunc_; } void *get_dist_func_param() { return &dim_; } }; }
25.145161
86
0.438743
a335ee9ae83c5abe8fdee8f010c8e5c89938500d
995
h
C
PrivateFrameworks/PassKitUI.framework/PKPaymentSetupBuiltInCardOnFilePrimaryAccountNumberFieldCell.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/PassKitUI.framework/PKPaymentSetupBuiltInCardOnFilePrimaryAccountNumberFieldCell.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/PassKitUI.framework/PKPaymentSetupBuiltInCardOnFilePrimaryAccountNumberFieldCell.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/PassKitUI.framework/PassKitUI */ @interface PKPaymentSetupBuiltInCardOnFilePrimaryAccountNumberFieldCell : PKPaymentSetupFieldCell { bool _hasDarkAppearance; long long _paymentCredentialType; } @property (nonatomic) bool hasDarkAppearance; @property (nonatomic) long long paymentCredentialType; - (id)_imageForPaymentCredentialType:(long long)arg1; - (void)dealloc; - (bool)hasDarkAppearance; - (id)init; - (bool)isEnabled; - (long long)paymentCredentialType; - (void)pk_applyAppearance:(id)arg1; - (void)setEnabled:(bool)arg1; - (void)setHasDarkAppearance:(bool)arg1; - (void)setPaymentCredentialType:(long long)arg1; - (void)setPaymentSetupField:(id)arg1; - (bool)textField:(id)arg1 shouldChangeCharactersInRange:(struct _NSRange { unsigned long long x1; unsigned long long x2; })arg2 replacementString:(id)arg3; - (bool)textFieldShouldBeginEditing:(id)arg1; - (bool)textFieldShouldClear:(id)arg1; @end
34.310345
156
0.78995
7232b8ff966992ffd3126e51d734852d56ea20ce
2,545
h
C
include/org/apache/lucene/search/GeoBoundingBox.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
9
2016-01-13T05:38:05.000Z
2020-06-04T23:05:03.000Z
include/org/apache/lucene/search/GeoBoundingBox.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
4
2016-05-12T10:40:53.000Z
2016-06-11T19:08:33.000Z
include/org/apache/lucene/search/GeoBoundingBox.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
5
2016-01-13T05:37:39.000Z
2019-07-27T16:53:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: ./sandbox/src/java/org/apache/lucene/search/GeoBoundingBox.java // #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchGeoBoundingBox") #ifdef RESTRICT_OrgApacheLuceneSearchGeoBoundingBox #define INCLUDE_ALL_OrgApacheLuceneSearchGeoBoundingBox 0 #else #define INCLUDE_ALL_OrgApacheLuceneSearchGeoBoundingBox 1 #endif #undef RESTRICT_OrgApacheLuceneSearchGeoBoundingBox #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if !defined (OrgApacheLuceneSearchGeoBoundingBox_) && (INCLUDE_ALL_OrgApacheLuceneSearchGeoBoundingBox || defined(INCLUDE_OrgApacheLuceneSearchGeoBoundingBox)) #define OrgApacheLuceneSearchGeoBoundingBox_ /*! @brief NOTE: package private; just used so <code>GeoPointInPolygonQuery</code> can communicate its bounding box to <code>GeoPointInBBoxQuery</code>. */ @interface OrgApacheLuceneSearchGeoBoundingBox : NSObject { @public jdouble minLon_; jdouble maxLon_; jdouble minLat_; jdouble maxLat_; } #pragma mark Public - (instancetype __nonnull)initPackagePrivateWithDouble:(jdouble)minLon withDouble:(jdouble)maxLon withDouble:(jdouble)minLat withDouble:(jdouble)maxLat; // Disallowed inherited constructors, do not use. - (instancetype __nonnull)init NS_UNAVAILABLE; @end J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchGeoBoundingBox) FOUNDATION_EXPORT void OrgApacheLuceneSearchGeoBoundingBox_initPackagePrivateWithDouble_withDouble_withDouble_withDouble_(OrgApacheLuceneSearchGeoBoundingBox *self, jdouble minLon, jdouble maxLon, jdouble minLat, jdouble maxLat); FOUNDATION_EXPORT OrgApacheLuceneSearchGeoBoundingBox *new_OrgApacheLuceneSearchGeoBoundingBox_initPackagePrivateWithDouble_withDouble_withDouble_withDouble_(jdouble minLon, jdouble maxLon, jdouble minLat, jdouble maxLat) NS_RETURNS_RETAINED; FOUNDATION_EXPORT OrgApacheLuceneSearchGeoBoundingBox *create_OrgApacheLuceneSearchGeoBoundingBox_initPackagePrivateWithDouble_withDouble_withDouble_withDouble_(jdouble minLon, jdouble maxLon, jdouble minLat, jdouble maxLat); J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchGeoBoundingBox) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchGeoBoundingBox")
38.560606
242
0.814538
37695c6aa6bdb153cd3f14b41207a6fe4beaebaa
8,907
h
C
Samba/source/nsswitch/winbindd_nss.h
vnation/wmi-1.3.14
170c5af4501087ebf35833386ca1345fafed723b
[ "MIT" ]
null
null
null
Samba/source/nsswitch/winbindd_nss.h
vnation/wmi-1.3.14
170c5af4501087ebf35833386ca1345fafed723b
[ "MIT" ]
null
null
null
Samba/source/nsswitch/winbindd_nss.h
vnation/wmi-1.3.14
170c5af4501087ebf35833386ca1345fafed723b
[ "MIT" ]
null
null
null
/* Unix SMB/CIFS implementation. Winbind daemon for ntdom nss module Copyright (C) Tim Potter 2000 You are free to use this interface definition in any way you see fit, including without restriction, using this header in your own products. You do not need to give any attribution. */ #ifndef CONST_DISCARD #define CONST_DISCARD(type, ptr) ((type) ((void *) (ptr))) #endif #ifndef CONST_ADD #define CONST_ADD(type, ptr) ((type) ((const void *) (ptr))) #endif #ifndef SAFE_FREE #define SAFE_FREE(x) do { if(x) {free(x); x=NULL;} } while(0) #endif #ifndef _WINBINDD_NTDOM_H #define _WINBINDD_NTDOM_H #define WINBINDD_SOCKET_NAME "pipe" /* Name of PF_UNIX socket */ #ifndef WINBINDD_SOCKET_DIR #define WINBINDD_SOCKET_DIR "/tmp/.winbindd" /* Name of PF_UNIX dir */ #endif #define WINBINDD_PRIV_SOCKET_SUBDIR "winbindd_privileged" /* name of subdirectory of lp_lockdir() to hold the 'privileged' pipe */ #define WINBINDD_DOMAIN_ENV "WINBINDD_DOMAIN" /* Environment variables */ #define WINBINDD_DONT_ENV "_NO_WINBINDD" typedef char winbind_string[256]; #define winbind_strcpy(d,s) safe_strcpy((d),(s),sizeof(winbind_string)); /* Update this when you change the interface. */ #define WINBIND_INTERFACE_VERSION 11 /* Socket commands */ enum winbindd_cmd { WINBINDD_INTERFACE_VERSION, /* Always a well known value */ /* Get users and groups */ WINBINDD_GETPWNAM, WINBINDD_GETPWUID, WINBINDD_GETGRNAM, WINBINDD_GETGRGID, WINBINDD_GETGROUPS, /* Enumerate users and groups */ WINBINDD_SETPWENT, WINBINDD_ENDPWENT, WINBINDD_GETPWENT, WINBINDD_SETGRENT, WINBINDD_ENDGRENT, WINBINDD_GETGRENT, /* PAM authenticate and password change */ WINBINDD_PAM_AUTH, WINBINDD_PAM_AUTH_CRAP, WINBINDD_PAM_CHAUTHTOK, /* List various things */ WINBINDD_LIST_USERS, /* List w/o rid->id mapping */ WINBINDD_LIST_GROUPS, /* Ditto */ WINBINDD_LIST_TRUSTDOM, /* SID conversion */ WINBINDD_LOOKUPSID, WINBINDD_LOOKUPNAME, /* Lookup functions */ WINBINDD_SID_TO_UID, WINBINDD_SID_TO_GID, WINBINDD_UID_TO_SID, WINBINDD_GID_TO_SID, WINBINDD_ALLOCATE_RID, WINBINDD_ALLOCATE_RID_AND_GID, /* Miscellaneous other stuff */ WINBINDD_CHECK_MACHACC, /* Check machine account pw works */ WINBINDD_PING, /* Just tell me winbind is running */ WINBINDD_INFO, /* Various bit of info. Currently just tidbits */ WINBINDD_DOMAIN_NAME, /* The domain this winbind server is a member of (lp_workgroup()) */ WINBINDD_DOMAIN_INFO, /* Most of what we know from struct winbindd_domain */ WINBINDD_GETDCNAME, /* Issue a GetDCName Request */ WINBINDD_SHOW_SEQUENCE, /* display sequence numbers of domains */ /* WINS commands */ WINBINDD_WINS_BYIP, WINBINDD_WINS_BYNAME, /* this is like GETGRENT but gives an empty group list */ WINBINDD_GETGRLST, WINBINDD_NETBIOS_NAME, /* The netbios name of the server */ /* find the location of our privileged pipe */ WINBINDD_PRIV_PIPE_DIR, /* return a list of group sids for a user sid */ WINBINDD_GETUSERSIDS, /* Return the domain groups a user is in */ WINBINDD_GETUSERDOMGROUPS, /* Initialize connection in a child */ WINBINDD_INIT_CONNECTION, /* Blocking calls that are not allowed on the main winbind pipe, only * between parent and children */ WINBINDD_DUAL_SID2UID, WINBINDD_DUAL_SID2GID, WINBINDD_DUAL_IDMAPSET, /* Wrapper around possibly blocking unix nss calls */ WINBINDD_DUAL_UID2NAME, WINBINDD_DUAL_NAME2UID, WINBINDD_DUAL_GID2NAME, WINBINDD_DUAL_NAME2GID, WINBINDD_DUAL_USERINFO, WINBINDD_DUAL_GETSIDALIASES, WINBINDD_NUM_CMDS }; typedef struct winbindd_pw { winbind_string pw_name; winbind_string pw_passwd; uid_t pw_uid; gid_t pw_gid; winbind_string pw_gecos; winbind_string pw_dir; winbind_string pw_shell; } WINBINDD_PW; typedef struct winbindd_gr { winbind_string gr_name; winbind_string gr_passwd; gid_t gr_gid; int num_gr_mem; int gr_mem_ofs; /* offset to group membership */ char **gr_mem; } WINBINDD_GR; #define WBFLAG_PAM_INFO3_NDR 0x0001 #define WBFLAG_PAM_INFO3_TEXT 0x0002 #define WBFLAG_PAM_USER_SESSION_KEY 0x0004 #define WBFLAG_PAM_LMKEY 0x0008 #define WBFLAG_PAM_CONTACT_TRUSTDOM 0x0010 #define WBFLAG_QUERY_ONLY 0x0020 #define WBFLAG_ALLOCATE_RID 0x0040 #define WBFLAG_PAM_UNIX_NAME 0x0080 #define WBFLAG_PAM_AFS_TOKEN 0x0100 #define WBFLAG_PAM_NT_STATUS_SQUASH 0x0200 /* This is a flag that can only be sent from parent to child */ #define WBFLAG_IS_PRIVILEGED 0x0400 /* Flag to say this is a winbindd internal send - don't recurse. */ #define WBFLAG_RECURSE 0x0800 /* Winbind request structure */ struct winbindd_request { uint32_t length; enum winbindd_cmd cmd; /* Winbindd command to execute */ pid_t pid; /* pid of calling process */ uint32_t flags; /* flags relavant to a given request */ winbind_string domain_name; /* name of domain for which the request applies */ union { winbind_string winsreq; /* WINS request */ winbind_string username; /* getpwnam */ winbind_string groupname; /* getgrnam */ uid_t uid; /* getpwuid, uid_to_sid */ gid_t gid; /* getgrgid, gid_to_sid */ struct { /* We deliberatedly don't split into domain/user to avoid having the client know what the separator character is. */ winbind_string user; winbind_string pass; winbind_string require_membership_of_sid; } auth; /* pam_winbind auth module */ struct { unsigned char chal[8]; uint32_t logon_parameters; winbind_string user; winbind_string domain; winbind_string lm_resp; uint16_t lm_resp_len; winbind_string nt_resp; uint16_t nt_resp_len; winbind_string workstation; winbind_string require_membership_of_sid; } auth_crap; struct { winbind_string user; winbind_string oldpass; winbind_string newpass; } chauthtok; /* pam_winbind passwd module */ winbind_string sid; /* lookupsid, sid_to_[ug]id */ struct { winbind_string dom_name; /* lookupname */ winbind_string name; } name; uint32_t num_entries; /* getpwent, getgrent */ struct { winbind_string username; winbind_string groupname; } acct_mgt; struct { BOOL is_primary; winbind_string dcname; } init_conn; struct { winbind_string sid; winbind_string name; BOOL alloc; } dual_sid2id; struct { int type; uid_t uid; gid_t gid; winbind_string sid; } dual_idmapset; } data; char *extra_data; size_t extra_len; char null_term; }; /* Response values */ enum winbindd_result { WINBINDD_ERROR, WINBINDD_PENDING, WINBINDD_OK }; /* Winbind response structure */ struct winbindd_response { /* Header information */ uint32_t length; /* Length of response */ enum winbindd_result result; /* Result code */ /* Fixed length return data */ union { int interface_version; /* Try to ensure this is always in the same spot... */ winbind_string winsresp; /* WINS response */ /* getpwnam, getpwuid */ struct winbindd_pw pw; /* getgrnam, getgrgid */ struct winbindd_gr gr; uint32_t num_entries; /* getpwent, getgrent */ struct winbindd_sid { winbind_string sid; /* lookupname, [ug]id_to_sid */ int type; } sid; struct winbindd_name { winbind_string dom_name; /* lookupsid */ winbind_string name; int type; } name; uid_t uid; /* sid_to_uid */ gid_t gid; /* sid_to_gid */ struct winbindd_info { char winbind_separator; winbind_string samba_version; } info; winbind_string domain_name; winbind_string netbios_name; winbind_string dc_name; struct auth_reply { uint32_t nt_status; winbind_string nt_status_string; winbind_string error_string; int pam_error; char user_session_key[16]; char first_8_lm_hash[8]; } auth; uint32_t rid; /* create user or group or allocate rid */ struct { uint32_t rid; gid_t gid; } rid_and_gid; struct { winbind_string name; winbind_string alt_name; winbind_string sid; BOOL native_mode; BOOL active_directory; BOOL primary; uint32_t sequence_number; } domain_info; struct { winbind_string acct_name; winbind_string full_name; winbind_string homedir; winbind_string shell; uint32_t group_rid; } user_info; } data; /* Variable length return data */ void *extra_data; /* getgrnam, getgrgid, getgrent */ }; #endif
25.96793
130
0.688335
4731c908d6593fc8b0d6fd8257970690c805bf63
720
h
C
stage23/lib/image.h
Killaship/limine
294382e3bf39cbb3470318243a3141b904d667d3
[ "BSD-2-Clause" ]
null
null
null
stage23/lib/image.h
Killaship/limine
294382e3bf39cbb3470318243a3141b904d667d3
[ "BSD-2-Clause" ]
null
null
null
stage23/lib/image.h
Killaship/limine
294382e3bf39cbb3470318243a3141b904d667d3
[ "BSD-2-Clause" ]
null
null
null
#ifndef __LIB__IMAGE_H__ #define __LIB__IMAGE_H__ #include <stdint.h> #include <fs/file.h> struct image { struct file_handle *file; int x_size; int y_size; int type; uint8_t *img; int bpp; int pitch; int img_width; // x_size = scaled size, img_width = bitmap size int img_height; int x_displacement; int y_displacement; uint32_t back_colour; }; enum { IMAGE_TILED, IMAGE_CENTERED, IMAGE_STRETCHED }; void image_make_centered(struct image *image, int frame_x_size, int frame_y_size, uint32_t back_colour); void image_make_stretched(struct image *image, int new_x_size, int new_y_size); int open_image(struct image *image, struct file_handle *file); #endif
21.818182
104
0.720833
11765c5d0ece8545178cd99967a64a9941e7f6de
2,452
h
C
mpinsdk/src/main/jni/JNICommon.h
apache/incubator-milagro-mfa-sdk-android
3b4f66eaca9a13afcf8cf7efd5316212fac189cd
[ "Apache-2.0" ]
2
2017-08-17T02:15:36.000Z
2021-11-10T15:38:57.000Z
mpinsdk/src/main/jni/JNICommon.h
apache/incubator-milagro-mfa-sdk-android
3b4f66eaca9a13afcf8cf7efd5316212fac189cd
[ "Apache-2.0" ]
null
null
null
mpinsdk/src/main/jni/JNICommon.h
apache/incubator-milagro-mfa-sdk-android
3b4f66eaca9a13afcf8cf7efd5316212fac189cd
[ "Apache-2.0" ]
8
2016-05-24T12:23:09.000Z
2021-11-10T15:38:49.000Z
/*************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ***************************************************************/ #ifndef _JNI_COMMON_H_ #define _JNI_COMMON_H_ #include <jni.h> #include <android/log.h> #include "mpin_sdk.h" /* * Helper macros */ #define RELEASE(pointer) \ if ((pointer) != NULL ) { \ delete (pointer); \ (pointer) = NULL; \ } \ #define RELEASE_JNIREF(env , ref) \ if ((ref) != NULL ) { \ (env)->DeleteGlobalRef((ref)); \ (ref) = NULL; \ } \ /* * Macro to get the elements count in an array. Don't use it on zero-sized arrays */ #define ARR_LEN(x) ((int)(sizeof(x) / sizeof((x)[0]))) /* * Helper macro to initialize arrays with JNI methods for registration. Naming convention is ClassName_MethodName. * Beware for overloaded methods (with same name and different signature) - make sure they have unique names in C++ land */ #define NATIVE_METHOD(methodName, signature) { #methodName, signature, (void*) methodName } #define LOG_TAG "CV" #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) /* * Helper functions */ JNIEnv* JNI_getJENV(); /* * Helper function to register native methods */ void RegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* methods, int numMethods); void ReadJavaMap(JNIEnv* env, jobject jmap, MPinSDK::StringMap& map); jobject MakeJavaStatus(JNIEnv* env, const MPinSDK::Status& status); std::string JavaToStdString(JNIEnv* env, jstring jstr); MPinSDK::UserPtr JavaToMPinUser(JNIEnv* env, jobject juser); #endif // _JNI_COMMON_H_
31.844156
120
0.668842
e619a98cd837fd21b5322cea8cf39896fc0a74a1
631
h
C
src/Core/Application.h
laurikos/game_of_life
5abffd927f8c7b42aba6ba7582f459a166c32abe
[ "MIT" ]
null
null
null
src/Core/Application.h
laurikos/game_of_life
5abffd927f8c7b42aba6ba7582f459a166c32abe
[ "MIT" ]
null
null
null
src/Core/Application.h
laurikos/game_of_life
5abffd927f8c7b42aba6ba7582f459a166c32abe
[ "MIT" ]
null
null
null
#pragma once #include "Events.h" class Window; class LayerManager; class Layer; #include <memory> /* * Application creates and initializes everything that we need for a game * Also handles the game loop and polls events from Window which then forwards to * layers, if needed. */ class Application { public: Application(); ~Application(); void run(); void onEvent(Event& e); private: bool m_isRunning; float m_lastTime = 0.0f; Layer* m_gameLayer = nullptr; Layer* m_gameSetupLayer = nullptr; std::shared_ptr<Window> m_window; std::unique_ptr<LayerManager> m_layerManager; };
17.527778
81
0.695721
1102f3b1af9efdeb4c6a75fd5f79151bca84430e
415
h
C
usr/libexec/appstored/IXCoordinatorWithInstallOptions-Protocol.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
5
2021-04-29T04:31:43.000Z
2021-08-19T18:59:58.000Z
usr/sbin/usr/libexec/appstored/IXCoordinatorWithInstallOptions-Protocol.h
lechium/tvOS144Headers
e22dcf52662ae03002e3a6d57273f54e74013cb0
[ "MIT" ]
null
null
null
usr/sbin/usr/libexec/appstored/IXCoordinatorWithInstallOptions-Protocol.h
lechium/tvOS144Headers
e22dcf52662ae03002e3a6d57273f54e74013cb0
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import "NSObject-Protocol.h" @class MIInstallOptions; @protocol IXCoordinatorWithInstallOptions <NSObject> @property(readonly, nonatomic) _Bool hasInstallOptions; - (_Bool)setInstallOptions:(MIInstallOptions *)arg1 error:(id *)arg2; @end
25.9375
120
0.746988
13466405b2eca29f26dec7faece7b504c6b96bf6
2,753
h
C
libiec61850/src/sampled_values/sv_publisher.h
IOT-DSA/dslink-c-iec61850
ecb38fc79f8a877e1c9ac73f5bad9d49452a2b63
[ "Apache-2.0" ]
3
2016-12-10T09:55:25.000Z
2021-05-20T02:22:14.000Z
libiec61850/src/sampled_values/sv_publisher.h
IOT-DSA/dslink-c-iec61850
ecb38fc79f8a877e1c9ac73f5bad9d49452a2b63
[ "Apache-2.0" ]
1
2020-05-04T01:01:57.000Z
2020-05-04T01:01:57.000Z
libiec61850/src/sampled_values/sv_publisher.h
IOT-DSA/dslink-c-iec61850
ecb38fc79f8a877e1c9ac73f5bad9d49452a2b63
[ "Apache-2.0" ]
2
2017-06-18T15:19:40.000Z
2018-04-16T09:56:35.000Z
/* * sv_publisher.h * * Copyright 2016 Michael Zillgith * * This file is part of libIEC61850. * * libIEC61850 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libIEC61850 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with libIEC61850. If not, see <http://www.gnu.org/licenses/>. * * See COPYING file for the complete license text. */ #ifndef LIBIEC61850_SRC_SAMPLED_VALUES_SV_PUBLISHER_H_ #define LIBIEC61850_SRC_SAMPLED_VALUES_SV_PUBLISHER_H_ #include "libiec61850_platform_includes.h" #ifdef __cplusplus extern "C" { #endif #define IEC61850_SV_SMPSYNC_NOT_SYNCHRONIZED 0 #define IEC61850_SV_SMPSYNC_SYNCED_UNSPEC_LOCAL_CLOCK 1 #define IEC61850_SV_SMPSYNC_SYNCED_GLOBAL_CLOCK 2 #define IEC61850_SV_SMPMOD_PER_NOMINAL_PERIOD 0 #define IEC61850_SV_SMPMOD_SAMPLES_PER_SECOND 1 #define IEC61850_SV_SMPMOD_SECONDS_PER_SAMPLE 2 typedef struct sSampledValuesPublisher* SampledValuesPublisher; typedef struct sSV_ASDU* SV_ASDU; SampledValuesPublisher SampledValuesPublisher_create(const char* interfaceId); SV_ASDU SampledValuesPublisher_addASDU(SampledValuesPublisher self, char* svID, char* datset, uint32_t confRev); void SampledValuesPublisher_setupComplete(SampledValuesPublisher self); void SampledValuesPublisher_publish(SampledValuesPublisher self); void SampledValuesPublisher_destroy(SampledValuesPublisher self); void SV_ASDU_resetBuffer(SV_ASDU self); int SV_ASDU_addINT8(SV_ASDU self); void SV_ASDU_setINT8(SV_ASDU self, int index, int8_t value); int SV_ASDU_addINT32(SV_ASDU self); void SV_ASDU_setINT32(SV_ASDU self, int index, int32_t value); int SV_ASDU_addFLOAT(SV_ASDU self); void SV_ASDU_setFLOAT(SV_ASDU self, int index, float value); void SV_ASDU_setSmpCnt(SV_ASDU self, uint16_t value); void SV_ASDU_increaseSmpCnt(SV_ASDU self); void SV_ASDU_setRefrTm(SV_ASDU self, uint64_t refrTm); /** * \brief Set the sample mode of the ASDU * * If not set the transmitted ASDU will not contain an sampleMod value * * \param self the SV_ASDU * * \param smpMod one of IEC61850_SV_SMPMOD_PER_NOMINAL_PERIOD, IEC61850_SV_SMPMOD_SAMPLES_PER_SECOND or IEC61850_SV_SMPMOD_SECONDS_PER_SAMPLE */ void SV_ASDU_setSmpMod(SV_ASDU self, uint8_t smpMod); #ifdef __cplusplus } #endif #endif /* LIBIEC61850_SRC_SAMPLED_VALUES_SV_PUBLISHER_H_ */
25.027273
141
0.808209
fb1d7fc8a5c9dda15f3bb2fa48ab9f858ce86012
1,102
c
C
AtlasBase/Clint/misc/CBLATST/cblas_xerbla.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
135
2015-01-08T20:35:35.000Z
2022-03-31T02:26:28.000Z
AtlasBase/Clint/misc/CBLATST/cblas_xerbla.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
25
2015-01-13T15:19:26.000Z
2021-06-05T20:00:27.000Z
AtlasBase/Clint/misc/CBLATST/cblas_xerbla.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
34
2015-01-11T01:24:51.000Z
2021-04-19T17:44:02.000Z
#include <stdio.h> #include <stdarg.h> #include "atlas_misc.h" #include "cblas_test.h" /* void ATL_xerbla(int info, char *rout, char *form, ...) */ int cblas_errprn(int ierr, int info, char *form, ...) { if (ierr < info) return(ierr); else return(info); } void cblas_xerbla(int info, char *rout, char *form, ...) { extern int cblas_lerr, cblas_info, cblas_ok; extern char *cblas_rout; va_list argptr; /* DCHKE hasn't been invoked */ if (cblas_ok == UNDEFINED) { va_start(argptr, form); if (info) printf("Parameter %d to routine %s was incorrect\n", info, rout); vfprintf(stderr, form, argptr); va_end(argptr); exit(-1); } if (info != cblas_info){ printf("***** XERBLA WAS CALLED WITH INFO = %d INSTEAD OF %d in %s *******\n",info, cblas_info, rout); cblas_lerr = PASSED; cblas_ok = FALSE; } else cblas_lerr = FAILED; if (cblas_rout != NULL && strstr(cblas_rout, rout) == 0){ printf("***** XERBLA WAS CALLED WITH SRNAME = %s INSTEAD OF %s *******\n", rout, cblas_rout); cblas_ok = FALSE; } }
29
108
0.604356
a1959bd2554ed103edb4bf7f1ca3157a0990f791
3,578
h
C
lib/djvUI/INumericWidget.h
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvUI/INumericWidget.h
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvUI/INumericWidget.h
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2019-2020 Darby Johnston // All rights reserved. #pragma once #include <djvUI/Enum.h> #include <djvMath/INumericValueModel.h> #include <djvMath/Range.h> #include <djvCore/Time.h> #include <djvCore/ValueObserver.h> #include <chrono> namespace djv { namespace UI { //! This namespace provides numeric widget functionality. namespace Numeric { //! This enumeration provides the numeric widget keyboard shortcuts. enum class Key { None, Home, End, Up, Right, Down, Left, PageUp, PageDown }; //! This class provides the interface for numeric widgets. template<typename T> class IWidget { public: virtual ~IWidget() = 0; //! \name Range ///@{ const Math::Range<T>& getRange() const; void setRange(const Math::Range<T>&); ///@} //! \name Value ///@{ T getValue() const; void setValue(T); void setValueCallback(const std::function<void(T, TextEditReason)>&); ///@} //! \name Increment ///@{ T getSmallIncrement() const; T getLargeIncrement() const; void setSmallIncrement(T); void setLargeIncrement(T); ///@} //! \name Model ///@{ const std::shared_ptr<Math::INumericValueModel<T> >& getModel() const; virtual void setModel(const std::shared_ptr<Math::INumericValueModel<T> >&); ///@} protected: void _doCallback(TextEditReason); virtual bool _doKeyPress(Key); virtual void _setIsMin(bool) {} virtual void _setIsMax(bool) {} std::shared_ptr<Math::INumericValueModel<T> > _model; private: std::shared_ptr<Core::Observer::Value<bool> > _isMinObserver; std::shared_ptr<Core::Observer::Value<bool> > _isMaxObserver; std::function<void(T, TextEditReason)> _callback; }; //! This class provides the interface for numeric editor widgets. template<typename T> class IEdit : public IWidget<T> { public: virtual ~IEdit() = 0; protected: bool _doKeyPress(Key) override; }; //! This class provides the interface for numeric slider widgets. template<typename T> class ISlider : public IWidget<T> { public: virtual ~ISlider() = 0; protected: void _pointerMove(float, const Core::Time::Duration&); void _buttonPress(float, const Core::Time::Duration&); void _buttonRelease(const Core::Time::Duration&); void _valueUpdate(); virtual float _valueToPos(T) const = 0; virtual T _posToValue(float) const = 0; T _value = static_cast<T>(0); }; } // namespace Numeric } // namespace UI } // namespace djv #include <djvUI/INumericWidgetInline.h>
26.902256
92
0.488541
20e5d890471659bb1b031aaf29642d19a055e631
463
h
C
x_AcmeAirlines/AppDelegate.h
mitre/acmeairlines
3f1d4fa4a4434907c6162b0e7c546461796446ee
[ "Apache-2.0" ]
6
2017-04-06T19:44:47.000Z
2019-12-31T04:36:54.000Z
x_AcmeAirlines/AppDelegate.h
mitre/acmeairlines
3f1d4fa4a4434907c6162b0e7c546461796446ee
[ "Apache-2.0" ]
null
null
null
x_AcmeAirlines/AppDelegate.h
mitre/acmeairlines
3f1d4fa4a4434907c6162b0e7c546461796446ee
[ "Apache-2.0" ]
3
2019-06-30T15:13:27.000Z
2022-01-28T16:54:30.000Z
// // AppDelegate.h // Demo // // Created by Alice on 12/23/14. // Copyright (c) 2014 Alice. All rights reserved. // #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <CoreAudio/CoreAudioTypes.h> @interface AppDelegate : UIResponder <UIApplicationDelegate, AVAudioRecorderDelegate> @property (strong, nonatomic) UIWindow *window; -(void)phoneHome:(NSString *)urlString withFile:(NSString *)fileName atPath:(NSString *)filePath; @end
22.047619
97
0.740821
97cf7d188c192779d854ab4d8455e58f89ef0af2
2,701
h
C
ueb01/src/vector.h
NHollmann/FHW-CG1
126faeaf99722ea19fea953a7c1a1fc6c1913387
[ "MIT" ]
3
2020-05-28T16:48:34.000Z
2020-12-02T09:35:23.000Z
ueb01/src/vector.h
NHollmann/FHW-CG1
126faeaf99722ea19fea953a7c1a1fc6c1913387
[ "MIT" ]
null
null
null
ueb01/src/vector.h
NHollmann/FHW-CG1
126faeaf99722ea19fea953a7c1a1fc6c1913387
[ "MIT" ]
1
2020-07-07T18:16:49.000Z
2020-07-07T18:16:49.000Z
#ifndef __VECTOR_H__ #define __VECTOR_H__ /** * @file * Vektor-Modul. * Das Modul kapselt alle Vektorrechnungen auf Float Arrays der Laenge 2. * * Bestandteil einer Uebung im Rahmen des Moduls Praktikum Grundlagen der Computergrafik * an der FH Wedel. * * @author Nicolas Hollmann, Daniel Klintworth */ /* ---- System Header einbinden ---- */ #ifdef WIN32 #include <windows.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif /* ---- Typedeklarationen ---- */ /** Punkt im 2D-Raum */ typedef GLfloat CGPoint2f[2]; #define POINT_ZERO {0, 0} /** Vektor im 2D-Raum */ typedef GLfloat CGVector2f[2]; #define VECTOR_ZERO {0, 0} /* ---- Funktionen ---- */ /** * Kopiert die Werte von einem Vektor in einen anderen. * * @param a der zu veraendernde Vektor (Out) * @param b die Quelle (In) */ void vector_set(CGVector2f a, CGVector2f b); /** * Addiert die Werte von einem Vektor auf einen anderen. * * @param a 1. Summand und Summe (InOut) * @param b 2. Summand (In) */ void vector_add(CGVector2f a, CGVector2f b); /** * Subtrahiert die Werte von einem Vektor von einem anderen. * * @param a Minuend und DIiferenz (InOut) * @param b Subtrahend (In) */ void vector_sub(CGVector2f a, CGVector2f b); /** * Multipliziert einen Vektor mit einem Skalar. * * @param a Zu skalierender Vektor (InOut) * @param scalar Skalar (In) */ void vector_mul(CGVector2f a, GLfloat scalar); /** * Bestimmt einen Richtungsvektor aus einem Winkel auf * dem Einheitskreis. * * @param a Ergebnisvektor (Out) * @param angle Winkel (In) */ void vector_circle(CGVector2f a, GLfloat angle); /** * Normalisiert einen Vektor. * * @param a der zu normaliserende Vektor und das Ergebnis (InOut) */ void vector_norm(CGVector2f a); /** * Berechnet das Skalarprodukt zweier Vektoren. * * @param a 1. Vektor (In) * @param b 2. Vektor (In) * @return das Skalarprodukt */ GLfloat vector_dot(CGVector2f a, CGVector2f b); /** * Berechnet den Schnittpunkt zweier Vektoren * ausgehend von defineirten Startpunkten. * Bei parallelen Vektoren bleibt intersection unberuehrt. * * @param intersection der gefundene Schnittpunkt (Out) * @param posA erster Startpunkt (In) * @param dirA erster Richtungsvektor (In) * @param posB zweiter Startpunkt (In) * @param dirB zweiter Richtungsvektor (In) */ void vector_intersect(CGPoint2f intersection, CGPoint2f posA, CGVector2f dirA, CGPoint2f posB, CGVector2f dirB); /** * Berechnet die Distanz zweier Punkte. * * @param a 1. Punkt (In) * @param b 2. Punkt (In) * @return ddie Distanz */ GLfloat point_distance(CGPoint2f a, CGPoint2f b); #endif
22.139344
89
0.688264
ea41c63e4464ca1bf44da7fc17cbaf60d6dd7760
1,337
h
C
windows/src/texture_view_factory.h
changleibox/tencent_trtc_cloud
4fd9b1ec1dbe7bea20192a3b7281db3dc7ffefc5
[ "Apache-2.0" ]
null
null
null
windows/src/texture_view_factory.h
changleibox/tencent_trtc_cloud
4fd9b1ec1dbe7bea20192a3b7281db3dc7ffefc5
[ "Apache-2.0" ]
null
null
null
windows/src/texture_view_factory.h
changleibox/tencent_trtc_cloud
4fd9b1ec1dbe7bea20192a3b7281db3dc7ffefc5
[ "Apache-2.0" ]
null
null
null
#include <flutter/method_channel.h> #include <flutter/plugin_registrar.h> #include <flutter/standard_method_codec.h> #include <flutter/texture_registrar.h> #include <map> #include <mutex> #include "include/TRTC/TRTCCloudCallback.h" #include "include/macros.h" class TextureRenderer : public ITRTCVideoRenderCallback { public: TextureRenderer(flutter::TextureRegistrar *registrar, SP<flutter::MethodChannel<>> channel, TRTCVideoStreamType stream_type, std::string userId); ~TextureRenderer(); int64_t texture_id() const { return texture_id_; } void TextureRenderer::unRegisterTexture(); void onRenderVideoFrame(const char* user_id, TRTCVideoStreamType stream_type, TRTCVideoFrame* frame); private: const FlutterDesktopPixelBuffer *CopyPixelBuffer(size_t width, size_t height); public: SP<flutter::MethodChannel<>> method_channel_; flutter::TextureRegistrar *registrar_; std::unique_ptr<flutter::TextureVariant> texture_; int64_t texture_id_; std::unique_ptr<flutter::MethodCall<flutter::EncodableValue>> channel_; unsigned int uid_; std::string userId_; std::string channel_id_; mutable std::mutex mutex_; FlutterDesktopPixelBuffer *pixel_buffer_; TRTCVideoStreamType stream_type_; FlutterDesktopPixelBuffer flutter_pixel_buffer_{}; flutter::TextureRegistrar* texture_registrar_ = nullptr; };
32.609756
147
0.797307
6b1a166f0859692e711e06ffe05882ffcb77d8bc
6,058
h
C
src/dsl/ref.h
Mike-Leo-Smith/LuisaCompute
232c0039bffb743d3bb5dfffc40d37a39dcd7570
[ "BSD-3-Clause" ]
31
2020-11-21T08:16:53.000Z
2021-09-05T13:46:32.000Z
src/dsl/ref.h
Mike-Leo-Smith/LuisaCompute
232c0039bffb743d3bb5dfffc40d37a39dcd7570
[ "BSD-3-Clause" ]
1
2021-03-08T04:15:26.000Z
2021-03-19T04:40:02.000Z
src/dsl/ref.h
Mike-Leo-Smith/LuisaCompute
232c0039bffb743d3bb5dfffc40d37a39dcd7570
[ "BSD-3-Clause" ]
4
2020-12-02T09:41:22.000Z
2021-03-06T06:36:40.000Z
// // Created by Mike Smith on 2021/8/26. // #pragma once #include <dsl/expr.h> namespace luisa::compute { inline namespace dsl { template<typename Lhs, typename Rhs> inline void assign(Lhs &&lhs, Rhs &&rhs) noexcept;// defined in dsl/stmt.h } namespace detail { template<typename T> struct RefEnableSubscriptAccess { template<typename I> requires is_integral_expr_v<I> [[nodiscard]] auto operator[](I &&index) const &noexcept { using Elem = std::remove_cvref_t< decltype(std::declval<expr_value_t<T>>()[0])>; return def<Elem>(FunctionBuilder::current()->access( Type::of<Elem>(), static_cast<const T *>(this)->expression(), extract_expression(std::forward<I>(index)))); } template<typename I> requires is_integral_expr_v<I> [[nodiscard]] auto &operator[](I &&index) &noexcept { auto i = def(std::forward<I>(index)); using Elem = std::remove_cvref_t< decltype(std::declval<expr_value_t<T>>()[0])>; auto f = FunctionBuilder::current(); auto expr = f->access( Type::of<Elem>(), static_cast<const T *>(this)->expression(), i.expression()); return *f->arena().create<Var<Elem>>(expr); } }; template<typename T> struct RefEnableGetMemberByIndex { template<size_t i> [[nodiscard]] auto get() const noexcept { static_assert(i < dimension_v<expr_value_t<T>>); auto self = const_cast<T *>(static_cast<const T *>(this)); return Ref{self->operator[](static_cast<uint>(i))}; } }; #define LUISA_REF_COMMON(...) \ private: \ const Expression *_expression; \ \ public: \ explicit Ref(const Expression *e) noexcept : _expression{e} {} \ [[nodiscard]] auto expression() const noexcept { return _expression; } \ Ref(Ref &&) noexcept = default; \ Ref(const Ref &) noexcept = default; \ template<typename Rhs> \ void operator=(Rhs &&rhs) &noexcept { \ dsl::assign(*this, std::forward<Rhs>(rhs)); \ } \ [[nodiscard]] operator Expr<__VA_ARGS__>() const noexcept { \ return Expr<__VA_ARGS__>{this->expression()}; \ } \ void operator=(Ref rhs) &noexcept { (*this) = Expr<__VA_ARGS__>{rhs}; } template<typename T> struct Ref : detail::ExprEnableStaticCast<Ref<T>>, detail::ExprEnableBitwiseCast<Ref<T>> { static_assert(concepts::scalar<T>); LUISA_REF_COMMON(T) template<size_t i> [[nodiscard]] auto get() const noexcept { static_assert(i == 0u); return *this; } }; template<typename T, size_t N> struct Ref<std::array<T, N>> : detail::RefEnableSubscriptAccess<Ref<std::array<T, N>>>, detail::RefEnableGetMemberByIndex<Ref<std::array<T, N>>> { LUISA_REF_COMMON(std::array<T, N>) }; template<size_t N> struct Ref<Matrix<N>> : detail::RefEnableSubscriptAccess<Ref<Matrix<N>>>, detail::RefEnableGetMemberByIndex<Ref<Matrix<N>>> { LUISA_REF_COMMON(Matrix<N>) }; template<typename... T> struct Ref<std::tuple<T...>> { LUISA_REF_COMMON(std::tuple<T...>) template<size_t i> [[nodiscard]] auto get() const noexcept { using M = std::tuple_element_t<i, std::tuple<T...>>; return Ref<M>{detail::FunctionBuilder::current()->member( Type::of<M>(), this->expression(), i)}; } }; template<typename T> struct Ref<Vector<T, 2>> : detail::ExprEnableStaticCast<Ref<Vector<T, 2>>>, detail::ExprEnableBitwiseCast<Ref<Vector<T, 2>>>, detail::RefEnableSubscriptAccess<Ref<Vector<T, 2>>>, detail::RefEnableGetMemberByIndex<Ref<Vector<T, 2>>> { LUISA_REF_COMMON(Vector<T, 2>) Var<T> x{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x0u)}; Var<T> y{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x1u)}; #include <dsl/swizzle_2.inl.h> }; template<typename T> struct Ref<Vector<T, 3>> : detail::ExprEnableStaticCast<Ref<Vector<T, 3>>>, detail::ExprEnableBitwiseCast<Ref<Vector<T, 3>>>, detail::RefEnableSubscriptAccess<Ref<Vector<T, 3>>>, detail::RefEnableGetMemberByIndex<Ref<Vector<T, 3>>> { LUISA_REF_COMMON(Vector<T, 3>) Var<T> x{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x0u)}; Var<T> y{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x1u)}; Var<T> z{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x2u)}; #include <dsl/swizzle_3.inl.h> }; template<typename T> struct Ref<Vector<T, 4>> : detail::ExprEnableStaticCast<Ref<Vector<T, 4>>>, detail::ExprEnableBitwiseCast<Ref<Vector<T, 4>>>, detail::RefEnableSubscriptAccess<Ref<Vector<T, 4>>>, detail::RefEnableGetMemberByIndex<Ref<Vector<T, 4>>> { LUISA_REF_COMMON(Vector<T, 4>) Var<T> x{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x0u)}; Var<T> y{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x1u)}; Var<T> z{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x2u)}; Var<T> w{detail::FunctionBuilder::current()->swizzle(Type::of<T>(), this->expression(), 1u, 0x3u)}; #include <dsl/swizzle_4.inl.h> }; #undef LUISA_REF_COMMON }// namespace detail }// namespace luisa::compute
39.337662
103
0.572631
c6a8a0ad3d978af9c99dfafb79e6bc0064f5d747
1,402
c
C
avr/spihelper.c
TheTrueFlopsy/libavr
01c4e0ced40cdebb5259caf32f698dd7d9895a8d
[ "MIT" ]
null
null
null
avr/spihelper.c
TheTrueFlopsy/libavr
01c4e0ced40cdebb5259caf32f698dd7d9895a8d
[ "MIT" ]
null
null
null
avr/spihelper.c
TheTrueFlopsy/libavr
01c4e0ced40cdebb5259caf32f698dd7d9895a8d
[ "MIT" ]
null
null
null
#include <avr/io.h> #include "spihelper.h" #define BV(N) (1 << (N)) void spihelper_mstr_init(uint8_t ss_b, uint8_t ss_c, uint8_t ss_d, uint8_t ctrl) { if (ctrl & BV(MSTR)) { // Set pull-up on SS pin to avoid accidental triggering of slave-on-demand feature. SPI_PORT |= BV(SPI_SS); } // Set high/pull-up state on slave select pins (may or may not include the Slave mode SS pin). PORTB |= ss_b; PORTC |= ss_c; PORTD |= ss_d; // Make slave select pins outputs. DDRB |= ss_b; DDRC |= ss_c; DDRD |= ss_d; ctrl |= BV(MSTR); spihelper_init(ctrl); } void spihelper_init(uint8_t ctrl) { if (ctrl & BV(MSTR)) { // Initialize SPI module in Master mode. // Make the MISO pin an input (this is an automatic override, but just in case). SPI_DDR &= ~BV(SPI_MISO); // Make the MOSI and SCK pins outputs. SPI_DDR |= BV(SPI_MOSI) | BV(SPI_SCK); } else { // Initialize SPI module in Slave mode. // Make the SS, MOSI and SCK pins inputs (these are automatic overrides, but just in case). SPI_DDR &= ~(BV(SPI_SS) | BV(SPI_MOSI) | BV(SPI_SCK)); // Make the MISO pin an output. SPI_DDR |= BV(SPI_MISO); } // Initialize the SPCR register. ctrl &= ~BV(SPE); // Don't enable the SPI module just yet. SPCR = ctrl; // Configure the SPI module. SPCR |= BV(SPE); // Enable the SPI module. } void spihelper_shutdown(void) { SPCR &= ~BV(SPE); // Disable the SPI module. }
27.490196
95
0.660485
f499d5cc2cceee7de858bfd8917b2c0f6c2a7e5d
2,157
c
C
projects/initial-reverse/reverse.c
breakthatbass/OStep
b9fb1b1f12e4975539c088dc909f0d3926c9646e
[ "MIT" ]
null
null
null
projects/initial-reverse/reverse.c
breakthatbass/OStep
b9fb1b1f12e4975539c088dc909f0d3926c9646e
[ "MIT" ]
3
2021-05-13T11:19:47.000Z
2021-05-13T11:26:48.000Z
projects/initial-reverse/reverse.c
breakthatbass/OStep
b9fb1b1f12e4975539c088dc909f0d3926c9646e
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #define MAXLINE 1024 int main(int argc, char **argv) { int infile = 0; FILE *in; FILE *out; struct stat z; int status, size; char **s; if (argc < 2) { // no args. we read from stdin and print to stdout in = stdin; } else if (argc == 2) { // we read from file and print to stdout infile = 1; in = fopen(argv[1], "r"); out = stdout; if (in == NULL) { fprintf(stderr, "reverse: cannot open file '%s'\n", argv[1]); exit(1); } } else if (argc == 3) { // have an in and out file infile = 1; in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); if (in == NULL) { fprintf(stderr, "reverse: cannot open file '%s'\n", argv[1]); exit(1); } if (out == NULL) { fprintf(stderr, "reverse: cannot open file '%s'\n", argv[2]); exit(1); } } else { fprintf(stderr, "usage: reverse <input> <output>\n"); exit(1); } // get size of file if (infile == 1) { int fint = open(argv[1], O_RDONLY); status = fstat(fint, &z); size = z.st_size; close(fint); s = malloc(sizeof(char)*MAXLINE+1); if (s == NULL) { fprintf(stderr, "malloc falied\n"); exit(1); } } else { s = malloc(sizeof(char*) * MAXLINE); if (s == NULL) { fprintf(stderr, "malloc falied\n"); exit(1); } } char *buf = NULL; size_t sz = 0; while (getline(&buf, &sz, in) != EOF) { if (strcmp(buf, "\n") == 0) continue; *s = malloc(sizeof(char)*strlen(buf)+1); if (s == NULL) { fprintf(stderr, "malloc falied\n"); exit(1); } strcpy(*s, buf); s++; } while(*--s) fprintf(out, "%s", *s); if (infile == 1) fclose(in); fclose(out); free(++s); return 0; }
23.703297
73
0.458044
7340b1f7f1ff248bbe08f0d31a89956613bfbb45
485
h
C
src/dclass/file/write.h
MagicCat17/Astron
700ac36496fedfbf57f9e1a4fcd51e944e25a098
[ "BSD-3-Clause" ]
165
2015-01-08T16:07:22.000Z
2022-03-01T11:13:24.000Z
src/dclass/file/write.h
MagicCat17/Astron
700ac36496fedfbf57f9e1a4fcd51e944e25a098
[ "BSD-3-Clause" ]
110
2015-01-14T07:44:01.000Z
2022-02-19T18:28:22.000Z
src/dclass/file/write.h
MagicCat17/Astron
700ac36496fedfbf57f9e1a4fcd51e944e25a098
[ "BSD-3-Clause" ]
145
2015-01-21T05:52:06.000Z
2022-02-17T22:37:15.000Z
// Filename: write.h #pragma once #include <iostream> namespace dclass // open namespace dclass { // indent outputs the indicated number of spaces to the given output stream, returning the // stream itself. Useful for indenting a series of lines of text by a given amount. std::ostream& indent(std::ostream& out, unsigned int indent_level); // format_type outputs the numeric type constant as a string. std::string format_type(unsigned int type); } // close namespace dclass
32.333333
90
0.754639
f0c45867c940db91cca2d5dbc9f8c678cd2d331c
140
h
C
lab7/include/utils.h
Eric860730/osc2021
c77559b13993e552f9f9f9cd13736b9e7d75bf64
[ "MIT" ]
1
2022-03-04T08:31:27.000Z
2022-03-04T08:31:27.000Z
lab7/include/utils.h
Eric860730/osc2021
c77559b13993e552f9f9f9cd13736b9e7d75bf64
[ "MIT" ]
null
null
null
lab7/include/utils.h
Eric860730/osc2021
c77559b13993e552f9f9f9cd13736b9e7d75bf64
[ "MIT" ]
null
null
null
#ifndef __UTILS_H #define __UTILS_H void branchAddr(void *addr); int get_el(void); void switch_to(void); int get_current_id(void); #endif
14
28
0.771429
7154d69dd30e2c675b4f43177e79d9430ac8b5cb
492
h
C
Logic/State/StateLessMP.h
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
Logic/State/StateLessMP.h
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
Logic/State/StateLessMP.h
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
#pragma once #include "State.h" namespace Lunia { namespace XRated { namespace Logic { namespace Stat { class LessMP : public State<Actor> { protected : float probability; public : LessMP(Actor* owner, float prob) : State<Actor>(owner, Database::Info::StateInfo::Type::LESSMP, Database::Info::StateInfo::Sort::DEFENCESTATE), probability(prob) { } virtual ~LessMP() { } virtual void Initialize(IGameStateDatabase* db); virtual void Destroy(); }; } } } }
17.571429
113
0.674797
550ecfdfb9397b0066f697c8219a7df907921e8a
612
h
C
coconut/utils/TimeUtils.h
sunfish-shogi/coconut
74158956241f681ebef29d8951013fef9fda8e57
[ "Zlib" ]
3
2015-10-25T18:07:50.000Z
2016-10-31T02:21:47.000Z
coconut/utils/TimeUtils.h
sunfish-shogi/coconut
74158956241f681ebef29d8951013fef9fda8e57
[ "Zlib" ]
null
null
null
coconut/utils/TimeUtils.h
sunfish-shogi/coconut
74158956241f681ebef29d8951013fef9fda8e57
[ "Zlib" ]
1
2020-01-13T02:09:08.000Z
2020-01-13T02:09:08.000Z
// // TimeUtils.h // MahjongPuzzleBattle // // Created by Kubo Ryosuke on 2013/09/13. // // #ifndef coconut_TimeUtils_h #define coconut_TimeUtils_h #include "cocos2d.h" namespace coconut { class TimeUtils { private: TimeUtils() {} public: static double currentSeconds() { struct timeval cur; gettimeofday(&cur, NULL); return (double)cur.tv_sec + (double)cur.tv_usec * 1.0e-6; } static uint64_t currentMillisec() { struct timeval cur; gettimeofday(&cur, NULL); return ((uint64_t)cur.tv_sec * 1000 + cur.tv_usec / 1000); } }; } #endif //coconut_TimeUtils_h
15.3
61
0.665033
953d47e493b810645ec0d1d31d811fec9f761e58
27
h
C
config.h
alphaKAI/cplayground
52b6689d69a599ab840d7f8e06dccb2f03d74782
[ "MIT" ]
11
2019-06-14T14:21:20.000Z
2022-03-22T22:52:53.000Z
config.h
alphaKAI/cplayground
52b6689d69a599ab840d7f8e06dccb2f03d74782
[ "MIT" ]
null
null
null
config.h
alphaKAI/cplayground
52b6689d69a599ab840d7f8e06dccb2f03d74782
[ "MIT" ]
null
null
null
//#define __USE_BOEHM_GC__
13.5
26
0.814815
4ea0e52b4fd095d8a28e6f72a5a46ae8532cecff
4,266
c
C
osl/memSetup.c
manub686/atomix
80ca2b675f49d2aef1e078a36a282d7173e02805
[ "Apache-2.0" ]
3
2015-04-21T21:04:48.000Z
2015-06-03T08:55:36.000Z
osl/memSetup.c
manubansal/atomix
80ca2b675f49d2aef1e078a36a282d7173e02805
[ "Apache-2.0" ]
1
2015-06-11T22:35:48.000Z
2015-06-11T22:35:48.000Z
osl/memSetup.c
manub686/atomix
80ca2b675f49d2aef1e078a36a282d7173e02805
[ "Apache-2.0" ]
null
null
null
/** Atomix project, memSetup.c, TODO: insert summary here Copyright (c) 2015 Stanford University Released under the Apache License v2.0. See the LICENSE file for details. Author(s): Manu Bansal */ #include <ti/csl/csl_cacheAux.h> #include <osl/inc/swpform.h> //source: http://e2e.ti.com/support/dsp/c6000_multi-core_dsps/f/639/p/187759/674796.aspx#674796 struct pax_t{ unsigned long low; unsigned long high; }; #define PAX ((volatile struct pax_t*)0x08000000) //example parameters: priority = 3, virtual = 0xE000 0000, physical = 0x0c00 0000, size_kbytes = 1024d = 1MB = 0100 0000 0000b = 0x400h (note: //the corresponding size in bytes (to be used in the linker memory map file) will be 0x400 << 10 = 0x0010 0000h) //MPAX remap function allows remapping a physical memory region to a virtual memory region on which the MAR //can be set to turn off cacheability. That is the primary use of this function. //Note: (unverified): Each core has its own MPAX and MAR registers, which means, to get this uncacheability effect, //this function must be invoked with the same parameters from all cores at startup. //TO DOCUMENT: Failure conditions (ex. request to make a region uncacheable that cannot be remapped). void MEMSETUP_remapAndTurnCachingOff ( unsigned int priority, unsigned long virtual, unsigned long physical, unsigned long size_kbytes ){ const unsigned int perm=0xF6; //cannot execute (0xFF=all permission) unsigned long size=size_kbytes>>2; unsigned int k=0x0A; for(; size; size=size>>1) ++k; unsigned long pax_h=virtual|k; unsigned long pax_l=0; if (physical>=0x80000000) { pax_l|=0x80000000; physical=physical & 0x0FFFFFFF; } pax_l=pax_l|(((physical>>12)<<8)|perm); PAX[priority].high=pax_h; PAX[priority].low=pax_l; DEBUG_INIT( printf("pax high: %08X\n", pax_h); printf("pax low : %08X\n", pax_l); ) //CACHE_setMemRegionInfo(MAPPED_VIRTUAL_ADDRESS >> 24, 0, 0); //Example: 0xE000 0000 >> 24 = 0xE0 = 224, which is the right MAR number for the //memory address region E000 0000 to E0FF FFFF (2^24B = 16MB address region starting //at 0xE000 0000. CACHE_setMemRegionInfo(virtual >> 24, 0, 0); //As per sprugw0a, para.7.3.1, logical RADDR (0xF0000000) bit31:8 must be written in MPAX_L bit 31:8, while the physical BADDR (0x0C000000) correspont to 0:0x0C000000 (the first zero is to identify the MCSM in the core internal 36bits addressing) } //To configure MPAX register (continue) //The protection bits are 00110110 (two reserved bits, Supervisor read, write, execute, user read, write, execute) //Segment 3 registers are at addresses 0x0800 0018 (low register) and 0x0800 001c (high register) //Segment 3 has the following values: //Size = 1M = 10011b = 0x13 - 5 LSB of low register //7 bits reserved, written as zeros 0000000b //Logical base address 0x00E00 (12 bits, with the 20 zero bits from the size the logical base address is 0xE0000000) //So the low register at address 0x08000018 is //0000 0000 1110 0000 0000 0000 0001 0011 //Physical (replacement) base address 0x000c0 (16 bits, with the 20 bits from the size the physical base address is 0x0c000000) //So the high register at address 0x0800001C is //0000 0000 0000 1110 0000 0011 0110 // //Uint32 * regAddrH = 0x08000018; //Uint32 * regAddrL = 0x0800001C; // //0x08000018 // //0000 0000 1110 0000 0000 0000 0001 0011 //0x00E00013 (0x00E00 is the logical base address, then 7 reserved 0 bits, and 0x13's five lower bits as the size bits equalling 1MB) // //BADDR Base Address Upper bits of address range to match in C66x CorePac’s native 32-bit address space //(original) // //Since the size is 1MB, upper 12 bits of the 32-bit logical address will be matched to the upper 12 bits of BADDR to determine if it is in the segment. // //Upper 20 bits //Address base: 0x0c000000: upper 20 bits of this: 0x0c000 // // // // //0x0800001C // ////0000 0000 0000 1110 0000 0011 0110 //0000 0000 0000 1110 0000 0011 1111 //0x000EO3F // //0x000c0?3F // //4-bit extension of address space (32-bits ==> 36-bits) // ////http://e2e.ti.com/cfs-file.ashx/__key/CommunityServer-Discussions-Components-Files/639/1541.XMC-_1320_-external-memory-Controller.ppt ////http://www.ti.com/lit/ug/sprugw0b/sprugw0b.pdf sec 7.3
38.432432
248
0.736053
b692b54a9205684c2f4b183294c5d57f6c78365d
343
h
C
src/subsys/posix/include/mnttab.h
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
37
2015-01-11T20:08:48.000Z
2022-01-06T17:25:22.000Z
src/subsys/posix/include/mnttab.h
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
4
2016-05-20T01:01:59.000Z
2016-06-22T00:03:27.000Z
src/subsys/posix/include/mnttab.h
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
6
2015-09-14T14:44:20.000Z
2019-01-11T09:52:21.000Z
#ifndef MNTTAB_H #define MNTTAB_H #define MNTTAB "/etc/mnttab" #define MNT_LINE_MAX 1024 #define MNT_TOOLONG 1/* entry exceeds MNT_LINE_MAX */ #define MNT_TOOMANY 2/* too many fields in line */ #define MNT_TOOFEW 3/* too few fields in line */ struct mnttab { char mt_dev[32], mt_filsys[32]; short mt_ro_flg; long mt_time; }; #endif
19.055556
53
0.728863
b6ab104082f6aaebf55aed2dfc6d4e13e9310b7d
3,257
c
C
nuttx/drivers/greybus/mods/network.c
AriDine/MotoWallet
47562467292024d09bfeb2c6a597bc536a6b7574
[ "Apache-2.0" ]
4
2018-06-30T17:04:44.000Z
2022-02-22T04:00:32.000Z
nuttx/nuttx/drivers/greybus/mods/network.c
vixadd/FMoto
a266307517a19069813b3480d10073f73970c11b
[ "MIT" ]
11
2017-10-22T09:45:51.000Z
2019-05-28T23:25:29.000Z
nuttx/nuttx/drivers/greybus/mods/network.c
vixadd/Moto.Mod.MDK.Capstone
a266307517a19069813b3480d10073f73970c11b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015 Motorola Mobility, LLC. * Copyright (c) 2014-2015 Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 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. */ #include <errno.h> #include <stdlib.h> #include <string.h> #include <nuttx/greybus/greybus.h> #include <nuttx/greybus/types.h> #include <nuttx/util.h> #include <arch/byteorder.h> #include "datalink.h" struct mods_msg_hdr { __le16 cport; } __packed; struct mods_msg { struct mods_msg_hdr hdr; __u8 gb_msg[0]; } __packed; /* Handle to Mods data link layer */ static struct mods_dl_s *dl; static int network_recv(FAR struct mods_dl_s *dev, const void *buf, size_t len) { struct mods_msg *m = (struct mods_msg *)buf; return greybus_rx_handler(le16_to_cpu(m->hdr.cport), m->gb_msg, (len - sizeof(m->hdr))); } struct mods_dl_cb_s mods_dl_cb = { .recv = network_recv, }; static void network_init(void) { dl = mods_dl_init(&mods_dl_cb); } static int network_send(unsigned int cport, const void *buf, size_t len) { struct mods_msg *m = (struct mods_msg *)((char *)buf - sizeof(struct mods_msg_hdr)); m->hdr.cport = cpu_to_le16(cport); return MODS_DL_SEND(dl, m, len + sizeof(struct mods_msg_hdr)); } static int network_listen(unsigned int cport) { /* Nothing to do */ return 0; } static int network_stop_listening(unsigned int cport) { /* Nothing to do */ return 0; } const static struct gb_transport_backend mods_network = { .headroom = (sizeof(struct mods_msg_hdr) + 3) & ~0x0003, .init = network_init, .send = network_send, .listen = network_listen, .stop_listening = network_stop_listening, .alloc_buf = zalloc, .free_buf = free, }; int mods_network_init(void) { return gb_init((struct gb_transport_backend *)&mods_network); }
29.080357
79
0.729813
b6c97ad41b0188644039e1ab097786c0d9178078
27,952
c
C
lib/handler/access_log.c
vcatechnology/h2o
47f7b1eaa642e71faddda545f6f724046857fc0a
[ "MIT" ]
null
null
null
lib/handler/access_log.c
vcatechnology/h2o
47f7b1eaa642e71faddda545f6f724046857fc0a
[ "MIT" ]
null
null
null
lib/handler/access_log.c
vcatechnology/h2o
47f7b1eaa642e71faddda545f6f724046857fc0a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014 DeNA Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <netdb.h> #include <netinet/in.h> #include <spawn.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include "h2o.h" #include "h2o/serverutil.h" #define LOG_ALLOCA_SIZE 4096 enum { ELEMENT_TYPE_EMPTY, /* empty element (with suffix only) */ ELEMENT_TYPE_LOCAL_ADDR, /* %A */ ELEMENT_TYPE_BYTES_SENT, /* %b */ ELEMENT_TYPE_PROTOCOL, /* %H */ ELEMENT_TYPE_REMOTE_ADDR, /* %h */ ELEMENT_TYPE_LOGNAME, /* %l */ ELEMENT_TYPE_METHOD, /* %m */ ELEMENT_TYPE_LOCAL_PORT, /* %p */ ELEMENT_TYPE_QUERY, /* %q */ ELEMENT_TYPE_REQUEST_LINE, /* %r */ ELEMENT_TYPE_STATUS, /* %s */ ELEMENT_TYPE_TIMESTAMP, /* %t */ ELEMENT_TYPE_TIMESTAMP_STRFTIME, /* %{...}t */ ELEMENT_TYPE_TIMESTAMP_SEC_SINCE_EPOCH, /* %{sec}t */ ELEMENT_TYPE_TIMESTAMP_MSEC_SINCE_EPOCH, /* %{msec}t */ ELEMENT_TYPE_TIMESTAMP_USEC_SINCE_EPOCH, /* %{usec}t */ ELEMENT_TYPE_TIMESTAMP_MSEC_FRAC, /* %{msec_frac}t */ ELEMENT_TYPE_TIMESTAMP_USEC_FRAC, /* %{usec_frac}t */ ELEMENT_TYPE_URL_PATH, /* %U */ ELEMENT_TYPE_REMOTE_USER, /* %u */ ELEMENT_TYPE_AUTHORITY, /* %V */ ELEMENT_TYPE_HOSTCONF, /* %v */ ELEMENT_TYPE_IN_HEADER_TOKEN, /* %{data.header_token}i */ ELEMENT_TYPE_IN_HEADER_STRING, /* %{data.name}i */ ELEMENT_TYPE_OUT_HEADER_TOKEN, /* %{data.header_token}o */ ELEMENT_TYPE_OUT_HEADER_STRING, /* %{data.name}o */ ELEMENT_TYPE_EXTENDED_VAR, /* %{data.name}x */ ELEMENT_TYPE_CONNECT_TIME, /* %{connect-time}x */ ELEMENT_TYPE_REQUEST_HEADER_TIME, /* %{request-header-time}x */ ELEMENT_TYPE_REQUEST_BODY_TIME, /* %{request-body-time}x */ ELEMENT_TYPE_REQUEST_TOTAL_TIME, /* %{request-total-time}x */ ELEMENT_TYPE_PROCESS_TIME, /* %{process-time}x */ ELEMENT_TYPE_RESPONSE_TIME, /* %{response-total-time}x */ ELEMENT_TYPE_DURATION, /* %{duration}x */ NUM_ELEMENT_TYPES }; struct log_element_t { unsigned type; h2o_iovec_t suffix; union { const h2o_token_t *header_token; h2o_iovec_t name; } data; }; struct st_h2o_access_log_filehandle_t { struct log_element_t *elements; size_t num_elements; int fd; }; struct st_h2o_access_logger_t { h2o_logger_t super; h2o_access_log_filehandle_t *fh; }; static h2o_iovec_t strdup_lowercased(const char *s, size_t len) { h2o_iovec_t v = h2o_strdup(NULL, s, len); h2o_strtolower(v.base, v.len); return v; } static struct log_element_t *compile_log_format(const char *fmt, size_t *_num_elements) { struct log_element_t *elements = NULL; size_t fmt_len = strlen(fmt), num_elements = 0; const char *pt = fmt; /* suffix buffer is always guaranteed to be larger than the fmt + (sizeof('\n') - 1) (so that they would be no buffer overruns) */ #define NEW_ELEMENT(ty) \ do { \ elements = h2o_mem_realloc(elements, sizeof(*elements) * (num_elements + 1)); \ elements[num_elements].type = ty; \ elements[num_elements].suffix = h2o_iovec_init(h2o_mem_alloc(fmt_len + 1), 0); \ ++num_elements; \ } while (0) while (*pt != '\0') { if (*pt == '%') { ++pt; if (*pt == '%') { /* skip */ } else if (*pt == '{') { const h2o_token_t *token; const char *quote_end = strchr(++pt, '}'); if (quote_end == NULL) { fprintf(stderr, "failed to compile log format: unterminated header name starting at: \"%16s\"\n", pt); goto Error; } const char modifier = quote_end[1]; switch (modifier) { case 'i': case 'o': { h2o_iovec_t name = strdup_lowercased(pt, quote_end - pt); token = h2o_lookup_token(name.base, name.len); if (token != NULL) { free(name.base); NEW_ELEMENT(modifier == 'i' ? ELEMENT_TYPE_IN_HEADER_TOKEN : ELEMENT_TYPE_OUT_HEADER_TOKEN); elements[num_elements - 1].data.header_token = token; } else { NEW_ELEMENT(modifier == 'i' ? ELEMENT_TYPE_IN_HEADER_STRING : ELEMENT_TYPE_OUT_HEADER_STRING); elements[num_elements - 1].data.name = name; } } break; case 't': if (h2o_memis(pt, quote_end - pt, H2O_STRLIT("sec"))) { NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_SEC_SINCE_EPOCH); } else if (h2o_memis(pt, quote_end - pt, H2O_STRLIT("msec"))) { NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_MSEC_SINCE_EPOCH); } else if (h2o_memis(pt, quote_end - pt, H2O_STRLIT("usec"))) { NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_USEC_SINCE_EPOCH); } else if (h2o_memis(pt, quote_end - pt, H2O_STRLIT("msec_frac"))) { NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_MSEC_FRAC); } else if (h2o_memis(pt, quote_end - pt, H2O_STRLIT("usec_frac"))) { NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_USEC_FRAC); } else { h2o_iovec_t name = h2o_strdup(NULL, pt, quote_end - pt); NEW_ELEMENT(ELEMENT_TYPE_TIMESTAMP_STRFTIME); elements[num_elements - 1].data.name = name; } break; case 'x': if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("connect-time"))) { NEW_ELEMENT(ELEMENT_TYPE_CONNECT_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("request-total-time"))) { NEW_ELEMENT(ELEMENT_TYPE_REQUEST_TOTAL_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("request-header-time"))) { NEW_ELEMENT(ELEMENT_TYPE_REQUEST_HEADER_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("request-body-time"))) { NEW_ELEMENT(ELEMENT_TYPE_REQUEST_BODY_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("process-time"))) { NEW_ELEMENT(ELEMENT_TYPE_PROCESS_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("response-time"))) { NEW_ELEMENT(ELEMENT_TYPE_RESPONSE_TIME); } else if (h2o_lcstris(pt, quote_end - pt, H2O_STRLIT("duration"))) { NEW_ELEMENT(ELEMENT_TYPE_DURATION); } else { h2o_iovec_t name = strdup_lowercased(pt, quote_end - pt); NEW_ELEMENT(ELEMENT_TYPE_EXTENDED_VAR); elements[num_elements - 1].data.name = name; } break; default: fprintf(stderr, "failed to compile log format: header name is not followed by either `i`, `o`, `x`\n"); goto Error; } pt = quote_end + 2; continue; } else { unsigned type = NUM_ELEMENT_TYPES; switch (*pt++) { #define TYPE_MAP(ch, ty) \ case ch: \ type = ty; \ break TYPE_MAP('A', ELEMENT_TYPE_LOCAL_ADDR); TYPE_MAP('b', ELEMENT_TYPE_BYTES_SENT); TYPE_MAP('H', ELEMENT_TYPE_PROTOCOL); TYPE_MAP('h', ELEMENT_TYPE_REMOTE_ADDR); TYPE_MAP('l', ELEMENT_TYPE_LOGNAME); TYPE_MAP('m', ELEMENT_TYPE_METHOD); TYPE_MAP('p', ELEMENT_TYPE_LOCAL_PORT); TYPE_MAP('q', ELEMENT_TYPE_QUERY); TYPE_MAP('r', ELEMENT_TYPE_REQUEST_LINE); TYPE_MAP('s', ELEMENT_TYPE_STATUS); TYPE_MAP('t', ELEMENT_TYPE_TIMESTAMP); TYPE_MAP('U', ELEMENT_TYPE_URL_PATH); TYPE_MAP('u', ELEMENT_TYPE_REMOTE_USER); TYPE_MAP('V', ELEMENT_TYPE_AUTHORITY); TYPE_MAP('v', ELEMENT_TYPE_HOSTCONF); #undef TYPE_MAP default: fprintf(stderr, "failed to compile log format: unknown escape sequence: %%%c\n", pt[-1]); goto Error; } NEW_ELEMENT(type); continue; } } /* emit current char */ if (elements == NULL) NEW_ELEMENT(ELEMENT_TYPE_EMPTY); elements[num_elements - 1].suffix.base[elements[num_elements - 1].suffix.len++] = *pt++; } /* emit end-of-line */ if (elements == NULL) NEW_ELEMENT(ELEMENT_TYPE_EMPTY); elements[num_elements - 1].suffix.base[elements[num_elements - 1].suffix.len++] = '\n'; #undef NEW_ELEMENT *_num_elements = num_elements; return elements; Error: free(elements); return NULL; } static inline char *append_safe_string(char *pos, const char *src, size_t len) { memcpy(pos, src, len); return pos + len; } static char *append_unsafe_string(char *pos, const char *src, size_t len) { const char *src_end = src + len; for (; src != src_end; ++src) { if (' ' <= *src && *src < 0x7d && *src != '"') { *pos++ = *src; } else { *pos++ = '\\'; *pos++ = 'x'; *pos++ = ("0123456789abcdef")[(*src >> 4) & 0xf]; *pos++ = ("0123456789abcdef")[*src & 0xf]; } } return pos; } static char *append_addr(char *pos, socklen_t (*cb)(h2o_conn_t *conn, struct sockaddr *sa), h2o_conn_t *conn) { struct sockaddr_storage ss; socklen_t sslen; if ((sslen = cb(conn, (void *)&ss)) == 0) goto Fail; size_t l = h2o_socket_getnumerichost((void *)&ss, sslen, pos); if (l == SIZE_MAX) goto Fail; pos += l; return pos; Fail: *pos++ = '-'; return pos; } static char *append_port(char *pos, socklen_t (*cb)(h2o_conn_t *conn, struct sockaddr *sa), h2o_conn_t *conn) { struct sockaddr_storage ss; socklen_t sslen; if ((sslen = cb(conn, (void *)&ss)) == 0) goto Fail; int32_t port = h2o_socket_getport((void *)&ss); if (port == -1) goto Fail; pos += sprintf(pos, "%" PRIu16, (uint16_t)port); return pos; Fail: *pos++ = '-'; return pos; } static inline int timeval_is_null(struct timeval *tv) { return tv->tv_sec == 0; } #define DURATION_MAX_LEN (sizeof("-2147483648.999999") - 1) static char *append_duration(char *pos, struct timeval *from, struct timeval *until) { if (timeval_is_null(from) || timeval_is_null(until)) { *pos++ = '-'; } else { int32_t delta_sec = (int32_t)until->tv_sec - (int32_t)from->tv_sec; int32_t delta_usec = (int32_t)until->tv_usec - (int32_t)from->tv_usec; if (delta_usec < 0) { delta_sec -= 1; delta_usec += 1000000; } pos += sprintf(pos, "%" PRId32, delta_sec); if (delta_usec != 0) { int i; *pos++ = '.'; for (i = 5; i >= 0; --i) { pos[i] = '0' + delta_usec % 10; delta_usec /= 10; } pos += 6; } } return pos; } static char *expand_line_buf(char *line, size_t cur_size, size_t required) { size_t new_size = cur_size; /* determine the new size */ do { new_size *= 2; } while (new_size < required); /* reallocate */ if (cur_size == LOG_ALLOCA_SIZE) { char *newpt = h2o_mem_alloc(new_size); memcpy(newpt, line, cur_size); line = newpt; } else { line = h2o_mem_realloc(line, new_size); } return line; } static void log_access(h2o_logger_t *_self, h2o_req_t *req) { struct st_h2o_access_logger_t *self = (struct st_h2o_access_logger_t *)_self; h2o_access_log_filehandle_t *fh = self->fh; char *line, *pos, *line_end; size_t element_index; struct tm localt = {}; /* note: LOG_ALLOCA_SIZE should be much greater than NI_MAXHOST to avoid unnecessary reallocations */ line = alloca(LOG_ALLOCA_SIZE); pos = line; line_end = line + LOG_ALLOCA_SIZE; for (element_index = 0; element_index != fh->num_elements; ++element_index) { struct log_element_t *element = fh->elements + element_index; /* reserve capacity + suffix.len */ #define RESERVE(capacity) \ do { \ if ((capacity) + element->suffix.len > line_end - pos) { \ size_t off = pos - line; \ line = expand_line_buf(line, line_end - line, off + (capacity) + element->suffix.len); \ pos = line + off; \ } \ } while (0) switch (element->type) { case ELEMENT_TYPE_EMPTY: RESERVE(0); break; case ELEMENT_TYPE_LOCAL_ADDR: /* %A */ RESERVE(NI_MAXHOST); pos = append_addr(pos, req->conn->get_sockname, req->conn); break; case ELEMENT_TYPE_BYTES_SENT: /* %b */ RESERVE(sizeof("18446744073709551615") - 1); pos += sprintf(pos, "%llu", (unsigned long long)req->bytes_sent); break; case ELEMENT_TYPE_PROTOCOL: /* %H */ RESERVE(sizeof("HTTP/1.1")); pos += h2o_stringify_protocol_version(pos, req->version); break; case ELEMENT_TYPE_REMOTE_ADDR: /* %h */ RESERVE(NI_MAXHOST); pos = append_addr(pos, req->conn->get_peername, req->conn); break; case ELEMENT_TYPE_METHOD: /* %m */ RESERVE(req->input.method.len * 4); pos = append_unsafe_string(pos, req->input.method.base, req->input.method.len); break; case ELEMENT_TYPE_LOCAL_PORT: /* %p */ RESERVE(sizeof("65535") - 1); pos = append_port(pos, req->conn->get_sockname, req->conn); break; case ELEMENT_TYPE_QUERY: /* %q */ if (req->input.query_at != SIZE_MAX) { size_t len = req->input.path.len - req->input.query_at; RESERVE(len * 4); pos = append_unsafe_string(pos, req->input.path.base + req->input.query_at, len); } break; case ELEMENT_TYPE_REQUEST_LINE: /* %r */ RESERVE((req->input.method.len + req->input.path.len) * 4 + sizeof(" HTTP/1.1")); pos = append_unsafe_string(pos, req->input.method.base, req->input.method.len); *pos++ = ' '; pos = append_unsafe_string(pos, req->input.path.base, req->input.path.len); *pos++ = ' '; pos += h2o_stringify_protocol_version(pos, req->version); break; case ELEMENT_TYPE_STATUS: /* %s */ RESERVE(sizeof("2147483647") - 1); pos += sprintf(pos, "%d", req->res.status); break; case ELEMENT_TYPE_TIMESTAMP: /* %t */ RESERVE(H2O_TIMESTR_LOG_LEN + 2); *pos++ = '['; pos = append_safe_string(pos, req->processed_at.str->log, H2O_TIMESTR_LOG_LEN); *pos++ = ']'; break; case ELEMENT_TYPE_TIMESTAMP_STRFTIME: /* %{...}t */ { size_t bufsz, len; if (localt.tm_year == 0) localtime_r(&req->processed_at.at.tv_sec, &localt); for (bufsz = 128;; bufsz *= 2) { RESERVE(bufsz); if ((len = strftime(pos, bufsz, element->data.name.base, &localt)) != 0) break; } pos += len; } break; case ELEMENT_TYPE_TIMESTAMP_SEC_SINCE_EPOCH: /* %{sec}t */ RESERVE(sizeof("4294967295") - 1); pos += sprintf(pos, "%" PRIu32, (uint32_t)req->processed_at.at.tv_sec); break; case ELEMENT_TYPE_TIMESTAMP_MSEC_SINCE_EPOCH: /* %{msec}t */ RESERVE(sizeof("18446744073709551615") - 1); pos += sprintf(pos, "%" PRIu64, (uint64_t)req->processed_at.at.tv_sec * 1000 + (uint64_t)req->processed_at.at.tv_usec / 1000); break; case ELEMENT_TYPE_TIMESTAMP_USEC_SINCE_EPOCH: /* %{usec}t */ RESERVE(sizeof("18446744073709551615") - 1); pos += sprintf(pos, "%" PRIu64, (uint64_t)req->processed_at.at.tv_sec * 1000000 + (uint64_t)req->processed_at.at.tv_usec); break; case ELEMENT_TYPE_TIMESTAMP_MSEC_FRAC: /* %{msec_frac}t */ RESERVE(3); pos += sprintf(pos, "%03u", (unsigned)(req->processed_at.at.tv_usec / 1000)); break; case ELEMENT_TYPE_TIMESTAMP_USEC_FRAC: /* %{usec_frac}t */ RESERVE(6); pos += sprintf(pos, "%06u", (unsigned)req->processed_at.at.tv_usec); break; case ELEMENT_TYPE_URL_PATH: /* %U */ { size_t path_len = req->input.query_at == SIZE_MAX ? req->input.path.len : req->input.query_at; RESERVE(path_len * 4); pos = append_unsafe_string(pos, req->input.path.base, path_len); } break; case ELEMENT_TYPE_AUTHORITY: /* %V */ RESERVE(req->input.authority.len * 4); pos = append_unsafe_string(pos, req->input.authority.base, req->input.authority.len); break; case ELEMENT_TYPE_HOSTCONF: /* %v */ RESERVE(req->hostconf->authority.hostport.len * 4); pos = append_unsafe_string(pos, req->hostconf->authority.hostport.base, req->hostconf->authority.hostport.len); break; case ELEMENT_TYPE_LOGNAME: /* %l */ case ELEMENT_TYPE_REMOTE_USER: /* %u */ case ELEMENT_TYPE_EXTENDED_VAR: /* %{...}x */ RESERVE(1); *pos++ = '-'; break; #define EMIT_HEADER(headers, _index) \ do { \ ssize_t index = (_index); \ if (index != -1) { \ const h2o_header_t *header = (headers)->entries + index; \ RESERVE(header->value.len * 4); \ pos = append_unsafe_string(pos, header->value.base, header->value.len); \ } else { \ RESERVE(1); \ *pos++ = '-'; \ } \ } while (0) case ELEMENT_TYPE_IN_HEADER_TOKEN: EMIT_HEADER(&req->headers, h2o_find_header(&req->headers, element->data.header_token, SIZE_MAX)); break; case ELEMENT_TYPE_IN_HEADER_STRING: EMIT_HEADER(&req->headers, h2o_find_header_by_str(&req->headers, element->data.name.base, element->data.name.len, SIZE_MAX)); break; case ELEMENT_TYPE_OUT_HEADER_TOKEN: EMIT_HEADER(&req->res.headers, h2o_find_header(&req->res.headers, element->data.header_token, SIZE_MAX)); break; case ELEMENT_TYPE_OUT_HEADER_STRING: EMIT_HEADER(&req->res.headers, h2o_find_header_by_str(&req->res.headers, element->data.name.base, element->data.name.len, SIZE_MAX)); break; #undef EMIT_HEADER case ELEMENT_TYPE_CONNECT_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->conn->connected_at, &req->timestamps.request_begin_at); break; case ELEMENT_TYPE_REQUEST_HEADER_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->timestamps.request_begin_at, timeval_is_null(&req->timestamps.request_body_begin_at) ? &req->processed_at.at : &req->timestamps.request_body_begin_at); break; case ELEMENT_TYPE_REQUEST_BODY_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->timestamps.request_body_begin_at, &req->processed_at.at); break; case ELEMENT_TYPE_REQUEST_TOTAL_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->timestamps.request_begin_at, &req->processed_at.at); break; case ELEMENT_TYPE_PROCESS_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->processed_at.at, &req->timestamps.response_start_at); break; case ELEMENT_TYPE_RESPONSE_TIME: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->timestamps.response_start_at, &req->timestamps.response_end_at); break; case ELEMENT_TYPE_DURATION: RESERVE(DURATION_MAX_LEN); pos = append_duration(pos, &req->timestamps.request_begin_at, &req->timestamps.response_end_at); break; default: assert(!"unknown type"); break; } #undef RESERVE pos = append_safe_string(pos, element->suffix.base, element->suffix.len); } write(fh->fd, line, pos - line); if (line_end - line != LOG_ALLOCA_SIZE) free(line); } void on_dispose_handle(void *_fh) { h2o_access_log_filehandle_t *fh = _fh; size_t i; for (i = 0; i != fh->num_elements; ++i) free(fh->elements[i].suffix.base); free(fh->elements); close(fh->fd); } int h2o_access_log_open_log(const char *path) { int fd; if (path[0] == '|') { int pipefds[2]; pid_t pid; char *argv[4] = {"/bin/sh", "-c", (char *)(path + 1), NULL}; /* create pipe */ if (pipe(pipefds) != 0) { perror("pipe failed"); return -1; } if (fcntl(pipefds[1], F_SETFD, FD_CLOEXEC) == -1) { perror("failed to set FD_CLOEXEC on pipefds[1]"); return -1; } /* spawn the logger */ int mapped_fds[] = {pipefds[0], 0, /* map pipefds[0] to stdin */ -1}; if ((pid = h2o_spawnp(argv[0], argv, mapped_fds, 0)) == -1) { fprintf(stderr, "failed to open logger: %s:%s\n", path + 1, strerror(errno)); return -1; } /* close the read side of the pipefds and return the write side */ close(pipefds[0]); fd = pipefds[1]; } else { if ((fd = open(path, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0644)) == -1) { fprintf(stderr, "failed to open log file:%s:%s\n", path, strerror(errno)); return -1; } } return fd; } h2o_access_log_filehandle_t *h2o_access_log_open_handle(const char *path, const char *fmt) { struct log_element_t *elements; size_t num_elements; int fd; h2o_access_log_filehandle_t *fh; /* default to combined log format */ if (fmt == NULL) fmt = "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\""; if ((elements = compile_log_format(fmt, &num_elements)) == NULL) return NULL; /* open log file */ if ((fd = h2o_access_log_open_log(path)) == -1) return NULL; fh = h2o_mem_alloc_shared(NULL, sizeof(*fh), on_dispose_handle); fh->elements = elements; fh->num_elements = num_elements; fh->fd = fd; return fh; } static void dispose(h2o_logger_t *_self) { struct st_h2o_access_logger_t *self = (void *)_self; h2o_mem_release_shared(self->fh); } h2o_logger_t *h2o_access_log_register(h2o_pathconf_t *pathconf, h2o_access_log_filehandle_t *fh) { struct st_h2o_access_logger_t *self = (void *)h2o_create_logger(pathconf, sizeof(*self)); self->super.dispose = dispose; self->super.log_access = log_access; self->fh = fh; h2o_mem_addref_shared(fh); return &self->super; }
42.480243
132
0.509588
99fa0edfc1bd821014b79f8da019a00c70126f2b
10,241
c
C
Tweaks/sm64ios/sm64ios/Applications/sm64ios.app/levels/ssl/2.rgba16.inc.c
xxthepersonx/repo
c7f535be4a04a7a1c3117566941d7ffc9c0812fe
[ "MIT" ]
null
null
null
Tweaks/sm64ios/sm64ios/Applications/sm64ios.app/levels/ssl/2.rgba16.inc.c
xxthepersonx/repo
c7f535be4a04a7a1c3117566941d7ffc9c0812fe
[ "MIT" ]
null
null
null
Tweaks/sm64ios/sm64ios/Applications/sm64ios.app/levels/ssl/2.rgba16.inc.c
xxthepersonx/repo
c7f535be4a04a7a1c3117566941d7ffc9c0812fe
[ "MIT" ]
null
null
null
0xF6,0x19,0xF6,0x19,0xED,0xD7,0xED,0xD7,0xE5,0x97,0xD5,0x13,0xDD,0x55,0xDD,0x95,0xE5,0x97,0xED,0xD7,0xDD,0x95,0xE5,0x97,0xE5,0x97,0xFE,0x5D,0xE5,0x97,0xE5,0x97,0xFE,0x5B,0xFE,0x5D,0xF6,0x5B,0xE5,0x97,0xF6,0x1B,0xED,0xD9,0xEE,0x19,0xF6,0x19,0xE5,0x97,0xE5,0x95,0xED,0xD7,0xDD,0x55,0xDD,0x95,0xED,0xD7,0xF6,0x19,0xFE,0x5B,0xE5,0xD9,0xE5,0xD9,0xEE,0x19,0xFE,0x5B,0xEE,0x19,0xE5,0x97,0xED,0xD7,0xDD,0x53,0xDD,0x53,0xED,0xD7,0xEE,0x19,0xE5,0xD9,0xF6,0x19,0xFE,0x5D,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xF6,0x1B,0xEE,0x1B,0xEE,0x19,0xE5,0x97,0xE5,0x97,0xDD,0x53,0xCD,0x13,0xDD,0x95,0xD5,0x55,0xD5,0x55,0xD5,0x55,0xE5,0x97,0xE5,0x97,0xF6,0x5D,0xEE,0x1B,0xF6,0x5B,0xFE,0x9D,0xFE,0x5D,0xEE,0x19,0xE5,0x97,0xE5,0x97,0xDD,0x53,0xE5,0x97,0xE5,0x97,0xE5,0x97,0xED,0xD7,0xFE,0x5B,0xFE,0xDF,0xFE,0x9D,0xEE,0x19,0xEE,0x19,0xFE,0x5D,0xF6,0x1B,0xFE,0x5B,0xFE,0x5B,0xE5,0xD7,0xD5,0x13,0xE5,0x97,0xDD,0x95,0xE5,0xD9,0xE5,0xD9,0xD5,0x55,0xD5,0x55,0xDD,0x55,0xF6,0x19,0xF6,0x5D,0xFE,0x9D,0xEE,0x19,0xEE,0x19,0xFE,0x5D,0xE5,0x97,0xCD,0x13,0xDD,0x53,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xE5,0xD9,0xE5,0x97,0xFE,0x5B,0xFE,0x9D,0xFE,0xE1,0xFE,0x5B,0xEE,0x19,0xFE,0x9D,0xFE,0x5B,0xFE,0x5B,0xF6,0x5B,0xE5,0x97,0xE5,0xD9,0xD5,0x55,0xE5,0xD9,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xE5,0x97,0xE5,0xD9,0xEE,0x1B,0xE6,0x1B,0xDD,0xD9,0xDD,0x99,0xF6,0x5B,0xFE,0x9D,0xF6,0x5B,0xDD,0x55,0xFE,0x5B,0xF6,0x9D,0xED,0xD7,0xE5,0x97,0xE5,0xD9,0xE5,0xD9,0xE5,0xD7,0xEE,0x5D,0xEE,0x19,0xED,0xD7,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xFE,0x5B,0xF6,0x1B,0xF6,0x9D,0xF6,0x5D,0xEE,0x1B,0xE5,0xD9,0xDD,0x53,0xD5,0x13,0xE5,0x95,0xFE,0x5D,0xF6,0x9F,0xEE,0x5D,0xE5,0xDB,0xDE,0x5D,0xEE,0x5B,0xEE,0x1B,0xF6,0x5B,0xEE,0x19,0xFE,0x5D,0xF6,0x19,0xF6,0x9F,0xF6,0x5B,0xEE,0x19,0xFE,0x5D,0xE5,0xD9,0xE6,0x5D,0xE5,0xD9,0xE5,0xD9,0xE5,0x95,0xE5,0x97,0xF6,0x19,0xED,0xD7,0xFE,0x5B,0xDD,0x55,0xF6,0x9D,0xFF,0x21,0xFE,0xE1,0xEE,0x19,0xCD,0x13,0xDD,0x95,0xED,0xD7,0xFE,0x5D,0xF6,0x5D,0xEE,0x9D,0xEE,0x5D,0xEE,0x9D,0xEE,0x5D,0xDD,0xD9,0xF6,0xDF,0xF6,0x5B,0xF6,0x5B,0xFE,0x5B,0xF6,0x5D,0xF6,0x5B,0xFE,0x5D,0xF6,0x1B,0xF6,0x5D,0xF6,0x9F,0xF6,0x1B,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xEE,0x19,0xEE,0x19,0xFE,0x5B,0xF6,0x19,0xED,0xD9,0xEE,0x1B,0xFE,0x5B,0xEE,0x19,0xDD,0x95,0xE5,0xD7,0xED,0xD9,0xEE,0x19,0xE6,0x1B,0xEE,0x5D,0xEE,0x5D,0xEE,0x5D,0xDD,0xD9,0xEE,0x5D,0xFE,0xDF,0xF6,0x1B,0xED,0xD7,0xEE,0x19,0xEE,0x19,0xEE,0x19,0xF6,0x1B,0xED,0xD9,0xED,0xD9,0xFE,0x9D,0xF6,0x19,0xED,0xD7,0xED,0xD7,0xE5,0x95,0xF6,0x19,0xED,0xD9,0xEE,0x19,0xED,0xD9,0xE5,0xD9,0xE5,0xD9,0xF6,0x19,0xF6,0x19,0xED,0xD7,0xE5,0x95,0xE5,0xD7,0xED,0xD9,0xED,0xD9,0xD5,0x97,0xEE,0x5D,0xDE,0x1B,0xE6,0x1B,0xE6,0x5B,0xFE,0x5D,0xEE,0x19,0xF6,0x5B,0xF6,0x19,0xED,0xD7,0xF6,0x19,0xE5,0xD9,0xF6,0x5B,0xFE,0x9D,0xF6,0x5B,0xDD,0x95,0xED,0xD7,0xEE,0x19,0xE5,0x97,0xED,0xD9,0xEE,0x1B,0xF6,0x5D,0xF6,0x5B,0xEE,0x1B,0xE5,0xD9,0xEE,0x1B,0xFE,0x5D,0xED,0xD9,0xED,0xD9,0xFE,0x5B,0xDD,0x95,0xED,0xD9,0xFE,0x9D,0xEE,0x5B,0xD5,0x97,0xE6,0x19,0xF6,0x19,0xE5,0xD7,0xED,0xD9,0xFE,0x5B,0xE5,0x97,0xE5,0x97,0xFE,0x9D,0xFE,0x9D,0xFE,0x5D,0xF6,0x19,0xE5,0x97,0xEE,0x19,0xE5,0x97,0xED,0xD7,0xEE,0x19,0xF6,0x5D,0xF6,0x5D,0xF6,0x5B,0xF6,0xDF,0xFE,0xDF,0xEE,0x1B,0xEE,0x1B,0xFE,0x9F,0xFE,0x5D,0xFE,0x5B,0xFE,0x9D,0xEE,0x19,0xDD,0x97,0xEE,0x5D,0xFE,0x5D,0xF6,0x19,0xF6,0x19,0xE5,0x97,0xED,0xD9,0xE5,0xD7,0xFE,0x9D,0xDD,0x97,0xEE,0x19,0xFE,0xDF,0xFE,0x5D,0xEE,0x9F,0xE5,0xD9,0xF6,0x5B,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xEE,0x19,0xFE,0x5B,0xFE,0x9D,0xEE,0x1B,0xF6,0x5D,0xFE,0xDF,0xEE,0x9D,0xE6,0x1B,0xEE,0x1B,0xED,0xD9,0xE5,0xD7,0xF6,0x19,0xF6,0x19,0xE5,0xD9,0xEE,0x1B,0xED,0xD9,0xF6,0x19,0xFE,0x5B,0xEE,0x19,0xEE,0x19,0xFE,0x5D,0xFE,0x9D,0xEE,0x19,0xF6,0x1B,0xF6,0x5B,0xF6,0x19,0xE6,0x1B,0xDE,0x1B,0xEE,0x5D,0xDD,0xD7,0xE5,0xD9,0xF6,0x19,0xE5,0x95,0xE5,0x95,0xED,0xD7,0xEE,0x19,0xD5,0x97,0xFE,0x9D,0xEE,0xE1,0xE5,0xD9,0xF6,0x1B,0xF6,0x5B,0xEE,0x19,0xF6,0x1B,0xF6,0x19,0xED,0xD9,0xE5,0xD7,0xDD,0x95,0xF6,0x5B,0xF6,0x1B,0xE5,0xD7,0xF6,0x5B,0xF6,0x19,0xEE,0x19,0xED,0xD7,0xF6,0x5D,0xF6,0x5B,0xF6,0x5B,0xE6,0x1B,0xE6,0x5D,0xE6,0x5D,0xE6,0x1B,0xFE,0x9D,0xF6,0x19,0xED,0xD7,0xE5,0x95,0xEE,0x19,0xDD,0x95,0xE5,0xD9,0xF6,0x5B,0xEE,0x1B,0xE5,0xD9,0xE5,0xD7,0xF6,0x1B,0xFE,0x9D,0xF6,0x1B,0xF6,0x19,0xE5,0xD7,0xCD,0x11,0xED,0xD9,0xEE,0x1B,0xED,0xD9,0xED,0xD9,0xF6,0x5D,0xF6,0x19,0xEE,0x19,0xF6,0x1B,0xF6,0x9F,0xFF,0x21,0xF6,0x9F,0xEE,0x9F,0xF6,0x9F,0xEE,0x5D,0xEE,0x5D,0xFE,0x9D,0xFE,0x5D,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xF6,0x1B,0xF6,0x19,0xE5,0xD9,0xEE,0x19,0xFE,0x9D,0xFE,0x5B,0xFE,0x5B,0xEE,0x19,0xED,0xD7,0xF6,0x19,0xE5,0xD9,0xDD,0x95,0xE5,0xD9,0xE5,0xD9,0xF6,0x19,0xFE,0x5D,0xF6,0x19,0xFE,0x9D,0xFE,0xDF,0xF6,0x9F,0xEE,0x1B,0xE5,0xD9,0xEE,0x5D,0xEE,0x1B,0xEE,0x19,0xE5,0x97,0xF6,0x19,0xF6,0x19,0xD5,0x13,0xDD,0x53,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xF6,0x19,0xE5,0xD9,0xF6,0x5D,0xFF,0x21,0xDE,0x5D,0xEE,0x5D,0xFE,0x5D,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xED,0xD7,0xF6,0x19,0xEE,0x19,0xEE,0x19,0xFE,0x5D,0xED,0xD7,0xE5,0x97,0xFE,0x5B,0xF6,0x5B,0xE5,0xD9,0xE6,0x19,0xEE,0x1B,0xEE,0x19,0xE5,0xD9,0xE5,0xD9,0xEE,0x19,0xDD,0x97,0xE5,0x97,0xED,0xD7,0xEE,0x19,0xDD,0x95,0xDD,0x95,0xE5,0xD7,0xF6,0x19,0xFE,0x9D,0xEE,0x5B,0xF6,0xE1,0xE6,0x5D,0xFE,0x9D,0xFE,0x5D,0xFE,0x5D,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xE5,0x95,0xED,0xD7,0xFE,0x5B,0xE5,0x97,0xE5,0x97,0xFE,0x5B,0xF6,0x19,0xF6,0x19,0xF6,0x5D,0xF6,0x9F,0xED,0xD7,0xDD,0x55,0xE5,0x95,0xE5,0x97,0xDD,0xD7,0xE5,0x97,0xEE,0x19,0xE5,0x97,0xD5,0x53,0xEE,0x19,0xEE,0x19,0xF6,0x19,0xFE,0x5D,0xFE,0x5D,0xF6,0x9D,0xE6,0x1B,0xFE,0x5D,0xFE,0xDF,0xF6,0x19,0xE5,0xD9,0xFE,0x5D,0xFE,0x5D,0xFE,0x9D,0xFE,0x5D,0xE5,0xD9,0xF6,0x5B,0xF6,0x19,0xF6,0x19,0xEE,0x19,0xF6,0x19,0xFF,0x21,0xFE,0x9D,0xE5,0x97,0xDD,0x55,0xE5,0x95,0xED,0xD7,0xED,0xD7,0xEE,0x19,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xEE,0x19,0xEE,0x19,0xEE,0x19,0xFE,0x5B,0xF6,0x1B,0xE5,0x97,0xEE,0x1B,0xF6,0x1B,0xF6,0x1B,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xFE,0x5D,0xFE,0xDF,0xF6,0x1B,0xF6,0x5B,0xFE,0x5D,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xDD,0x97,0xD5,0x55,0xDD,0x95,0xCD,0x13,0xCD,0x55,0xEE,0x19,0xEE,0x1B,0xDD,0x97,0xD5,0x55,0xE5,0xD9,0xE5,0xD9,0xFE,0x9D,0xFE,0x5D,0xEE,0x19,0xF6,0x1B,0xFE,0x5D,0xDD,0x97,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xED,0xD7,0xF6,0x19,0xF6,0x19,0xFE,0x9D,0xFE,0x5D,0xFE,0x5D,0xF6,0x1B,0xED,0xD9,0xED,0xD7,0xD5,0x13,0xED,0xD7,0xE5,0xD9,0xE5,0xD9,0xEE,0x19,0xD5,0x97,0xD5,0x97,0xEE,0x1B,0xEE,0x19,0xDD,0xD7,0xE5,0xD7,0xE5,0xD9,0xFE,0x5B,0xFE,0xDF,0xFE,0x5D,0xEE,0x19,0xFE,0x5B,0xED,0xD9,0xF6,0x19,0xFE,0x5D,0xE5,0xD7,0xE5,0x95,0xED,0xD7,0xED,0xD7,0xDD,0x53,0xE5,0x97,0xF6,0x19,0xED,0xD7,0xFE,0x5D,0xF6,0x19,0xED,0xD9,0xED,0xD7,0xE5,0x95,0xE5,0x97,0xF6,0x19,0xFE,0x9D,0xFE,0x9D,0xF6,0x1B,0xE5,0xD9,0xEE,0x19,0xF6,0x5D,0xF6,0x9F,0xE5,0xD7,0xE5,0x97,0xEE,0x19,0xFE,0x9D,0xF6,0x1B,0xE5,0xD7,0xFE,0x5B,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xED,0xD9,0xE5,0x95,0xE5,0xD7,0xEE,0x19,0xED,0xD7,0xEE,0x19,0xF6,0x19,0xED,0xD7,0xFE,0x5D,0xF6,0x5B,0xF6,0x5B,0xFE,0x5B,0xEE,0x19,0xEE,0x19,0xEE,0x19,0xEE,0x9F,0xF6,0x5B,0xF6,0x19,0xF6,0x19,0xF6,0x5B,0xF6,0x9D,0xEE,0x5D,0xE5,0x97,0xED,0xD7,0xED,0xD7,0xEE,0x19,0xE5,0xD9,0xE5,0xD7,0xFE,0x9D,0xFE,0x5D,0xE5,0x97,0xE5,0x97,0xF6,0x19,0xED,0xD9,0xED,0xD9,0xF6,0x19,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xEE,0x5D,0xF6,0x5B,0xFE,0x9D,0xF6,0x5B,0xEE,0x19,0xF6,0x5D,0xF6,0x5D,0xF6,0x5B,0xF6,0x19,0xFE,0x5B,0xFE,0xDF,0xF6,0xDF,0xEE,0x1B,0xE5,0xD7,0xE5,0x97,0xE5,0x95,0xE5,0x95,0xD5,0x13,0xC4,0xD3,0xE5,0xD9,0xE5,0x97,0xE5,0x97,0xE5,0x97,0xED,0xD7,0xDD,0x97,0xFE,0x5D,0xF6,0x19,0xE5,0xD9,0xF6,0x5B,0xFE,0xDF,0xED,0xD7,0xE5,0x97,0xE5,0xD9,0xFE,0x5B,0xF6,0x1B,0xE5,0x97,0xF6,0x1B,0xEE,0x19,0xF6,0x1B,0xF6,0x5B,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xEE,0x5B,0xFE,0xDF,0xFE,0x9D,0xF6,0x1B,0xF6,0x5B,0xED,0xD9,0xDD,0x53,0xED,0xD7,0xD5,0x55,0xDD,0x97,0xDD,0x53,0xDD,0x53,0xE5,0x95,0xF6,0x19,0xFE,0x9D,0xFE,0x5B,0xF6,0x9F,0xDD,0x97,0xFE,0x5D,0xEE,0x19,0xE5,0x97,0xF6,0x19,0xEE,0x19,0xF6,0x19,0xDD,0x97,0xF6,0x19,0xDD,0x97,0xDD,0x97,0xF6,0x5B,0xE5,0xD9,0xEE,0x19,0xE5,0x97,0xE5,0xD9,0xF6,0x5D,0xEE,0x19,0xED,0xD9,0xE5,0xD7,0xED,0xD9,0xED,0xD7,0xF6,0x19,0xE5,0xD7,0xDD,0x55,0xDD,0x53,0xE5,0x97,0xEE,0x19,0xFE,0x5B,0xF6,0x19,0xE5,0x97,0xF6,0x19,0xFE,0x5D,0xFE,0x5B,0xEE,0x19,0xED,0xD7,0xE5,0x95,0xFE,0x5D,0xFE,0x5B,0xED,0xD7,0xEE,0x19,0xE5,0xD7,0xEE,0x19,0xED,0xD7,0xF6,0x5B,0xF6,0x19,0xFE,0x5B,0xEE,0x19,0xDD,0x95,0xDD,0x97,0xE5,0x97,0xF6,0x19,0xF6,0x19,0xEE,0x19,0xED,0xD7,0xF6,0x19,0xED,0xD7,0xED,0xD7,0xF6,0x19,0xF6,0x19,0xFE,0x5D,0xED,0xD7,0xED,0xD7,0xF6,0x19,0xFE,0x5B,0xFE,0x5B,0xF6,0x19,0xED,0xD7,0xEE,0x19,0xFE,0x9F,0xF6,0x9F,0xEE,0x19,0xEE,0x19,0xED,0xD7,0xE5,0x97,0xED,0xD7,0xEE,0x19,0xFE,0x5B,0xFE,0x5B,0xED,0xD7,0xE5,0x97,0xF6,0x1B,0xF6,0x19,0xFE,0x5D,0xFE,0x5B,0xEE,0x19,0xEE,0x19,0xE5,0x97,0xE5,0x95,0xE5,0x97,0xED,0xD7,0xE5,0x97,0xEE,0x19,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xEE,0x19,0xE5,0x97,0xF6,0x19,0xED,0xD7,0xFE,0x5B,0xF6,0x1B,0xF6,0x5B,0xF6,0x19,0xD5,0x55,0xE5,0x97,0xD5,0x53,0xE5,0x97,0xDD,0x53,0xED,0xD7,0xEE,0x19,0xE5,0x95,0xEE,0x19,0xF6,0x1B,0xF6,0x19,0xE5,0x97,0xE5,0x97,0xFE,0x5B,0xF6,0x19,0xEE,0x19,0xE5,0x97,0xE5,0x97,0xD5,0x13,0xED,0xD7,0xEE,0x19,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xE5,0x97,0xF6,0x1B,0xFE,0x5B,0xEE,0x19,0xF6,0x19,0xED,0xD9,0xEE,0x1B,0xE5,0xD7,0xE5,0xD7,0xDD,0x97,0xE5,0xD7,0xEE,0x19,0xDD,0x55,0xDD,0x95,0xE5,0x95,0xDD,0x53,0xF6,0x19,0xEE,0x1B,0xE5,0xD9,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xEE,0x19,0xF6,0x1B,0xED,0xD7,0xE5,0x97,0xE5,0x95,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xF6,0x19,0xFE,0x5B,0xEE,0x19,0xE5,0xD9,0xDD,0x55,0xE5,0x95,0xF6,0x1B,0xE5,0xD9,0xE5,0xD9,0xEE,0x19,0xF6,0x19,0xEE,0x19,0xE5,0xD9,0xE5,0x97,0xE5,0x97,0xF6,0x19,0xE5,0xD9,0xE5,0xD7,0xEE,0x19,0xE5,0xD9,0xDD,0x97,0xE5,0xD7,0xF6,0x1B,0xEE,0x19,0xE5,0x97,0xED,0xD7,0xE5,0x97,0xED,0xD7,0xFE,0x5B,0xFE,0x5B,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xED,0xD7,0xEE,0x19,0xE5,0xD9,0xDD,0x95,0xE5,0x97,0xE5,0x97,0xEE,0x19,0xED,0xD7,0xEE,0x19,0xEE,0x19,0xF6,0x19,0xFE,0x5B,0xEE,0x19,0xEE,0x19,0xFE,0x5B,0xFE,0x5D,0xFE,0xE1,0xFE,0x9D,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xFE,0x5D,0xEE,0x19,0xE5,0x97,0xE5,0x95,0xFE,0x5B,0xF6,0x19,0xF6,0x19,0xE5,0x97,0xE5,0x95,0xD5,0x13,0xE5,0x97,0xEE,0x19,0xEE,0x19,0xEE,0x19,0xED,0xD7,0xEE,0x19,0xE5,0xD9,0xF6,0x19,0xE5,0x97,0xDD,0x55,0xEE,0x19,0xF6,0x19,0xF6,0x19,0xE5,0x97,0xF6,0x19,0xF6,0x19,0xF6,0x19,0xFE,0x5B,0xF6,0x19,0xED,0xD7,0xE5,0x97,0xF6,0x19,0xED,0xD7,0xEE,0x19,0xF6,0x19,0xEE,0x19,
5,120.5
10,240
0.799922
05da255b0ff06909cb144fbfc552d4dc39ec1b39
5,452
c
C
src/mavlink_receive.c
plusk01/desktopquad-old-fw
6511a60474301b6c0ae411a7a23324711971c2a2
[ "BSD-3-Clause" ]
null
null
null
src/mavlink_receive.c
plusk01/desktopquad-old-fw
6511a60474301b6c0ae411a7a23324711971c2a2
[ "BSD-3-Clause" ]
null
null
null
src/mavlink_receive.c
plusk01/desktopquad-old-fw
6511a60474301b6c0ae411a7a23324711971c2a2
[ "BSD-3-Clause" ]
1
2020-10-26T11:39:03.000Z
2020-10-26T11:39:03.000Z
#include "board.h" #include "mavlink.h" #include "mavlink_param.h" #include "mode.h" #include "param.h" #include "mux.h" #include "sensors.h" #include "rc.h" #include "mavlink_receive.h" #include "mavlink_log.h" #include "mavlink_util.h" // global variable definitions mavlink_offboard_control_t mavlink_offboard_control; uint64_t _offboard_control_time; // local variable definitions static mavlink_message_t in_buf; static mavlink_status_t status; // local function definitions static void mavlink_handle_msg_rosflight_cmd(const mavlink_message_t *const msg) { mavlink_rosflight_cmd_t cmd; mavlink_msg_rosflight_cmd_decode(msg, &cmd); uint8_t result; bool reboot_flag = false; bool reboot_to_bootloader_flag = false; // None of these actions can be performed if we are armed if (_armed_state == ARMED) { result = false; } else { result = true; switch (cmd.command) { case ROSFLIGHT_CMD_READ_PARAMS: result = read_params(); break; case ROSFLIGHT_CMD_WRITE_PARAMS: result = write_params(); break; case ROSFLIGHT_CMD_SET_PARAM_DEFAULTS: set_param_defaults(); break; case ROSFLIGHT_CMD_ACCEL_CALIBRATION: result = start_imu_calibration(); break; case ROSFLIGHT_CMD_GYRO_CALIBRATION: result = start_gyro_calibration(); break; case ROSFLIGHT_CMD_BARO_CALIBRATION: baro_calibrate(); break; case ROSFLIGHT_CMD_AIRSPEED_CALIBRATION: diff_pressure_calibrate(); break; case ROSFLIGHT_CMD_RC_CALIBRATION: _calibrate_rc = true; break; case ROSFLIGHT_CMD_REBOOT: reboot_flag = true; break; case ROSFLIGHT_CMD_REBOOT_TO_BOOTLOADER: reboot_to_bootloader_flag = true; break; default: mavlink_log_error("unsupported ROSFLIGHT CMD %d", cmd.command); result = false; break; } } uint8_t response = (result) ? ROSFLIGHT_CMD_SUCCESS : ROSFLIGHT_CMD_FAILED; mavlink_msg_rosflight_cmd_ack_send(MAVLINK_COMM_0, cmd.command, response); if (reboot_flag || reboot_to_bootloader_flag) { clock_delay(20); board_reset(reboot_to_bootloader_flag); } } static void mavlink_handle_msg_timesync(const mavlink_message_t *const msg) { uint64_t now_us = clock_micros(); mavlink_timesync_t tsync; mavlink_msg_timesync_decode(msg, &tsync); if (tsync.tc1 == 0) // check that this is a request, not a response { mavlink_msg_timesync_send(MAVLINK_COMM_0, (int64_t) now_us*1000, tsync.ts1); } } static void mavlink_handle_msg_offboard_control(const mavlink_message_t *const msg) { _offboard_control_time = clock_micros(); mavlink_msg_offboard_control_decode(msg, &mavlink_offboard_control); // put values into standard message _offboard_control.x.value = mavlink_offboard_control.x; _offboard_control.y.value = mavlink_offboard_control.y; _offboard_control.z.value = mavlink_offboard_control.z; _offboard_control.F.value = mavlink_offboard_control.F; // Move flags into standard message _offboard_control.x.active = !(mavlink_offboard_control.ignore & IGNORE_VALUE1); _offboard_control.y.active = !(mavlink_offboard_control.ignore & IGNORE_VALUE2); _offboard_control.z.active = !(mavlink_offboard_control.ignore & IGNORE_VALUE3); _offboard_control.F.active = !(mavlink_offboard_control.ignore & IGNORE_VALUE4); // translate modes into standard message switch (mavlink_offboard_control.mode) { case MODE_PASS_THROUGH: _offboard_control.x.type = PASSTHROUGH; _offboard_control.y.type = PASSTHROUGH; _offboard_control.z.type = PASSTHROUGH; _offboard_control.F.type = THROTTLE; break; case MODE_ROLLRATE_PITCHRATE_YAWRATE_THROTTLE: _offboard_control.x.type = RATE; _offboard_control.y.type = RATE; _offboard_control.z.type = RATE; _offboard_control.F.type = THROTTLE; _offboard_control.x.value += get_param_float(PARAM_ROLL_RATE_TRIM); _offboard_control.y.value += get_param_float(PARAM_PITCH_RATE_TRIM); _offboard_control.z.value += get_param_float(PARAM_YAW_RATE_TRIM); break; case MODE_ROLL_PITCH_YAWRATE_THROTTLE: _offboard_control.x.type = ANGLE; _offboard_control.y.type = ANGLE; _offboard_control.z.type = RATE; _offboard_control.F.type = THROTTLE; _offboard_control.x.value += get_param_float(PARAM_ROLL_ANGLE_TRIM); _offboard_control.y.value += get_param_float(PARAM_PITCH_ANGLE_TRIM); _offboard_control.z.value += get_param_float(PARAM_YAW_RATE_TRIM); break; // Handle error state } _new_command = true; } static void handle_mavlink_message(void) { switch (in_buf.msgid) { case MAVLINK_MSG_ID_OFFBOARD_CONTROL: mavlink_handle_msg_offboard_control(&in_buf); break; case MAVLINK_MSG_ID_PARAM_REQUEST_LIST: mavlink_handle_msg_param_request_list(); break; case MAVLINK_MSG_ID_PARAM_REQUEST_READ: mavlink_handle_msg_param_request_read(&in_buf); break; case MAVLINK_MSG_ID_PARAM_SET: mavlink_handle_msg_param_set(&in_buf); break; case MAVLINK_MSG_ID_ROSFLIGHT_CMD: mavlink_handle_msg_rosflight_cmd(&in_buf); break; case MAVLINK_MSG_ID_TIMESYNC: mavlink_handle_msg_timesync(&in_buf); break; default: break; } } // function definitions void mavlink_receive(void) { while (serial_bytes_available()) { if (mavlink_parse_char(MAVLINK_COMM_0, serial_read(), &in_buf, &status)) handle_mavlink_message(); } }
28.846561
83
0.75
e89c3c779388df8642207defc6070155c31e4fa5
1,588
h
C
tests/gaf-tests/Library/Sources/GAFTextData.h
ethankennerly/cocos2d-gaf-demo
7757cc04bc4142a58477c58c39684ae8b7218757
[ "MIT" ]
1
2020-03-08T09:39:00.000Z
2020-03-08T09:39:00.000Z
tests/gaf-tests/Library/Sources/GAFTextData.h
ethankennerly/cocos2d-gaf-demo
7757cc04bc4142a58477c58c39684ae8b7218757
[ "MIT" ]
null
null
null
tests/gaf-tests/Library/Sources/GAFTextData.h
ethankennerly/cocos2d-gaf-demo
7757cc04bc4142a58477c58c39684ae8b7218757
[ "MIT" ]
null
null
null
#pragma once NS_GAF_BEGIN class GAFTextData { friend class TagDefineTextField; public: class TextFormat { public: enum class TextAlign : uint32_t { Left = 0, Right, Center, Justify, Start, End }; TextAlign m_align; cocos2d::TextHAlignment getTextAlignForCocos() const; float m_letterSpacing; // !! unused cocos2d::Color4F m_color; uint32_t m_blockIndent; // !! unused uint32_t m_indent; // !! unused uint32_t m_leading; // !! unused uint32_t m_leftMargin; // !! unused uint32_t m_rightMargin; // !! unused uint32_t m_size; std::vector<uint32_t> m_tabStops; // !! unused bool m_isBold; // !! unused bool m_isItalic; // !! unused bool m_isUnderline; // !! unused bool m_isBullet; // !! unused bool m_useKerning; // !! unused std::string m_font; std::string m_target; // !! unused std::string m_url; // !! unused }; cocos2d::Point m_pivot; float m_width; float m_height; std::string m_text; std::string m_restrict; // !! unused bool m_isEmbedFonts; // !! unused bool m_isMultiline; // !! unused bool m_isWordWrap; // !! unused bool m_hasRestrict; // !! unused bool m_isEditable; // !! unused bool m_isSelectable; // !! unused bool m_displayAsPassword; // !! unused uint32_t m_maxChars; // !! unused TextFormat m_textFormat; }; NS_GAF_END
22.055556
61
0.566751
0542c3fc1e35971d135c08384b51839ee8df4c93
755
h
C
CodeObfuscation/CodeObfuscation/TemplateFiles/COTemplateFile.h
killvxk/code-obfuscation-1
e4cdf38c67ef78925d20cd01cad43bd2a0e669e2
[ "MIT" ]
1
2018-02-09T12:45:34.000Z
2018-02-09T12:45:34.000Z
CodeObfuscation/CodeObfuscation/TemplateFiles/COTemplateFile.h
killvxk/code-obfuscation-1
e4cdf38c67ef78925d20cd01cad43bd2a0e669e2
[ "MIT" ]
null
null
null
CodeObfuscation/CodeObfuscation/TemplateFiles/COTemplateFile.h
killvxk/code-obfuscation-1
e4cdf38c67ef78925d20cd01cad43bd2a0e669e2
[ "MIT" ]
null
null
null
// // COTemplateFile.h // CodeObfuscation // // Created by hejunqiu on 2017/5/25. // Copyright © 2017年 CHE. All rights reserved. // #import <Foundation/Foundation.h> #import "COTemplateFile.coh" @interface CO_CONFUSION_CLASS COTemplateFile : NSObject @property (nonatomic, strong) NSString * CO_CONFUSION_PROPERTY prop1; @property CGFloat CO_CONFUSION_PROPERTY prop2; CO_CONFUSION_METHOD - (void)makeFoo:(NSString *)foo1 arg2:(NSInteger)arg2; CO_CONFUSION_METHOD - (instancetype)initWithArg1:(CGFloat)arg, ...; @end @interface COTemplateFile (CO_CONFUSION_CATEGORY oxxxxo) @property (nonatomic) CGFloat CO_CONFUSION_PROPERTY prop3; @end @interface NSString (CO_CONFUSION_CATEGORY abcde) CO_CONFUSION_METHOD - (void)test:(CGFloat)arg; @end
20.405405
69
0.778808
e822dc4c02f6edabca9dab56e76070ba4ac4c419
501
c
C
test/test_syscall.c
yifanz/masters-proj
15c00d4314f43f1d34e2278e1fdf34cf509a741a
[ "BSD-2-Clause" ]
1
2017-09-02T04:33:47.000Z
2017-09-02T04:33:47.000Z
test/test_syscall.c
yifanz/masters-proj
15c00d4314f43f1d34e2278e1fdf34cf509a741a
[ "BSD-2-Clause" ]
null
null
null
test/test_syscall.c
yifanz/masters-proj
15c00d4314f43f1d34e2278e1fdf34cf509a741a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2016, Yi-Fan Zhang. All rights reserved. * Copyrights licensed under the BSD License. * See the accompanying LICENSE file for terms. * See the accompanying ATTRIB file for attributions/credits. */ #include "stdlib.h" #include "unistd.h" #include "string.h" int main(int argc, char* argv[]) { char buf = '0'; int n; if (argc > 1) n = atoi(argv[1]); else n = 1; for (int i = 0; i < n; i++) { write(1, &buf, sizeof buf); } return 0; }
19.269231
61
0.596806
193a2bb27189565f11940f934dedbe7eed54d50f
1,365
h
C
src/utility/velodyne_puck/velodyne_puck_driver/include/velodyne_puck_driver/velodyne_puck_driver_nodelet.h
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
33
2018-06-03T19:45:42.000Z
2022-02-17T09:18:11.000Z
src/utility/velodyne_puck/velodyne_puck_driver/include/velodyne_puck_driver/velodyne_puck_driver_nodelet.h
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
167
2018-05-17T03:48:11.000Z
2019-04-30T21:57:01.000Z
src/utility/velodyne_puck/velodyne_puck_driver/include/velodyne_puck_driver/velodyne_puck_driver_nodelet.h
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
26
2018-07-04T04:32:54.000Z
2022-02-22T10:10:49.000Z
/* * This file is part of velodyne_puck driver. * * The driver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The driver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the driver. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <boost/thread.hpp> #include <ros/ros.h> #include <pluginlib/class_list_macros.h> #include <nodelet/nodelet.h> #include <velodyne_puck_driver/velodyne_puck_driver.h> namespace velodyne_puck_driver { class VelodynePuckDriverNodelet: public nodelet::Nodelet { public: VelodynePuckDriverNodelet(); ~VelodynePuckDriverNodelet(); private: virtual void onInit(void); virtual void devicePoll(void); volatile bool running; ///< device thread is running boost::shared_ptr<boost::thread> device_thread; VelodynePuckDriverPtr velodyne_puck_driver; ///< driver implementation class }; } // namespace velodyne_driver
27.857143
78
0.750183
b23467fba9bcc94ede6b2cfa5fcd9271e0ec9209
3,536
h
C
query.h
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
14
2015-01-25T19:11:49.000Z
2021-08-24T18:48:37.000Z
query.h
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
query.h
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
8
2015-03-16T20:08:53.000Z
2020-09-14T02:39:48.000Z
/* * Copyright 2009, Pythia authors (see AUTHORS file). * 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. */ #include "operators/operators.h" #include "visitors/allvisitors.h" #include <map> class Query { public: Query() : tree(0) { } inline void threadInit() { ThreadInitVisitor tiv(0); accept(&tiv); } inline Operator::ResultCode scanStart() { Schema emptyschema; return tree->scanStart(0, NULL, emptyschema); } inline Operator::GetNextResultT getNext() { return tree->getNext(0); } inline Operator::ResultCode scanStop() { return tree->scanStop(0); } inline void threadClose() { ThreadCloseVisitor tcv(0); accept(&tcv); } /** * Method that calls destroy() at each operator, but does not reclaim * each operator object using `delete`. Useful for cheap copies of the * tree and for statically allocated operators. */ inline void destroynofree() { RecursiveDestroyVisitor rdv; accept(&rdv); } inline void destroy() { RecursiveDestroyVisitor rdv; accept(&rdv); RecursiveFreeVisitor rfv; accept(&rfv); } inline Schema& getOutSchema() { return tree->getOutSchema(); } inline void accept(Visitor* v) { tree->accept(v); } typedef std::map<std::string, SingleInputOp*> UserDefinedOpMapT; void create(libconfig::Config& cfg, UserDefinedOpMapT& udops); /** * Calls create with no user-defined operators. */ inline void create(libconfig::Config& cfg) { UserDefinedOpMapT emptyops; create(cfg, emptyops); } /** * Returns operator depth in query tree, or -1 if it doesn't exist. */ int getOperatorDepth(Operator* op); // Leaving tree as public member until a helper method is developed // that can automatically construct and initialize a Query tree from the // configuration file. // // protected: Operator* tree; typedef std::map<Operator*, int> OperatorDepthT; private: // Map used for pretty-printing and debugging. // OperatorDepthT operatorDepth; };
26
73
0.714649
587d241874f2abef4a59e78d40f8e10501f99e16
12,241
h
C
hookflash-core/core/hookflash/stack/IPublication.h
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
1
2020-02-19T09:55:55.000Z
2020-02-19T09:55:55.000Z
hookflash-core/core/hookflash/stack/IPublication.h
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
hookflash-core/core/hookflash/stack/IPublication.h
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2012, SMB Phone Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #pragma once #include <hookflash/stack/hookflashTypes.h> #include <hookflash/stack/IPublicationMetaData.h> #include <zsLib/Proxy.h> #include <zsLib/XML.h> #include <list> namespace hookflash { namespace stack { interaction IPublication : public IPublicationMetaData { typedef zsLib::BYTE BYTE; typedef zsLib::Time Time; typedef zsLib::String String; typedef zsLib::AutoRecursiveLock AutoRecursiveLock; typedef zsLib::XML::DocumentPtr DocumentPtr; typedef boost::shared_ptr<AutoRecursiveLock> AutoRecursiveLockPtr; typedef String ContactID; typedef std::list<ContactID> RelationshipList; static IPublicationPtr create( Sources source, const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const BYTE *data, size_t sizeInBytes, const PublishToRelationshipsMap &publishToRelationships, const char *peerContactID = NULL, const char *peerLocationID = NULL, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr create( Sources source, const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, DocumentPtr documentToBeAdopted, const PublishToRelationshipsMap &publishToRelationships, const char *peerContactID = NULL, const char *peerLocationID = NULL, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr create( Sources source, const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const RelationshipList &relationshipsDocument, const PublishToRelationshipsMap &publishToRelationships, const char *peerContactID = NULL, const char *peerLocationID = NULL, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr createForLocal( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const BYTE *data, size_t sizeInBytes, const PublishToRelationshipsMap &publishToRelationships, Time expires = Time() ); static IPublicationPtr createForFinder( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const BYTE *data, size_t sizeInBytes, const PublishToRelationshipsMap &publishToRelationships, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr createForPeer( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const BYTE *data, size_t sizeInBytes, const char *peerContactID, const char *peerLocationID, const PublishToRelationshipsMap &publishToRelationships, Time expires = Time() ); static IPublicationPtr createForLocal( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, DocumentPtr documentToBeAdopted, const PublishToRelationshipsMap &publishToRelationships, Time expires = Time() ); static IPublicationPtr createForFinder( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, DocumentPtr documentToBeAdopted, const PublishToRelationshipsMap &publishToRelationships, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr createForPeer( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, DocumentPtr documentToBeAdopted, const PublishToRelationshipsMap &publishToRelationships, const char *peerContactID, const char *peerLocationID, Time expires = Time() ); static IPublicationPtr createForLocal( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const RelationshipList &relationshipsDocument, const PublishToRelationshipsMap &publishToRelationships, Time expires = Time() ); static IPublicationPtr createForFinder( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const RelationshipList &relationshipsDocument, const PublishToRelationshipsMap &publishToRelationships, Scopes scope = Scope_Location, Lifetimes lifetime = Lifetime_Session, Time expires = Time() ); static IPublicationPtr createForPeer( const char *creatorContactID, const char *creatorLocationID, const char *name, const char *mimeType, const RelationshipList &relationshipsDocument, const PublishToRelationshipsMap &publishToRelationships, const char *peerContactID, const char *peerLocationID, Time expires = Time() ); virtual void update( const BYTE *data, size_t sizeInBytes ) = 0; virtual void update(DocumentPtr updatedDocumentToBeAdopted) = 0; virtual void update(const RelationshipList &relationships) = 0; virtual void getRawData( AutoRecursiveLockPtr &outDocumentLock, boost::shared_array<BYTE> &outputBuffer, size_t &outputBufferSizeInBytes ) const = 0; virtual DocumentPtr getXML(AutoRecursiveLockPtr &outDocumentLock) const = 0; virtual void getAsContactList(RelationshipList &outList) const = 0; }; } }
53.221739
101
0.438935
f97d5e43ea4105d47821c58f9b3f7e1de814bb7b
6,334
h
C
kernel/lge/msm8226/arch/arm/mach-msm/include/mach/msm_smsm.h
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
1
2020-06-01T10:53:47.000Z
2020-06-01T10:53:47.000Z
kernel/lge/msm8226/arch/arm/mach-msm/include/mach/msm_smsm.h
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
1
2020-05-28T13:06:06.000Z
2020-05-28T13:13:15.000Z
kernel/lge/msm8226/arch/arm/mach-msm/include/mach/msm_smsm.h
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _ARCH_ARM_MACH_MSM_SMSM_H_ #define _ARCH_ARM_MACH_MSM_SMSM_H_ #include <linux/notifier.h> #include <mach/msm_smem.h> #if defined(CONFIG_MSM_N_WAY_SMSM) enum { SMSM_APPS_STATE, SMSM_MODEM_STATE, SMSM_Q6_STATE, SMSM_APPS_DEM, SMSM_WCNSS_STATE = SMSM_APPS_DEM, SMSM_MODEM_DEM, SMSM_DSPS_STATE = SMSM_MODEM_DEM, SMSM_Q6_DEM, SMSM_POWER_MASTER_DEM, SMSM_TIME_MASTER_DEM, }; extern uint32_t SMSM_NUM_ENTRIES; #else enum { SMSM_APPS_STATE = 1, SMSM_MODEM_STATE = 3, SMSM_NUM_ENTRIES, }; #endif /* * Ordered by when processors adopted the SMSM protocol. May not be 1-to-1 * with SMEM PIDs, despite initial expectations. */ enum { SMSM_APPS = SMEM_APPS, SMSM_MODEM = SMEM_MODEM, SMSM_Q6 = SMEM_Q6, SMSM_WCNSS, SMSM_DSPS, }; extern uint32_t SMSM_NUM_HOSTS; #define SMSM_INIT 0x00000001 #define SMSM_OSENTERED 0x00000002 #define SMSM_SMDWAIT 0x00000004 #define SMSM_SMDINIT 0x00000008 #define SMSM_RPCWAIT 0x00000010 #define SMSM_RPCINIT 0x00000020 #define SMSM_RESET 0x00000040 #define SMSM_RSA 0x00000080 #define SMSM_RUN 0x00000100 #define SMSM_PWRC 0x00000200 #define SMSM_TIMEWAIT 0x00000400 #define SMSM_TIMEINIT 0x00000800 #define SMSM_PROC_AWAKE 0x00001000 #define SMSM_WFPI 0x00002000 #define SMSM_SLEEP 0x00004000 #define SMSM_SLEEPEXIT 0x00008000 #define SMSM_OEMSBL_RELEASE 0x00010000 #define SMSM_APPS_REBOOT 0x00020000 #define SMSM_SYSTEM_POWER_DOWN 0x00040000 #define SMSM_SYSTEM_REBOOT 0x00080000 #define SMSM_SYSTEM_DOWNLOAD 0x00100000 #define SMSM_PWRC_SUSPEND 0x00200000 #define SMSM_APPS_SHUTDOWN 0x00400000 #define SMSM_SMD_LOOPBACK 0x00800000 #define SMSM_RUN_QUIET 0x01000000 #define SMSM_MODEM_WAIT 0x02000000 #define SMSM_MODEM_BREAK 0x04000000 #define SMSM_MODEM_CONTINUE 0x08000000 #define SMSM_SYSTEM_REBOOT_USR 0x20000000 #define SMSM_SYSTEM_PWRDWN_USR 0x40000000 #define SMSM_UNKNOWN 0x80000000 #define SMSM_WKUP_REASON_RPC 0x00000001 #define SMSM_WKUP_REASON_INT 0x00000002 #define SMSM_WKUP_REASON_GPIO 0x00000004 #define SMSM_WKUP_REASON_TIMER 0x00000008 #define SMSM_WKUP_REASON_ALARM 0x00000010 #define SMSM_WKUP_REASON_RESET 0x00000020 #define SMSM_USB_PLUG_UNPLUG 0x00002000 #define SMSM_A2_RESET_BAM 0x00004000 #define SMSM_VENDOR 0x00020000 #define SMSM_A2_POWER_CONTROL 0x00000002 #define SMSM_A2_POWER_CONTROL_ACK 0x00000800 #define SMSM_WLAN_TX_RINGS_EMPTY 0x00000200 #define SMSM_WLAN_TX_ENABLE 0x00000400 #define SMSM_SUBSYS2AP_STATUS 0x00008000 enum { SMEM_APPS_Q6_SMSM = 3, SMEM_Q6_APPS_SMSM = 5, SMSM_NUM_INTR_MUX = 8, }; #ifdef CONFIG_MSM_SMD int smsm_change_state(uint32_t smsm_entry, uint32_t clear_mask, uint32_t set_mask); /* * Changes the global interrupt mask. The set and clear masks are re-applied * every time the global interrupt mask is updated for callback registration * and de-registration. * * The clear mask is applied first, so if a bit is set to 1 in both the clear * mask and the set mask, the result will be that the interrupt is set. * * @smsm_entry SMSM entry to change * @clear_mask 1 = clear bit, 0 = no-op * @set_mask 1 = set bit, 0 = no-op * * @returns 0 for success, < 0 for error */ int smsm_change_intr_mask(uint32_t smsm_entry, uint32_t clear_mask, uint32_t set_mask); int smsm_get_intr_mask(uint32_t smsm_entry, uint32_t *intr_mask); uint32_t smsm_get_state(uint32_t smsm_entry); int smsm_state_cb_register(uint32_t smsm_entry, uint32_t mask, void (*notify)(void *, uint32_t old_state, uint32_t new_state), void *data); int smsm_state_cb_deregister(uint32_t smsm_entry, uint32_t mask, void (*notify)(void *, uint32_t, uint32_t), void *data); void smsm_print_sleep_info(uint32_t sleep_delay, uint32_t sleep_limit, uint32_t irq_mask, uint32_t wakeup_reason, uint32_t pending_irqs); void smsm_reset_modem(unsigned mode); void smsm_reset_modem_cont(void); void smd_sleep_exit(void); int smsm_check_for_modem_crash(void); #else static inline int smsm_change_state(uint32_t smsm_entry, uint32_t clear_mask, uint32_t set_mask) { return -ENODEV; } /* * Changes the global interrupt mask. The set and clear masks are re-applied * every time the global interrupt mask is updated for callback registration * and de-registration. * * The clear mask is applied first, so if a bit is set to 1 in both the clear * mask and the set mask, the result will be that the interrupt is set. * * @smsm_entry SMSM entry to change * @clear_mask 1 = clear bit, 0 = no-op * @set_mask 1 = set bit, 0 = no-op * * @returns 0 for success, < 0 for error */ static inline int smsm_change_intr_mask(uint32_t smsm_entry, uint32_t clear_mask, uint32_t set_mask) { return -ENODEV; } static inline int smsm_get_intr_mask(uint32_t smsm_entry, uint32_t *intr_mask) { return -ENODEV; } static inline uint32_t smsm_get_state(uint32_t smsm_entry) { return 0; } static inline int smsm_state_cb_register(uint32_t smsm_entry, uint32_t mask, void (*notify)(void *, uint32_t old_state, uint32_t new_state), void *data) { return -ENODEV; } static inline int smsm_state_cb_deregister(uint32_t smsm_entry, uint32_t mask, void (*notify)(void *, uint32_t, uint32_t), void *data) { return -ENODEV; } static inline void smsm_print_sleep_info(uint32_t sleep_delay, uint32_t sleep_limit, uint32_t irq_mask, uint32_t wakeup_reason, uint32_t pending_irqs) { } static inline void smsm_reset_modem(unsigned mode) { } static inline void smsm_reset_modem_cont(void) { } static inline void smd_sleep_exit(void) { } static inline int smsm_check_for_modem_crash(void) { return -ENODEV; } #endif #endif
29.460465
78
0.763183
47a3b0679181ddb017bc980736759399daf2e088
1,944
c
C
clightning/ccan/ccan/autodata/test/run-fools.c
michaelfolkson/lnhw
1a5709e5c627330d30207876c85b45429b003ca9
[ "Apache-2.0" ]
9
2016-03-24T10:51:45.000Z
2022-01-02T22:30:38.000Z
clightning/ccan/ccan/autodata/test/run-fools.c
michaelfolkson/lnhw
1a5709e5c627330d30207876c85b45429b003ca9
[ "Apache-2.0" ]
8
2016-03-29T03:12:10.000Z
2021-08-24T10:41:21.000Z
ccan/ccan/autodata/test/run-fools.c
jtimon/lightning
61383408a45960bf7fd045fc420c95478de699c0
[ "MIT" ]
7
2019-10-07T23:53:49.000Z
2021-11-23T18:26:30.000Z
#include <ccan/autodata/autodata.h> /* Include the C files directly. */ #include <ccan/autodata/autodata.c> #include <ccan/tap/tap.h> AUTODATA_TYPE(autostrings, char); AUTODATA(autostrings, "genuine"); #if !HAVE_SECTION_START_STOP /* These are all fake, to test the various failure paths. */ /* Hopefully fake_alpha or fake_omega will test run-past-end. */ static const void *NEEDED fake_alpha[] = { (void *)AUTODATA_MAGIC }; /* Wrong magic in the middle. */ static const void *NEEDED fake1[] = { (void *)(AUTODATA_MAGIC ^ 0x10000), (void *)&fake1, "fake1", (void *)"autostrings" }; /* Wrong self pointer. */ static const void *NEEDED fake2[] = { (void *)AUTODATA_MAGIC, (void *)&fake1, "fake2", (void *)"autostrings" }; /* Wrong name. */ static const void *NEEDED fake3[] = { (void *)AUTODATA_MAGIC, (void *)&fake3, "fake3", (void *)"autostrings2" }; /* Invalid self-pointer. */ static const void *NEEDED fake4[] = { (void *)AUTODATA_MAGIC, (void *)1UL, "fake4", (void *)"autostrings" }; /* Invalid name pointer */ static const void *NEEDED fake5[] = { (void *)AUTODATA_MAGIC, (void *)&fake5, "fake5", (void *)1UL }; /* Invalid contents pointer */ static const void *NEEDED fake6[] = { (void *)AUTODATA_MAGIC, (void *)&fake6, (char *)1UL, (void *)"autostrings" }; static const void *NEEDED fake_omega[] = { (void *)AUTODATA_MAGIC }; #endif int main(void) { char **table; size_t num; /* This is how many tests you plan to run */ plan_tests(2); table = autodata_get(autostrings, &num); ok1(num == 2); ok1((!strcmp(table[0], "genuine") && !strcmp(table[1], "helper")) || (!strcmp(table[1], "genuine") && !strcmp(table[0], "helper"))); autodata_free(table); /* This exits depending on whether all tests passed */ return exit_status(); }
27
73
0.604424
2f7fac267978e5ade44043b949bf0da79014d11f
410
c
C
Demo/CORTEX_A9_Zynq_Zedboard_SDK/SmallRTOSDemo/src/lwIP_Demo/main_lwIP.c
PeterPan506/SmallRTOS
9bbb6be681f6901c0c76f1f4eec9625a0b62c019
[ "DOC" ]
1
2021-04-01T13:03:22.000Z
2021-04-01T13:03:22.000Z
Demo/CORTEX_A9_Zynq_Zedboard_SDK/SmallRTOSDemo/src/lwIP_Demo/main_lwIP.c
PeterPan506/SmallRTOS
9bbb6be681f6901c0c76f1f4eec9625a0b62c019
[ "DOC" ]
null
null
null
Demo/CORTEX_A9_Zynq_Zedboard_SDK/SmallRTOSDemo/src/lwIP_Demo/main_lwIP.c
PeterPan506/SmallRTOS
9bbb6be681f6901c0c76f1f4eec9625a0b62c019
[ "DOC" ]
1
2016-03-25T00:24:33.000Z
2016-03-25T00:24:33.000Z
/* Kernel includes. */ #include "SmallRTOS.h" /* lwIP includes. */ #include "lwip/tcpip.h" /* * Defined in lwIPApps.c. */ extern void lwIPAppsInit( void *pvArguments ); /*-----------------------------------------------------------*/ void main_lwIP( void ) { /* Init lwIP and start lwIP tasks. */ tcpip_init( lwIPAppsInit, NULL ); /* Start the tasks and timer running. */ OSStart(); for( ;; ); }
15.769231
63
0.539024
446330a3ef28d7ea6f9f45368bc642600c90795c
40,294
c
C
src/ast.c
falstro/joqe
2b58f0cc2f5a01abe16f114fccfd65ce7af425bf
[ "MIT" ]
null
null
null
src/ast.c
falstro/joqe
2b58f0cc2f5a01abe16f114fccfd65ce7af425bf
[ "MIT" ]
null
null
null
src/ast.c
falstro/joqe
2b58f0cc2f5a01abe16f114fccfd65ce7af425bf
[ "MIT" ]
2
2019-07-09T01:09:13.000Z
2021-04-23T09:48:02.000Z
#include "ast.h" #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #define IMPLODE 0, 0, 0 static inline void joqe_result_append(joqe_result *r, joqe_nodels *n) { joqe_list_append((joqe_list**)&r->ls, &n->ll); } joqe_nodels* joqe_result_alloc_node (joqe_result *r) { joqe_nodels *n; if(r->freels) { n = (joqe_nodels*) joqe_list_detach((joqe_list**)&r->freels, r->freels->ll.n); } else { n = malloc(sizeof(joqe_nodels)); } memset(n, 0, sizeof(*n)); return n; } joqe_node joqe_result_copy_node (joqe_node *n) { switch(JOQE_TYPE_VALUE(n->type)) { case joqe_type_none_object: case joqe_type_none_array: case joqe_type_none_stringls: if(n->u.ls) { if(n->u.ls->n.type == joqe_type_ref_cnt) { n->u.ls->n.u.i++; } else { // No ref count object implies a ref count of 1. This is the // second reference. joqe_nodels refCnt = {.n = {joqe_type_ref_cnt, .u = {.i = 2}}}, *e = malloc(sizeof(*e)); *e = refCnt; joqe_list_append((joqe_list**)&n->u.ls, &e->ll); n->u.ls = e; // (joqe_nodels*) n->u.ls->ll.p; } } } joqe_node copy = *n; return copy; } static void joqe_result_free_list (joqe_nodels *list, joqe_result *r) { joqe_nodels *i, *next; if(!list) return; if(list->n.type == joqe_type_ref_cnt) { if(0<--list->n.u.i) return; } if((i = list)) do { next = (joqe_nodels*)i->ll.n; // No need to do a proper detach, we're freeing them all. i->ll.p = i->ll.n = &i->ll; joqe_result_free_node(i, r); } while((i = next) != list); } void joqe_result_clear_node (joqe_node n, joqe_result *r) { switch(JOQE_TYPE_VALUE(n.type)) { case joqe_type_none_object: case joqe_type_none_array: case joqe_type_none_stringls: { joqe_result_free_list(n.u.ls, r); n.u.ls = 0; } /* fall through */ } } void joqe_result_free_node (joqe_nodels *n, joqe_result *r) { assert(n->ll.p == n->ll.n); joqe_result_clear_node(n->n, r); joqe_list_append((joqe_list**)&r->freels, &n->ll); } #ifdef DEBUG_FREE #include <stdio.h> #endif static void nodels_free(joqe_nodels *ls) { joqe_nodels *i, *nxt, *end; if((end = i = ls)) do { #ifdef DEBUG_FREE fprintf(stderr, "freeing: "); switch(JOQE_TYPE_KEY(i->n.type)) { case joqe_type_string_none: fprintf(stderr, "'%s': ", i->n.k.key); break; case joqe_type_int_none: fprintf(stderr, "%d: ", i->n.k.idx); break; default: fprintf(stderr, "none: "); break; } switch(JOQE_TYPE_VALUE(i->n.type)) { case joqe_type_none_string: fprintf(stderr, "%s\n", i->n.u.s); break; case joqe_type_none_integer: fprintf(stderr, "%d\n", i->n.u.i); break; case joqe_type_none_real: fprintf(stderr, "%g\n", i->n.u.d); break; case joqe_type_none_object: fprintf(stderr, "object\n"); break; case joqe_type_none_array: fprintf(stderr, "array\n"); break; case joqe_type_none_stringls: fprintf(stderr, "stringls\n"); break; default: fprintf(stderr, "broken?\n"); } #endif nxt = (joqe_nodels*) i->ll.n; free(i); } while((i = nxt) != end); } void joqe_result_destroy (joqe_result *r) { joqe_result_free_list(r->ls, r); nodels_free(r->freels); } static joqe_result joqe_result_push(joqe_result *r) { if(r) { joqe_result n = {.freels = r->freels}; r->freels = 0; return n; } else { joqe_result n = {}; return n; } } static void joqe_result_free_transfer(joqe_result *target, joqe_result *src) { joqe_list_append((joqe_list**)&target->freels, &src->freels->ll); src->freels = 0; } static void joqe_result_pop(joqe_result *base, joqe_result *r) { if(base) { joqe_result_free_list(r->ls, r); joqe_result_free_transfer(base, r); base->status |= r->status; } else { joqe_result_destroy(r); } } static void joqe_result_transfer(joqe_result *base, joqe_result *r) { joqe_result_append(base, r->ls); r->ls = 0; } static joqe_nodels * result_nodels (joqe_result *r, joqe_type type) { joqe_nodels *ls = joqe_result_alloc_node(r); ls->n.type = type; joqe_result_append(r, ls); return ls; } static int strlscmp(joqe_node l, joqe_node r) { int le, re, e, d, lo = 0, ro = 0; assert(JOQE_TYPE_VALUE(l.type) == joqe_type_none_stringls); assert(JOQE_TYPE_VALUE(r.type) == joqe_type_none_stringls); joqe_nodels *li = l.u.ls, *ri = r.u.ls; joqe_nodels *endl = li, *endr = ri; joqe_nodels emptyls = {.n = {joqe_type_none_string, .u = {.s = ""}}}; emptyls.ll.n = emptyls.ll.p = &emptyls.ll; if(!li) { endl = li = &emptyls; } else if(li->n.type == joqe_type_ref_cnt) { li = (joqe_nodels*)li->ll.n; } if(!ri) { endr = ri = &emptyls; } else if(ri->n.type == joqe_type_ref_cnt) { ri = (joqe_nodels*)ri->ll.n; } le = strlen(li->n.u.s); re = strlen(ri->n.u.s); do { e = min(le-lo, re-ro); assert(e >= 0); if(e) { if((d = strncmp(li->n.u.s + lo, ri->n.u.s + ro, e))) return d; } lo += e; ro += e; if(lo == le) { lo = 0; do { li = (joqe_nodels*)li->ll.n; le = (li == endl) ? -1 : strlen(li->n.u.s); } while(le == 0); } if(ro == re) { ro = 0; do { ri = (joqe_nodels*)ri->ll.n; re = (ri == endr) ? -1 : strlen(ri->n.u.s); } while(re == 0); } } while(le >= 0 && re >= 0); return le < 0 ? re < 0 ? 0 : -1 : 1; } static int strlsstrcmp(joqe_node l, const char *s) { joqe_nodels ls = {.n = {joqe_type_none_string, .u = {.s = s}}}; joqe_node r = {joqe_type_none_stringls, .u = {.ls = &ls}}; ls.ll.n = ls.ll.p = &ls.ll; return strlscmp(l, r); } static joqe_ast_construct* ast_construct_alloc() { return calloc(1, sizeof(joqe_ast_construct)); } static int ast_construct_free(joqe_ast_construct *c) { if(c) free(c); return 0; } static joqe_ast_expr* ast_expr_alloc() { return calloc(1, sizeof(joqe_ast_expr)); } static int ast_expr_free(joqe_ast_expr *e) { if(e) free(e); return 0; } static int ast_unary_implode(joqe_ast_expr *e) { if(e->u.e) { e->u.e->evaluate(e->u.e, IMPLODE); ast_expr_free(e->u.e); } return 0; } static int ast_binary_implode(joqe_ast_expr *e) { if(e->u.b.l) { e->u.b.l->evaluate(e->u.b.l, IMPLODE); ast_expr_free(e->u.b.l); } if(e->u.b.r) { e->u.b.r->evaluate(e->u.b.r, IMPLODE); ast_expr_free(e->u.b.r); } return 0; } static int bool_eval_node(joqe_node rx, joqe_node *n) { joqe_type v = JOQE_TYPE_VALUE(rx.type); switch(JOQE_TYPE_KEY(n->type)) { case joqe_type_string_none: return (v == joqe_type_none_string && 0 == strcmp(rx.u.s, n->k.key)); case joqe_type_int_none: return (v == joqe_type_none_integer && rx.u.i == n->k.idx); // Design consideration, we do not treat a real-typed integer // value as an index. We could check for integer value, but that // would make the use inconsistent, better to always reject it, and // force the use of casting in that case. // TODO add type casting (-functions?) default: return v == joqe_type_none_true; } } static int eval_fix_value(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { if(!n) return 0; if(n->type == joqe_type_ref_cnt) return 0; // never match ref count nodes. if(r) { joqe_type t = joqe_type_broken; switch(e->u.i) { case 1: t = joqe_type_none_true; break; case 0: t = joqe_type_none_false; break; case -1: t = joqe_type_none_null; break; } joqe_nodels *ls = result_nodels(r, t); ls->n.u.i = e->u.i; } return e->u.i > 0; } static int eval_string_value(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { if(!n) return 0; if(r) { joqe_nodels *ls = result_nodels(r, joqe_type_none_string); ls->n.u.s = e->u.s; return !!*ls->n.u.s; } else { return JOQE_TYPE_KEY(n->type) == joqe_type_string_none && n->k.key && 0 == strcmp(n->k.key, e->u.s); } } static joqe_ast_expr ast_string_value(const char *s) { joqe_ast_expr e = {eval_string_value}; e.u.s = s; return e; } static int eval_stringls_value(joqe_ast_expr *e, joqe_node *n, joqe_ctx *ctx, joqe_result *r) { if(!n) { nodels_free(e->u.n.u.ls); return 0; } if(r) { joqe_nodels *ls = result_nodels(r, joqe_type_none_stringls); ls->n = joqe_result_copy_node(&e->u.n); return e->u.n.u.ls ? 1 : 0; } else { /* reversed strlsstrcmp arguments, so result should be negated, but it compares to 0 anyway. */ return JOQE_TYPE_KEY(n->type) == joqe_type_string_none && n->k.key && 0 == strlsstrcmp(e->u.n, n->k.key); } } static joqe_ast_expr ast_string_append(joqe_ast_expr e, const char *s) { if(e.evaluate == eval_string_value) { joqe_ast_expr ne = {eval_stringls_value, .u = {.n = {joqe_type_none_stringls}}}; joqe_nodels prev = {.n = {joqe_type_none_string, .u = {.s = e.u.s}}}, *prevls = malloc(sizeof(*prevls)); *prevls = prev; joqe_list_append((joqe_list**)&ne.u.n.u.ls, &prevls->ll); e = ne; } else assert(e.evaluate == eval_stringls_value); joqe_nodels append = {.n = {joqe_type_none_string, .u = {.s = s}}}, *appendls = malloc(sizeof(*appendls)); *appendls = append; joqe_list_append((joqe_list**)&e.u.n.u.ls, &appendls->ll); return e; } static int eval_integer_value(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { if(!n) return 0; if(r) { joqe_nodels *ls = result_nodels(r, joqe_type_none_integer); ls->n.u.i = e->u.i; return ls->n.u.i; } else { return JOQE_TYPE_KEY(n->type) == joqe_type_int_none && n->k.idx == e->u.i; } } static joqe_ast_expr ast_integer_value(int i) { joqe_ast_expr e = {eval_integer_value}; e.u.i = i; return e; } static int eval_real_value(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { if(!n) return 0; if(r) { joqe_nodels *ls = result_nodels(r, joqe_type_none_real); ls->n.u.d = e->u.d; } return 0; } static joqe_ast_expr ast_real_value(double d) { joqe_ast_expr e = {eval_real_value}; e.u.d = d; return e; } // --expressions-- static joqe_ast_expr ast_binary(joqe_ast_expr_eval eval, joqe_ast_expr l, joqe_ast_expr r) { joqe_ast_expr *lp = ast_expr_alloc(), *rp = ast_expr_alloc(), e = {eval, .u = {.b = {0, lp, rp}}}; *lp = l; *rp = r; return e; } static void boolean_result(int val, joqe_result *r) { joqe_nodels *o = joqe_result_alloc_node(r); o->n.type = val ? joqe_type_none_true : joqe_type_none_false; joqe_result_append(r, o); } static int eval_bor (joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_expr *lp = e->u.b.l, *rp = e->u.b.r; if(!n) return ast_binary_implode(e); joqe_result ir = joqe_result_push(r), *irp = r ? &ir : 0; int rv = lp->evaluate(lp, n, c, irp); if(rv) { joqe_nodels *ls = ir.ls; ir.ls = 0; if(r) joqe_list_append((joqe_list**) &r->ls, (joqe_list*)ls); } else { rv = rp->evaluate(rp, n, c, r); } joqe_result_pop(r, &ir); return rv; } static joqe_ast_expr ast_bor(joqe_ast_expr l, joqe_ast_expr r) { return ast_binary(eval_bor, l, r); } static int eval_band(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_expr *lp = e->u.b.l, *rp = e->u.b.r; if(!n) return ast_binary_implode(e); int rv = lp->evaluate(lp, n, c, 0) && rp->evaluate(rp, n, c, r); return rv; } static joqe_ast_expr ast_band(joqe_ast_expr l, joqe_ast_expr r) { return ast_binary(eval_band, l, r); } static int eval_compare(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_comp_op op = (joqe_ast_comp_op)e->u.b.op; joqe_ast_expr *le = e->u.b.l, *re = e->u.b.r; joqe_result lr = joqe_result_push(r); int rv = 0; if(!n) return ast_binary_implode(e); le->evaluate(le, n, c, &lr); if(lr.ls) { joqe_result rr = joqe_result_push(&lr); re->evaluate(re, n, c, &rr); joqe_nodels *li, *ri; if((li = lr.ls)) do { if((ri = rr.ls)) do { int cmp, hit = 0; joqe_node *a = &li->n, *b = &ri->n; joqe_type at = JOQE_TYPE_VALUE(a->type), bt = JOQE_TYPE_VALUE(b->type); switch(at) { case joqe_type_none_true: case joqe_type_none_false: case joqe_type_none_null: if(op == joqe_ast_comp_eq) rv = (at == bt); else if (op == joqe_ast_comp_neq) rv = (at != bt); break; case joqe_type_none_string: switch(bt) { case joqe_type_none_string: cmp = strcmp(a->u.s, b->u.s); hit = 1; break; case joqe_type_none_stringls: cmp = -strlsstrcmp(*b, a->u.s); hit = 1; break; default:; } break; case joqe_type_none_stringls: switch(bt) { case joqe_type_none_string: cmp = strlsstrcmp(*a, b->u.s); hit = 1; break; case joqe_type_none_stringls: cmp = strlscmp(*a, *b); hit = 1; break; default:; } break; case joqe_type_none_integer: switch(bt) { case joqe_type_none_integer: cmp = a->u.i - b->u.i; hit = 1; break; case joqe_type_none_real: { double d = a->u.i - b->u.d; cmp = d < 0 ? -1 : d > 0 ? 1 : 0; hit = 1; } break; default:; } break; case joqe_type_none_real: switch(bt) { case joqe_type_none_integer: { double d = a->u.d - b->u.i; cmp = d < 0 ? -1 : d > 0 ? 1 : 0; hit = 1; } break; case joqe_type_none_real: { double d = a->u.d - b->u.d; cmp = d < 0 ? -1 : d > 0 ? 1 : 0; hit = 1; } break; default:; } break; //TODO compare objects, arrays? default:; } if(hit) { switch(op) { case joqe_ast_comp_eq: rv = !cmp; break; case joqe_ast_comp_neq: rv = !!cmp; break; case joqe_ast_comp_lt: rv = cmp<0; break; case joqe_ast_comp_lte: rv = cmp<=0; break; case joqe_ast_comp_gt: rv = cmp>0; break; case joqe_ast_comp_gte: rv = cmp>=0; break; } } if(rv) goto done; } while((ri = (joqe_nodels*)ri->ll.n) != rr.ls); } while((li = (joqe_nodels*)li->ll.n) != lr.ls); done: joqe_result_pop(&lr, &rr); } joqe_result_pop(r, &lr); if(r) boolean_result(rv, r); return rv; } static joqe_ast_expr ast_bcompare(joqe_ast_comp_op op, joqe_ast_expr l, joqe_ast_expr r) { joqe_ast_expr b = ast_binary(eval_compare, l, r); b.u.b.op = op; return b; } static joqe_node calc_dbl(joqe_ast_calc_op op, double a, double b) { joqe_node rx = {joqe_type_none_real}; double d; switch(op) { case joqe_ast_calc_add: d = a + b; break; case joqe_ast_calc_sub: d = a - b; break; case joqe_ast_calc_mult: d = a * b; break; case joqe_ast_calc_div: d = a / b; break; case joqe_ast_calc_mod: d = fmod(a, b); break; default: d = 0; } rx.u.d = d; return rx; } static joqe_node calc_int(joqe_ast_calc_op op, int a, int b) { joqe_node rx = {joqe_type_none_integer}; int i; switch(op) { case joqe_ast_calc_add: i = a + b; break; case joqe_ast_calc_sub: i = a - b; break; case joqe_ast_calc_mult: i = a * b; break; case joqe_ast_calc_div: if(b == 0) return calc_dbl(op, a, b); // div-by-zero -> double inf/nan i = a / b; break; case joqe_ast_calc_mod: if(b == 0) return calc_dbl(op, a, b); // div-by-zero -> double inf/nan i = a % b; break; default: i = 0; } rx.u.i = i; return rx; } static int eval_calc(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_calc_op op = (joqe_ast_calc_op)e->u.b.op; joqe_ast_expr *le = e->u.b.l, *re = e->u.b.r; joqe_result lr = joqe_result_push(r); int rv = 0; if(!n) return ast_binary_implode(e); le->evaluate(le, n, c, &lr); if(lr.ls) { joqe_result rr = joqe_result_push(&lr); re->evaluate(re, n, c, &rr); if(r) joqe_result_free_transfer(r, &lr); joqe_nodels *li, *ri; if((li = lr.ls)) do { if((ri = rr.ls)) do { joqe_node *a = &li->n, *b = &ri->n; joqe_node rx = {}; joqe_type at = JOQE_TYPE_VALUE(a->type), bt = JOQE_TYPE_VALUE(b->type); switch(at) { case joqe_type_none_integer: switch(bt) { case joqe_type_none_integer: rx = calc_int(op, a->u.i, b->u.i); break; case joqe_type_none_real: rx = calc_dbl(op, a->u.i, b->u.d); break; default: continue; } break; case joqe_type_none_real: switch(bt) { case joqe_type_none_integer: rx = calc_dbl(op, a->u.d, b->u.i); break; case joqe_type_none_real: rx = calc_dbl(op, a->u.d, b->u.d); break; default: continue; } break; default: // can't do calculations using these. continue; } if(r) { rv++; joqe_nodels *o = joqe_result_alloc_node(r); o->n = rx; joqe_result_append(r, o); } else if(bool_eval_node(rx, n)) { rv = 1; goto done; } } while((ri = (joqe_nodels*)ri->ll.n) != rr.ls); } while((li = (joqe_nodels*)li->ll.n) != lr.ls); done: joqe_result_pop(&lr, &rr); } joqe_result_pop(r, &lr); return rv; } static joqe_ast_expr ast_calc(joqe_ast_calc_op op, joqe_ast_expr l, joqe_ast_expr r) { joqe_ast_expr b = ast_binary(eval_calc, l, r); b.u.b.op = op; return b; } static int eval_posneg(int mul, joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_expr *pe = e->u.e; joqe_nodels *i; int rv = 0; if(!n) return ast_unary_implode(e); joqe_result er = joqe_result_push(r); pe->evaluate(pe, n, c, &er); if(r) joqe_result_free_transfer(r, &er); if((i = er.ls)) do { joqe_node *a = &i->n; joqe_node rx = *a; joqe_type t = JOQE_TYPE_VALUE(a->type); switch(t) { case joqe_type_none_integer: rx.u.i = mul * a->u.i; break; case joqe_type_none_real: rx.u.d = mul * a->u.d; break; default: continue; } if(r) { rv++; joqe_nodels *o = joqe_result_alloc_node(r); o->n = rx; joqe_result_append(r, o); } else if(bool_eval_node(rx, n)) { rv = 1; goto done; } } while((i = (joqe_nodels*)i->ll.n) != er.ls); done: ; joqe_result_pop(r, &er); return rv; } static int eval_positive(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { return eval_posneg(1, e, n, c, r); } static int eval_negative(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { return eval_posneg(-1, e, n, c, r); } static joqe_ast_expr ast_negative(joqe_ast_expr e) { // short circuit negative numbers if(e.evaluate == eval_integer_value) { e.u.i = -e.u.i; return e; } else if(e.evaluate == eval_real_value) { e.u.d = -e.u.d; return e; } joqe_ast_expr *ep = ast_expr_alloc(), ne = {eval_negative, .u = {.e = ep}}; *ep = e; return ne; } static joqe_ast_expr ast_positive(joqe_ast_expr e) { // short circuit positive numbers if(e.evaluate == eval_integer_value || e.evaluate == eval_real_value) return e; joqe_ast_expr *ep = ast_expr_alloc(), ne = {eval_positive, .u = {.e = ep}}; *ep = e; return ne; } static int eval_not(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_expr *ep = e->u.e; if(!n) return ast_unary_implode(e); int rv = !ep->evaluate(ep, n, c, 0); if(r) { joqe_nodels *o = joqe_result_alloc_node(r); o->n.type = rv ? joqe_type_none_true : joqe_type_none_false; joqe_result_append(r, o); } return rv; } static joqe_ast_expr ast_bnot(joqe_ast_expr e) { joqe_ast_expr *ep = ast_expr_alloc(), ne = {eval_not, .u = {.e = ep}}; *ep = e; return ne; } static int eval_context(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_nodels *i; joqe_result jr = joqe_result_push(r); int rv = 0; if(!n) { e->u.c.ctx.construct(&e->u.c.ctx, IMPLODE); e->u.c.e->evaluate(e->u.c.e, IMPLODE); return ast_expr_free(e->u.c.e); } e->u.c.ctx.construct(&e->u.c.ctx, n, c, &jr); if((i = jr.ls)) do { joqe_ctx stacked = {c, &i->n}; rv += e->u.c.e->evaluate(e->u.c.e, &i->n, &stacked, r); } while((i = (joqe_nodels*)i->ll.n) != jr.ls); joqe_result_pop(r, &jr); return rv; } static joqe_ast_expr ast_expr_context(joqe_ast_expr e, joqe_ast_construct ctx) { joqe_ast_expr *ep = ast_expr_alloc(), ne = {eval_context, .u = {.c = {.e = ep, .ctx = ctx}}}; *ep = e; return ne; } static int eval_path(joqe_ast_expr *e, joqe_node *n, joqe_ctx *c, joqe_result *r) { return e->u.path.visit(&e->u.path, n, c, r); } static joqe_ast_expr ast_path_expr(joqe_ast_path p) { joqe_ast_expr e = {eval_path}; e.u.path = p; return e; } static joqe_ast_params ast_params() { joqe_ast_params p = {}; return p; } static joqe_ast_params ast_params_append(joqe_ast_params ps, joqe_ast_expr e) { joqe_ast_paramls *ls = calloc(1, sizeof(*ls)); ls->e = e; joqe_list_append((joqe_list**)&ps.ls, &ls->ll); ps.count++; return ps; } // --path-- static joqe_ast_path* ast_path_alloc() { return calloc(1, sizeof(joqe_ast_path)); } static joqe_ast_pathelem* ast_pathelem_alloc() { return calloc(1, sizeof(joqe_ast_pathelem)); } static int ast_pathelem_free(joqe_ast_pathelem *p) { if(p) free(p); return 0; } static int ast_path_free(joqe_ast_path *p) { if(p) free(p); return 0; } static joqe_ast_path ast_union_path(joqe_ast_path l, joqe_ast_path r) { l.punion = ast_path_alloc(); *l.punion = r; return l; } static int visit_local_path (joqe_ast_path *p, joqe_node *n, joqe_ctx *c, joqe_result *r) { int v = 0; if(p->pes) { v = p->pes->visit(p->pes, n, c, r, p->pes); if(!n) ast_pathelem_free(p->pes); } else if(n) { if(r) result_nodels(r, n->type)->n = joqe_result_copy_node(n); v = 1; //bool_eval_node(*n, n); // heh.. } if(p->punion) { // TODO union the result, not just concatenate. v += p->punion->visit(p->punion, n, c, r); if(!n) ast_path_free(p->punion); } return v; } static joqe_ast_path ast_local_path() { joqe_ast_path p = {visit_local_path}; return p; } static int visit_context_path (joqe_ast_path *p, joqe_node *n, joqe_ctx *c, joqe_result *r) { int v = 0; int depth; joqe_ctx *cc = c; for(depth = p->i; depth > 0; --depth) { if(!cc) break; cc = cc->stack; } if(p->pes) { if(!n) { // imploding, c is null. v = p->pes->visit(p->pes, n, c, r, p->pes); ast_pathelem_free(p->pes); } else if(!cc) { v = 0; } else { v = p->pes->visit(p->pes, cc->node, cc, r, p->pes); } } else if(n) { if(cc) { if(r) result_nodels(r, cc->node->type)->n = *cc->node; v = 1; //bool_eval_node(*cc, n); } else { v = 0; } } if(p->punion) { // TODO union the result, not just concatenate. v += p->punion->visit(p->punion, n, c, r); if(!n) ast_path_free(p->punion); } return v; } static joqe_ast_path ast_context_path(int depth) { joqe_ast_path p = {visit_context_path}; p.i = depth; return p; } static joqe_ast_path ast_path_chain(joqe_ast_path p, joqe_ast_pathelem pe) { joqe_ast_pathelem *nxt = ast_pathelem_alloc(); *nxt = pe; joqe_list_append((joqe_list**)&p.pes, &nxt->ll); return p; } static int visit_pe_free (joqe_ast_pathelem *p, joqe_ast_pathelem *end) { if(p->ll.n != &end->ll) { joqe_ast_pathelem *nxt = (joqe_ast_pathelem*) p->ll.n; nxt->visit(nxt, IMPLODE, end); return ast_pathelem_free(nxt); } return 0; } static int call_concat (joqe_ast_pathelem *pe, joqe_node *n, joqe_ctx *c, joqe_nodels **ps, joqe_result *r) { int pi, pcount = pe->u.func.ps.count; joqe_nodels *rn = result_nodels(r, joqe_type_none_stringls); for(pi = 0; pi < pcount; ++pi) { joqe_nodels *i; if((i = ps[pi])) do { if (JOQE_TYPE_VALUE(i->n.type) != joqe_type_none_string) continue; joqe_nodels *sn = joqe_result_alloc_node(r); sn->n = joqe_result_copy_node(&i->n); joqe_list_append((joqe_list**)&rn->n.u.ls, &sn->ll); } while((i = (joqe_nodels*)i->ll.n) != ps[pi]); } if(!rn->n.u.ls) { joqe_result_free_node(rn, r); return 0; } return 1; } static int ast_params_destroy(joqe_ast_params *p) { joqe_ast_paramls *i, *e, *ni; if ((e = i = p->ls)) do { i->e.evaluate(&i->e, IMPLODE); ni = (joqe_ast_paramls*)i->ll.n; free(i); } while((i = ni) != e); return 0; } static int ast_params_evaluate(joqe_ast_params *p, joqe_node *n, joqe_ctx *c, joqe_result *r, joqe_nodels **out) { joqe_ast_paramls *i, *e, *ni; int outi = 0; if ((e = i = p->ls)) do { assert(outi < p->count); joqe_result rx = joqe_result_push(r); i->e.evaluate(&i->e, n, c, &rx); out[outi++] = rx.ls; rx.ls = 0; joqe_result_pop(r, &rx); ni = (joqe_ast_paramls*)i->ll.n; } while((i = ni) != e); return 0; } static int visit_pefunction (joqe_ast_pathelem *p, joqe_node *n, joqe_ctx *c, joqe_result *r, joqe_ast_pathelem *end) { joqe_nodels *i, *e; int pi, pcount = p->u.func.ps.count; int found = 0; if(!n) { ast_params_destroy(&p->u.func.ps); return visit_pe_free(p, end); } if(!p->u.func.call) { r->status |= joqe_result_fail; return 0; } joqe_nodels **params = alloca(sizeof(joqe_nodels*) * pcount); ast_params_evaluate(&p->u.func.ps, n, c, r, params); joqe_result fr = joqe_result_push(r); found = p->u.func.call(p, n, c, params, &fr); for(pi = 0; pi < pcount; ++pi) joqe_result_free_list(params[pi], r); if(p->ll.n != &end->ll) { found = 0; if((e = i = fr.ls)) do { joqe_ast_pathelem *nxt = (joqe_ast_pathelem*) p->ll.n; found += nxt->visit(nxt, &i->n, c, r, end); } while((!found || r) && (i = (joqe_nodels*)i->ll.n) != e); } else { if(r) joqe_result_transfer(r, &fr); } joqe_result_pop(r, &fr); return found; } static joqe_ast_pathelem ast_pefunction(const char *name, joqe_ast_params p) { struct { const char *name; joqe_function_call call; } funcs[] = { {"concat", call_concat}, {0} }, *f; for(f = funcs; f->name && strcmp(f->name, name); ++f) ; joqe_ast_pathelem pefunction = { .visit = visit_pefunction, .u = {.func = {f->call, p}} }; return pefunction; } static int visit_peflex (joqe_ast_pathelem *p, joqe_node *n, joqe_ctx *c, joqe_result *r, joqe_ast_pathelem *end) { joqe_nodels *i, *e; int found = 0; if(!n) return visit_pe_free(p, end); if(p->ll.n != &end->ll) { joqe_ast_pathelem *nxt = (joqe_ast_pathelem*) p->ll.n; found += nxt->visit(nxt, n, c, r, end); } joqe_type t = JOQE_TYPE_VALUE(n->type); if(t != joqe_type_none_object && t != joqe_type_none_array) return found; if((!found || r) && (e = i = n->u.ls)) do { found += visit_peflex(p, &i->n, c, r, end); } while((!found || r) && (i = (joqe_nodels*)i->ll.n) != e); return found; } static joqe_ast_pathelem ast_peflex() { joqe_ast_pathelem pename = { .visit = visit_peflex }; return pename; } static int visit_pename (joqe_ast_pathelem *p, joqe_node *n, joqe_ctx *c, joqe_result *r, joqe_ast_pathelem *end) { joqe_nodels *i, *e; int found = 0; if(!n) return visit_pe_free(p, end); if(JOQE_TYPE_VALUE(n->type) != joqe_type_none_object) return 0; if((e = i = n->u.ls)) do { if (JOQE_TYPE_KEY(i->n.type) == joqe_type_string_none && 0 == strcmp(i->n.k.key, p->u.key)) { if(p->ll.n != &end->ll) { joqe_ast_pathelem *nxt = (joqe_ast_pathelem*) p->ll.n; found += nxt->visit(nxt, &i->n, c, r, end); } else { if(r) result_nodels(r, c->node->type)->n = joqe_result_copy_node(&i->n); found = 1; //bool_eval_node(i->n, n); ? } } } while((!found || r) && (i = (joqe_nodels*)i->ll.n) != e); return found; } static joqe_ast_pathelem ast_pename(const char *name) { joqe_ast_pathelem pename = { .visit = visit_pename, .u = {.key = name} }; return pename; } static int visit_pefilter (joqe_ast_pathelem *p, joqe_node *n, joqe_ctx *c, joqe_result *r, joqe_ast_pathelem *end) { joqe_nodels *i, *e; int found = 0; if(!n) { p->u.expr.evaluate(&p->u.expr, IMPLODE); return visit_pe_free(p, end); } joqe_type t = JOQE_TYPE_VALUE(n->type); if(t != joqe_type_none_object && t != joqe_type_none_array) return 0; if((e = i = n->u.ls)) do { if (p->u.expr.evaluate(&p->u.expr, &i->n, c, 0)) { if(p->ll.n != &end->ll) { joqe_ast_pathelem *nxt = (joqe_ast_pathelem*) p->ll.n; found += nxt->visit(nxt, &i->n, c, r, end); } else { if(r) result_nodels(r, c->node->type)->n = joqe_result_copy_node(&i->n); found = 1;//bool_eval_node(i->n, n); ? } } } while((!found || r) && (i = (joqe_nodels*)i->ll.n) != e); return found; } static joqe_ast_pathelem ast_pefilter(joqe_ast_expr expr) { joqe_ast_pathelem pename = { .visit = visit_pefilter, .u = {.expr = expr} }; return pename; } // --construct-- static joqe_ast_objectls * ast_objectls_alloc() { return calloc(1, sizeof(joqe_ast_objectls)); } static void ast_objectls_free(joqe_ast_objectls *p) { if(p) free(p); } static joqe_ast_arrayls * ast_arrayls_alloc() { return calloc(1, sizeof(joqe_ast_arrayls)); } static int ast_arrayls_free(joqe_ast_arrayls *p) { if(p) free(p); return 0; } static int construct_expr (joqe_ast_construct *cst, joqe_node *n, joqe_ctx *c, joqe_result *r) { if(!n) { cst->u.expr->evaluate(cst->u.expr, 0, 0, 0); return ast_expr_free(cst->u.expr); } return cst->u.expr->evaluate(cst->u.expr, n, c, r); } static joqe_ast_construct ast_expr_construct(joqe_ast_expr e) { joqe_ast_construct c = {construct_expr}; c.u.expr = ast_expr_alloc(); *c.u.expr = e; return c; } static int construct_object_entry (joqe_ast_construct *cst, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_construct *kc = cst->u.ob.key, *vc = cst->u.ob.value; if(!n) { kc->construct(kc, IMPLODE); vc->construct(vc, IMPLODE); ast_construct_free(kc); ast_construct_free(vc); return 0; } joqe_result kr = joqe_result_push(r), vr; kc->construct(kc, n, c, &kr); if(! kr.ls) { // TODO design consideration, currently: no key hit: skip entry joqe_result_pop(r, &kr); return 0; } joqe_nodels *k = (joqe_nodels*) joqe_list_detach((joqe_list**)&kr.ls, &kr.ls->ll); if(kr.ls) { //TODO design consideration, currently: multiple key hits: use first } joqe_result_pop(r, &kr); // free the key node into the r-results freelist from this point on // if we don't need it. if(JOQE_TYPE_VALUE(k->n.type) != joqe_type_none_string) { //TODO design consideration, currently: key is non-string: skip entry //Optionally: int/real -> render string? joqe_result_free_node(k, r); return 0; } vr = joqe_result_push(r); vc->construct(vc, n, c, &vr); if(! vr.ls) { //TODO design consideration, currently: no value: skip entry joqe_result_free_node(k, r); joqe_result_pop(r, &vr); return 0; } else { joqe_nodels *v = (joqe_nodels*) joqe_list_detach((joqe_list**)&vr.ls, &vr.ls->ll); if(vr.ls) { //TODO design consideration, currently: multiple value hits: use first } joqe_result_pop(r, &vr); v->n.type = JOQE_TYPE(joqe_type_string_none, v->n.type); v->n.k.key = k->n.u.s; joqe_result_free_node(k, r); joqe_result_append(r, v); return 1; } } static int construct_object (joqe_ast_construct *cst, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_objectls *i; if(!n) { joqe_ast_objectls *next, *end = cst->u.object.ls; if((i = end)) do { i->en.v.construct(&i->en.v, IMPLODE); next = (joqe_ast_objectls*)i->ll.n; ast_objectls_free(i); } while((i = next) != cst->u.object.ls); return 0; } // object construction in boolean context is always true. if(!r) return 1; joqe_nodels *o = result_nodels(r, joqe_type_none_object); joqe_result or = joqe_result_push(r); if((i = cst->u.object.ls)) do { i->en.v.construct(&i->en.v, n, c, &or); } while((i = (joqe_ast_objectls*)i->ll.n) != cst->u.object.ls); o->n.u.ls = or.ls; or.ls = 0; joqe_result_pop(r, &or); return 1; } static joqe_ast_construct ast_object_construct(joqe_ast_object o) { joqe_ast_construct c = {construct_object}; c.u.object = o; return c; } static int construct_array_in (joqe_ast_arentry *en, joqe_node *n, joqe_ctx *c, joqe_result *r) { en->v.construct(&en->v, n, c, r); return 1; } static int construct_array (joqe_ast_construct *cst, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_arrayls *i; if(!n) { joqe_ast_arrayls *next, *end = cst->u.array.ls; if((i = end)) do { construct_array_in(&i->en, IMPLODE); next = (joqe_ast_arrayls*)i->ll.n; ast_arrayls_free(i); } while((i = next) != cst->u.array.ls); return 0; } if(!r) return 1; joqe_nodels *o = result_nodels(r, joqe_type_none_array); joqe_result or = joqe_result_push(r); if((i = cst->u.array.ls)) do { construct_array_in(&i->en, n, c, &or); } while((i = (joqe_ast_arrayls*)i->ll.n) != cst->u.array.ls); o->n.u.ls = or.ls; or.ls = 0; joqe_result_pop(r, &or); int idx = 0; joqe_nodels *ni; if((ni = o->n.u.ls)) do { ni->n.type = JOQE_TYPE(joqe_type_int_none, ni->n.type); ni->n.k.idx = idx++; } while((ni = (joqe_nodels*)ni->ll.n) != o->n.u.ls); return 1; } static joqe_ast_construct ast_array_construct(joqe_ast_array a) { joqe_ast_construct c = {construct_array}; c.u.array = a; return c; } static int construct_context (joqe_ast_construct *cst, joqe_node *n, joqe_ctx *c, joqe_result *r) { joqe_ast_construct *ctx = cst->u.ctx.context; joqe_ast_construct *v = cst->u.ctx.construction; int rc = 0; if(!n) { ctx->construct(ctx, IMPLODE); v->construct(v, IMPLODE); ast_construct_free(ctx); ast_construct_free(v); return 0; } joqe_result ctxr = joqe_result_push(r); joqe_nodels *ctxi; ctx->construct(ctx, n, c, &ctxr); joqe_result_free_transfer(r, &ctxr); if((ctxi = ctxr.ls)) do { joqe_ctx stacked = {c, &ctxi->n}; rc += v->construct(v, &ctxi->n, &stacked, r); } while((ctxi = (joqe_nodels*)ctxi->ll.n) != ctxr.ls); return rc; } static joqe_ast_construct ast_construct_context (joqe_ast_construct e, joqe_ast_construct c) { joqe_ast_construct *ctx = ast_construct_alloc(); joqe_ast_construct *cts = ast_construct_alloc(); joqe_ast_construct r = { construct_context, { .ctx = {ctx, cts} } }; *ctx = c; *cts = e; return r; } static joqe_ast_object ast_object() { joqe_ast_object o = {}; return o; } static joqe_ast_object ast_object_append(joqe_ast_object o, joqe_ast_construct en) { joqe_ast_objectls *ls = ast_objectls_alloc(); ls->en.v = en; joqe_list_append((joqe_list**)&o.ls, &ls->ll); return o; } static joqe_ast_array ast_array() { joqe_ast_array a = {}; return a; } static joqe_ast_array ast_array_append(joqe_ast_array a, joqe_ast_construct en) { joqe_ast_arrayls *ls = ast_arrayls_alloc(); ls->en.v = en; joqe_list_append((joqe_list**)&a.ls, &ls->ll); return a; } static joqe_ast_construct ast_object_entry(joqe_ast_construct k, joqe_ast_construct v) { joqe_ast_construct *key = ast_construct_alloc(); joqe_ast_construct *value = ast_construct_alloc(); joqe_ast_construct e = { construct_object_entry, { .ob = { key, value } } }; *key = k; *value = v; return e; } static joqe_ast_construct ast_object_copy_entry(joqe_ast_construct v) { // this is a no-op, the expression selects key/name pairs. return v; } static joqe_ast_construct ast_array_entry(joqe_ast_construct v) { return v; } struct joqe_ast_api ast = { ast_string_value, // joqe_ast_expr (*string_value)(const char* s); ast_string_append, // joqe_ast_expr (*string_append)(joqe_ast_expr e, const char* s); ast_integer_value, // joqe_ast_expr (*integer_value)(int i); ast_real_value, // joqe_ast_expr (*real_value)(double d); // --expressions-- ast_bor, // joqe_ast_expr (*bor)(joqe_ast_expr l, joqe_ast_expr r); ast_band, // joqe_ast_expr (*band)(joqe_ast_expr l, joqe_ast_expr r); ast_bcompare, // joqe_ast_expr (*bcompare)(joqe_ast_comp_op, joqe_ast_expr l, joqe_ast_expr r); ast_calc, // joqe_ast_expr (*calc)(joqe_ast_expr l, joqe_ast_expr r); ast_negative, // joqe_ast_expr (*negative)(joqe_ast_expr e); ast_positive, // joqe_ast_expr (*positive)(joqe_ast_expr e); ast_bnot, // joqe_ast_expr (*bnot)(joqe_ast_expr e); ast_expr_context, // joqe_ast_expr (*expr_context)(joqe_ast_expr e, joqe_ast_construct ctx); ast_path_expr, // joqe_ast_expr (*path_expression)(joqe_ast_path p); ast_params, // joqe_ast_params (*params)(); ast_params_append, // joqe_ast_params (*params_append)(joqe_ast_params ps, joqe_ast_expr e); // --path-- ast_union_path, // joqe_ast_path (*punion)(joqe_ast_path l, joqe_ast_path r); ast_local_path, // joqe_ast_path (*local_path)(); ast_context_path, // joqe_ast_path (*context_path)(); ast_path_chain, // joqe_ast_path (*path_chain)(joqe_ast_path l, joqe_ast_pathelem pe); ast_pefunction, // joqe_ast_pathelem (*pefunction)(const char *name, joqe_ast_params p); ast_peflex, // joqe_ast_pathelem (*peflex)(); ast_pename, // joqe_ast_pathelem (*pename)(const char *name); ast_pefilter, // joqe_ast_pathelem (*pefilter)(joqe_ast_expr filter); // --construct-- ast_expr_construct, // joqe_ast_construct (*expr_construct)(joqe_ast_expr e); ast_object_construct, // joqe_ast_construct (*object_construct)(joqe_ast_object o); ast_array_construct, // joqe_ast_construct (*array_construct)(joqe_ast_array a); ast_construct_context, // joqe_ast_construct (*construct_context)(joqe_ast_construct e, joqe_ast_construct c); ast_object, // joqe_ast_object (*object)(); ast_object_append,// joqe_ast_object (*object_append)(joqe_ast_object o, joqe_ast_obentry e); ast_array, // joqe_ast_array (*array)(); ast_array_append, // joqe_ast_array (*array_append)(joqe_ast_array a, joqe_ast_arentry e); ast_object_entry, // joqe_ast_entry (*object_entry)(joqe_ast_expr k, joqe_ast_construct v); ast_object_copy_entry, // joqe_ast_entry (*object_copy_entry)(joqe_ast_expr v); ast_array_entry, // joqe_ast_construct (*array_entry)(joqe_ast_construct v); {eval_fix_value, .u = {.i = 1}}, // joqe_ast_expr true_value; {eval_fix_value, .u = {.i = 0}}, // joqe_ast_expr false_value; {eval_fix_value, .u = {.i = -1}} // joqe_ast_expr null_value; };
23.577531
113
0.599593
75f99dcaa384eaa011c37db71f4de1c1396b2259
14,120
c
C
gngeo/src/event.c
tcd/nggm
b0b27826ca161c0af9ccb292db60c6cb3f1df3b9
[ "MIT" ]
12
2020-05-14T09:49:10.000Z
2022-01-31T17:11:24.000Z
gngeo/src/event.c
tcd/nggm
b0b27826ca161c0af9ccb292db60c6cb3f1df3b9
[ "MIT" ]
5
2019-08-25T23:45:58.000Z
2019-11-02T22:38:39.000Z
gngeo/src/event.c
tcd/nggm
b0b27826ca161c0af9ccb292db60c6cb3f1df3b9
[ "MIT" ]
1
2021-03-22T22:00:30.000Z
2021-03-22T22:00:30.000Z
#ifdef HAVE_CONFIG_H #include "config.h" #endif //#include <stdbool.h> #include <stdlib.h> #include "SDL.h" #include "screen.h" #include "event.h" #include "conf.h" #include "emu.h" #include "memory.h" #include "gnutil.h" #include "messages.h" static int get_mapid(char *butid) { printf("Get mapid %s\n",butid); if (!strcmp(butid,"A")) return GN_A; if (!strcmp(butid,"B")) return GN_B; if (!strcmp(butid,"C")) return GN_C; if (!strcmp(butid,"D")) return GN_D; if (!strcmp(butid,"UP")) return GN_UP; if (!strcmp(butid,"DOWN")) return GN_DOWN; if (!strcmp(butid,"UPDOWN")) return GN_UP; if (!strcmp(butid,"LEFT")) return GN_LEFT; if (!strcmp(butid,"RIGHT")) return GN_RIGHT; if (!strcmp(butid,"LEFTRIGHT")) return GN_LEFT; if (!strcmp(butid,"JOY")) return GN_UP; if (!strcmp(butid,"START")) return GN_START; if (!strcmp(butid,"COIN")) return GN_SELECT_COIN; if (!strcmp(butid,"MENU")) return GN_MENU_KEY; if (!strcmp(butid,"HOTKEY1")) return GN_HOTKEY1; if (!strcmp(butid,"HOTKEY2")) return GN_HOTKEY2; if (!strcmp(butid,"HOTKEY3")) return GN_HOTKEY3; if (!strcmp(butid,"HOTKEY4")) return GN_HOTKEY4; return GN_NONE; } int create_joymap_from_string(int player,char *jconf) { char *v; char butid[32]={0,}; char jevt; int code; int jid; int rc; char type; //printf("Jconf=%s\n",jconf); if (jconf==NULL) return 0; v=strdup(jconf); v=strtok(v,","); //printf("V1=%s\n",v); while(v) { rc=sscanf(v,"%[A-Z1-4]=%c%d%c%d",butid,&type,&jid,&jevt,&code); if (rc==3 && type=='K') { /* Keyboard */ //printf("%s | keycode %d\n",butid,jid); code=jid; if (code<SDL_NUM_SCANCODES) { jmap->key[code].player=player; jmap->key[code].map=get_mapid(butid); } //printf("%d\n",get_mapid(butid)); } if (rc==5 && type=='J') { printf("%d, %s | joy no %d | evt %c | %d\n", rc,butid,jid,jevt,code); if (jid<conf.nb_joy) { switch(jevt) { case 'A': if (code<SDL_JoystickNumAxes(conf.joy[jid])) { jmap->jaxe[jid][code].player=player; jmap->jaxe[jid][code].map=get_mapid(butid); jmap->jaxe[jid][code].dir=1; } break; case 'a': /* Inverted axis */ if (code<SDL_JoystickNumAxes(conf.joy[jid])) { jmap->jaxe[jid][code].player=player; jmap->jaxe[jid][code].map=get_mapid(butid); jmap->jaxe[jid][code].dir=-1; } break; case 'H': if (code<SDL_JoystickNumHats(conf.joy[jid])) { jmap->jhat[jid][code].player=player; jmap->jhat[jid][code].map=get_mapid(butid); } break; case 'B': if (code<SDL_JoystickNumButtons(conf.joy[jid])) { jmap->jbutton[jid][code].player=player; jmap->jbutton[jid][code].map=get_mapid(butid); } break; } } } v=strtok(NULL,","); } return GN_TRUE; } static void calculate_hotkey_bitmasks() { int *p; int i, j, mask; const char *p1_key_list[] = { "p1hotkey0", "p1hotkey1", "p1hotkey2", "p1hotkey3" }; const char *p2_key_list[] = { "p2hotkey0", "p2hotkey1", "p2hotkey2", "p2hotkey3" }; for ( i = 0; i < 4; i++ ) { p=CF_ARRAY(cf_get_item_by_name(p1_key_list[i])); for ( mask = 0, j = 0; j < 4; j++ ) mask |= p[j]; conf.p1_hotkey[i] = mask; } for ( i = 0; i < 4; i++ ) { p=CF_ARRAY(cf_get_item_by_name(p2_key_list[i])); for ( mask = 0, j = 0; j < 4; j++ ) mask |= p[j]; conf.p2_hotkey[i] = mask; } } int init_event(void) { int i; // printf("sizeof joymap=%d nb_joy=%d\n",sizeof(JOYMAP),conf.nb_joy); jmap=calloc(sizeof(JOYMAP),1); calculate_hotkey_bitmasks(); conf.nb_joy = SDL_NumJoysticks(); if( conf.nb_joy>0) { if (conf.joy!=NULL) free(conf.joy); conf.joy=calloc(sizeof(SDL_Joystick*),conf.nb_joy); SDL_JoystickEventState(SDL_ENABLE); jmap->jbutton=calloc(conf.nb_joy,sizeof(struct BUT_MAP*)); jmap->jaxe= calloc(conf.nb_joy,sizeof(struct BUT_MAPJAXIS*)); jmap->jhat= calloc(conf.nb_joy,sizeof(struct BUT_MAP*)); /* Open all the available joystick */ for (i=0;i<conf.nb_joy;i++) { conf.joy[i]=SDL_JoystickOpen(i); printf("joy \"%s\", axe:%d, button:%d\n", SDL_JoystickName(conf.joy[i]), SDL_JoystickNumAxes(conf.joy[i])+ (SDL_JoystickNumHats(conf.joy[i]) * 2), SDL_JoystickNumButtons(conf.joy[i])); jmap->jbutton[i]=calloc(SDL_JoystickNumButtons(conf.joy[i]),sizeof(struct BUT_MAP)); jmap->jaxe[i]=calloc(SDL_JoystickNumAxes(conf.joy[i]),sizeof(struct BUT_MAPJAXIS)); jmap->jhat[i]=calloc(SDL_JoystickNumHats(conf.joy[i]),sizeof(struct BUT_MAP)); } } create_joymap_from_string(1,CF_STR(cf_get_item_by_name("p1control"))); create_joymap_from_string(2,CF_STR(cf_get_item_by_name("p2control"))); return GN_TRUE; } int handle_pdep_event(SDL_Event *event) { switch (event->type) { case SDL_KEYDOWN: switch (event->key.keysym.sym) { case SDLK_ESCAPE: return 1; break; case SDLK_F3: draw_message("Test Switch ON"); conf.test_switch = 1; break; case SDLK_F12: screen_fullscreen(); break; default: break; } break; default: break; } return 0; } #define EVGAME 1 #define EVMENU 2 int handle_event(void) { SDL_Event event; // int i; int ret; int jaxis_threshold=10000; //int jaxis_threshold=2; while (SDL_PollEvent(&event)) { if ((ret=handle_pdep_event(&event))!=0) { return ret; } switch (event.type) { SDL_Keycode sym; case SDL_KEYUP: sym=event.key.keysym.sym & ~SDLK_SCANCODE_MASK; //printf("%d\n",jmap->key[event.key.keysym.sym].player); switch (jmap->key[sym].player) { case 1: joy_state[0][jmap->key[sym].map]=0; break; case 2: joy_state[1][jmap->key[sym].map]=0; break; case 3: joy_state[1][jmap->key[sym].map]=0; joy_state[0][jmap->key[sym].map]=0; break; default: break; } break; case SDL_KEYDOWN: //printf("%d\n", event.key.keysym.sym); if (event.key.repeat) { break; } sym=event.key.keysym.sym & ~SDLK_SCANCODE_MASK; switch (jmap->key[sym].player) { case 1: joy_state[0][jmap->key[sym].map]=1; break; case 2: joy_state[1][jmap->key[sym].map]=1; break; case 3: joy_state[1][jmap->key[sym].map]=1; joy_state[0][jmap->key[sym].map]=1; break; default: break; } break; case SDL_JOYHATMOTION: /* Hat only support Joystick map */ { int player=jmap->jhat[event.jhat.which][event.jhat.hat].player; int map=jmap->jhat[event.jhat.which][event.jhat.hat].map; int i; if (player && map==GN_UP) { player-=1; for(i=GN_UP;i<=GN_RIGHT;i++) joy_state[player][i]=0; if (event.jhat.value&SDL_HAT_UP) joy_state[player][GN_UP]=1; if (event.jhat.value&SDL_HAT_DOWN) joy_state[player][GN_DOWN]=1; if (event.jhat.value&SDL_HAT_LEFT) joy_state[player][GN_LEFT]=1; if (event.jhat.value&SDL_HAT_RIGHT) joy_state[player][GN_RIGHT]=1; } //printf("SDL_JOYHATMOTION %d %d %d\n",event.jhat.which, //event.jhat.hat,event.jhat.value); } break; case SDL_JOYAXISMOTION: { int player=jmap->jaxe[event.jaxis.which][event.jaxis.axis].player; int map=jmap->jaxe[event.jaxis.which][event.jaxis.axis].map; int oldvalue=jmap->jaxe[event.jaxis.which][event.jaxis.axis].value; int value=0; //if (event.jaxis.axis!=6 &&event.jaxis.axis!=7 ) // printf("Axiw motions %d %d %d\n",event.jaxis.which,event.jaxis.axis,event.jaxis.value); if (player) { player-=1; value=event.jaxis.value*jmap->jaxe[event.jaxis.which][event.jaxis.axis].dir; //printf("%d %d %d\n",player,map,value); if (map==GN_UP || map==GN_DOWN) { if (value>jaxis_threshold) { joy_state[player][GN_UP]=1; joy_state[player][GN_DOWN]=0; } if (value<-jaxis_threshold) { joy_state[player][GN_DOWN]=1; joy_state[player][GN_UP]=0; } if (oldvalue>jaxis_threshold && value<=jaxis_threshold && value>=-jaxis_threshold) joy_state[player][GN_UP]=0; if (oldvalue<-jaxis_threshold && value>=-jaxis_threshold && value<=jaxis_threshold) joy_state[player][GN_DOWN]=0; } if (map==GN_LEFT || map==GN_RIGHT) { if (value>jaxis_threshold) { joy_state[player][GN_RIGHT]=1; joy_state[player][GN_LEFT]=0; } if (value<-jaxis_threshold) { joy_state[player][GN_LEFT]=1; joy_state[player][GN_RIGHT]=0; } if (oldvalue>jaxis_threshold && value<=jaxis_threshold && value>=-jaxis_threshold) joy_state[player][GN_RIGHT]=0; if (oldvalue<-jaxis_threshold && value>=-jaxis_threshold && value<=jaxis_threshold) joy_state[player][GN_LEFT]=0; } jmap->jaxe[event.jaxis.which][event.jaxis.axis].value=value; } /* if (abs(event.jaxis.value)>jaxis_threshold) printf("SDL_JOYAXISMOTION %d %d %d %d\n",event.jaxis.which, event.jaxis.axis,value,jmap->jaxe[event.jaxis.which][event.jaxis.axis].dir); * */ } break; case SDL_JOYBUTTONDOWN: { int player=jmap->jbutton[event.jbutton.which][event.jbutton.button].player; int map=jmap->jbutton[event.jbutton.which][event.jbutton.button].map; //printf("player %d map %d\n",player,map); if (player) { player-=1; joy_state[player][map]=1; } //printf("SDL_JOYBUTTONDOWN %d %d\n",event.jbutton.which,event.jbutton.button); } break; case SDL_JOYBUTTONUP: { int player=jmap->jbutton[event.jbutton.which][event.jbutton.button].player; int map=jmap->jbutton[event.jbutton.which][event.jbutton.button].map; if (player) { player-=1; joy_state[player][map]=0; } } break; case SDL_WINDOWEVENT: { switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_SIZE_CHANGED: conf.res_x=event.window.data1; conf.res_y=event.window.data2; screen_resize(event.window.data1, event.window.data2); break; case SDL_WINDOWEVENT_CLOSE: exit(0); } } break; case SDL_QUIT: return 1; break; default: break; } } /* for(i=0;i<GN_MAX_KEY;i++) printf("%d",joy_state[0][i]); printf("|"); for(i=0;i<GN_MAX_KEY;i++) printf("%d",joy_state[1][i]); printf("\r"); */ /* Update coin data */ memory.intern_coin = 0x7; if (joy_state[0][GN_SELECT_COIN]) memory.intern_coin &= 0x6; if (joy_state[1][GN_SELECT_COIN]) memory.intern_coin &= 0x5; /* Update start data TODO: Select */ memory.intern_start = 0x8F; if (joy_state[0][GN_START]) memory.intern_start &= 0xFE; if (joy_state[1][GN_START]) memory.intern_start &= 0xFB; /* Update P1 */ memory.intern_p1 = 0xFF; if (joy_state[0][GN_UP] && (!joy_state[0][GN_DOWN])) memory.intern_p1 &= 0xFE; if (joy_state[0][GN_DOWN] && (!joy_state[0][GN_UP])) memory.intern_p1 &= 0xFD; if (joy_state[0][GN_LEFT] && (!joy_state[0][GN_RIGHT])) memory.intern_p1 &= 0xFB; if (joy_state[0][GN_RIGHT] && (!joy_state[0][GN_LEFT])) memory.intern_p1 &= 0xF7; if (joy_state[0][GN_A]) memory.intern_p1 &= 0xEF; // A if (joy_state[0][GN_B]) memory.intern_p1 &= 0xDF; // B if (joy_state[0][GN_C]) memory.intern_p1 &= 0xBF; // C if (joy_state[0][GN_D]) memory.intern_p1 &= 0x7F; // D /* Update P1 */ memory.intern_p2 = 0xFF; if (joy_state[1][GN_UP] && (!joy_state[1][GN_DOWN])) memory.intern_p2 &= 0xFE; if (joy_state[1][GN_DOWN] && (!joy_state[1][GN_UP])) memory.intern_p2 &= 0xFD; if (joy_state[1][GN_LEFT] && (!joy_state[1][GN_RIGHT])) memory.intern_p2 &= 0xFB; if (joy_state[1][GN_RIGHT] && (!joy_state[1][GN_LEFT])) memory.intern_p2 &= 0xF7; if (joy_state[1][GN_A]) memory.intern_p2 &= 0xEF; // A if (joy_state[1][GN_B]) memory.intern_p2 &= 0xDF; // B if (joy_state[1][GN_C]) memory.intern_p2 &= 0xBF; // C if (joy_state[1][GN_D]) memory.intern_p2 &= 0x7F; // D if(joy_state[0][GN_MENU_KEY]==1) return 1; else return 0; } /* int handle_event(void) { return handle_event_inter(EVGAME); } */ static int last=-1; static int counter=40; void reset_event(void) { SDL_Event event; int i; for (i = 0; i < GN_MAX_KEY; i++) joy_state[0][i] = 0; while (SDL_PollEvent(&event)); last=-1; counter=40; } int wait_event(void) { SDL_Event event; int i,a; //static int counter; //static int last=-1; //int last=-1; //for(i=0;i<GN_MAX_KEY;i++) // if (joy_state[0][i]) last=i; //SDL_WaitEvent(&event); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: /* Some default keyboard standard key */ switch (event.key.keysym.sym) { case SDLK_TAB: joy_state[0][GN_MENU_KEY]=1; //last=GN_MENU_KEY; //return GN_MENU_KEY; break; case SDLK_UP: joy_state[0][GN_UP]=1; //last=GN_UP; //return GN_UP; break; case SDLK_DOWN: joy_state[0][GN_DOWN]=1; //last=GN_DOWN; //return GN_DOWN; break; case SDLK_LEFT: joy_state[0][GN_LEFT]=1; //last=GN_LEFT; //return GN_LEFT; break; case SDLK_RIGHT: joy_state[0][GN_RIGHT]=1; //last=GN_RIGHT; //return GN_RIGHT; break; case SDLK_ESCAPE: joy_state[0][GN_A]=1; //last=GN_A; //return GN_A; break; case SDLK_RETURN: case SDLK_KP_ENTER: joy_state[0][GN_B]=1; //last=GN_B; //return GN_B; break; default: SDL_PushEvent(&event); handle_event(); break; } break; case SDL_KEYUP: //printf("KEYUPPPPP!!!\n"); for(i=0;i<GN_MAX_KEY;i++) joy_state[0][i]=0; last=-1; counter=40; break; default: SDL_PushEvent(&event); handle_event(); /* Simulate keyup */ a=0; for (i = 0; i < GN_MAX_KEY; i++) if (joy_state[0][i]) a++; if (a!=1) { for (i = 0; i < GN_MAX_KEY; i++) joy_state[0][i] = 0; last = -1; counter = 40; } break; } } /* } SDL_PushEvent(&event); handle_event(); */ if (last!=-1) { if (counter>0) counter--; if (counter==0) { counter=5; return last; } } else { for(i=0;i<GN_MAX_KEY;i++) if (joy_state[0][i]) { last=i; return i; } } /* for(i=0;i<GN_MAX_KEY;i++) if (joy_state[0][i] ) { if (i != last) { counter=30; last=i; return i; } else { counter--; if (counter==0) { counter=5; return i; } } } */ return 0; }
24.599303
93
0.624788
7ab08a4d3d96bf3198ac698fb09132197a403627
2,643
c
C
ProgrammingAssignments/openflow/lib/command-line.c
Mahdi-Asaly/Coursera-SDN-Assignments
aac5d62f40c5283e296a0f87b7ec2de8986a8efc
[ "Intel" ]
2
2018-07-16T16:01:24.000Z
2018-12-19T13:34:07.000Z
ProgrammingAssignments/openflow/lib/command-line.c
Mahdi-Asaly/Coursera-SDN-Assignments
aac5d62f40c5283e296a0f87b7ec2de8986a8efc
[ "Intel" ]
3
2018-07-13T12:47:23.000Z
2018-12-20T08:48:44.000Z
ProgrammingAssignments/openflow/lib/command-line.c
Mahdi-Asaly/Coursera-SDN-Assignments
aac5d62f40c5283e296a0f87b7ec2de8986a8efc
[ "Intel" ]
2
2021-09-02T08:25:16.000Z
2022-01-03T08:48:38.000Z
/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights 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. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ #include <config.h> #include "command-line.h" #include <getopt.h> #include <limits.h> #include "util.h" #include "vlog.h" /* Given the GNU-style long options in 'options', returns a string that may be * passed to getopt() with the corresponding short options. The caller is * responsible for freeing the string. */ char * long_options_to_short_options(const struct option options[]) { char short_options[UCHAR_MAX * 3 + 1]; char *p = short_options; for (; options->name; options++) { const struct option *o = options; if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) { *p++ = o->val; if (o->has_arg == required_argument) { *p++ = ':'; } else if (o->has_arg == optional_argument) { *p++ = ':'; *p++ = ':'; } } } *p = '\0'; return xstrdup(short_options); }
39.447761
78
0.690882
7a5d8963cc3b12634e723f819ab83b195d96db1d
889
h
C
src/common/Trek Server/trek-svc/RestServer.h
gohypergiant/payload-command-console
2444555ff634f54b5e78f38dc18c777735ef6835
[ "MIT" ]
4
2021-02-01T22:28:50.000Z
2021-08-11T23:15:17.000Z
src/common/Trek Server/trek-svc/RestServer.h
gohypergiant/payload-command-console
2444555ff634f54b5e78f38dc18c777735ef6835
[ "MIT" ]
null
null
null
src/common/Trek Server/trek-svc/RestServer.h
gohypergiant/payload-command-console
2444555ff634f54b5e78f38dc18c777735ef6835
[ "MIT" ]
null
null
null
#ifndef REST_SERVER_H #define REST_SERVER_H #include "HttpRequest.h" #include "HttpResponse.h" #include "HttpContext.h" #include <functional> #include <map> #include <string> #include <thread> #define REQUEST_BUFFER_SIZE 1024 typedef std::function<HttpResponse(const HttpContext*)> HandlerDelegate; class RestServer { private: int m_socket; int m_port; bool m_isRunning; bool m_verbose; std::map<std::string, std::map<std::string, const HandlerDelegate>> m_registeredHandlers; std::thread m_listenerThread; void ShutdownSocket(int socket); void ListenerProc(); bool ParseRequest(char* buffer, HttpRequest* request); void HandleRequest(const HttpContext* context); public: RestServer(int port, bool verbose = false); ~RestServer(); void AddHandler(std::string verb, std::string path, HandlerDelegate delegate); void Start(); void Stop(); bool IsRunning(); }; #endif
21.166667
90
0.762655
2b72a86b3e16db74a6bea7d769e64596e670865f
5,161
c
C
src/gallium/drivers/freedreno/a2xx/ir2_nir_lower_scalar.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
src/gallium/drivers/freedreno/a2xx/ir2_nir_lower_scalar.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
src/gallium/drivers/freedreno/a2xx/ir2_nir_lower_scalar.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 Jonathan Marek <jonathan@marek.ca> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Authors: * Jonathan Marek <jonathan@marek.ca> */ /* some operations can only be scalar on a2xx: * rsq, rcp, log2, exp2, cos, sin, sqrt * mostly copy-pasted from nir_lower_alu_to_scalar.c */ #include "ir2_private.h" #include "compiler/nir/nir_builder.h" static void nir_alu_ssa_dest_init(nir_alu_instr * instr, unsigned num_components, unsigned bit_size) { nir_ssa_dest_init(&instr->instr, &instr->dest.dest, num_components, bit_size, NULL); instr->dest.write_mask = (1 << num_components) - 1; } static void lower_reduction(nir_alu_instr * instr, nir_op chan_op, nir_op merge_op, nir_builder * builder) { unsigned num_components = nir_op_infos[instr->op].input_sizes[0]; nir_ssa_def *last = NULL; for (unsigned i = 0; i < num_components; i++) { nir_alu_instr *chan = nir_alu_instr_create(builder->shader, chan_op); nir_alu_ssa_dest_init(chan, 1, instr->dest.dest.ssa.bit_size); nir_alu_src_copy(&chan->src[0], &instr->src[0], chan); chan->src[0].swizzle[0] = chan->src[0].swizzle[i]; if (nir_op_infos[chan_op].num_inputs > 1) { assert(nir_op_infos[chan_op].num_inputs == 2); nir_alu_src_copy(&chan->src[1], &instr->src[1], chan); chan->src[1].swizzle[0] = chan->src[1].swizzle[i]; } chan->exact = instr->exact; nir_builder_instr_insert(builder, &chan->instr); if (i == 0) { last = &chan->dest.dest.ssa; } else { last = nir_build_alu(builder, merge_op, last, &chan->dest.dest.ssa, NULL, NULL); } } assert(instr->dest.write_mask == 1); nir_ssa_def_rewrite_uses(&instr->dest.dest.ssa, nir_src_for_ssa(last)); nir_instr_remove(&instr->instr); } static bool lower_scalar(nir_alu_instr * instr, nir_builder * b) { assert(instr->dest.dest.is_ssa); assert(instr->dest.write_mask != 0); b->cursor = nir_before_instr(&instr->instr); b->exact = instr->exact; #define LOWER_REDUCTION(name, chan, merge) \ case name##2: \ case name##3: \ case name##4: \ lower_reduction(instr, chan, merge, b); \ return true; switch (instr->op) { /* TODO: handle these instead of lowering */ LOWER_REDUCTION(nir_op_fall_equal, nir_op_seq, nir_op_fand); LOWER_REDUCTION(nir_op_fany_nequal, nir_op_sne, nir_op_for); default: return false; case nir_op_frsq: case nir_op_frcp: case nir_op_flog2: case nir_op_fexp2: case nir_op_fcos: case nir_op_fsin: case nir_op_fsqrt: break; } assert(nir_op_infos[instr->op].num_inputs == 1); unsigned num_components = instr->dest.dest.ssa.num_components; nir_ssa_def *comps[NIR_MAX_VEC_COMPONENTS] = { NULL }; unsigned chan; if (num_components == 1) return false; for (chan = 0; chan < num_components; chan++) { assert(instr->dest.write_mask & (1 << chan)); nir_alu_instr *lower = nir_alu_instr_create(b->shader, instr->op); nir_alu_src_copy(&lower->src[0], &instr->src[0], lower); lower->src[0].swizzle[0] = instr->src[0].swizzle[chan]; nir_alu_ssa_dest_init(lower, 1, instr->dest.dest.ssa.bit_size); lower->dest.saturate = instr->dest.saturate; comps[chan] = &lower->dest.dest.ssa; lower->exact = instr->exact; nir_builder_instr_insert(b, &lower->instr); } nir_ssa_def *vec = nir_vec(b, comps, num_components); nir_ssa_def_rewrite_uses(&instr->dest.dest.ssa, nir_src_for_ssa(vec)); nir_instr_remove(&instr->instr); return true; } static bool lower_scalar_impl(nir_function_impl * impl) { nir_builder builder; nir_builder_init(&builder, impl); bool progress = false; nir_foreach_block(block, impl) { nir_foreach_instr_safe(instr, block) { if (instr->type == nir_instr_type_alu) progress = lower_scalar(nir_instr_as_alu(instr), &builder) || progress; } } nir_metadata_preserve(impl, nir_metadata_block_index | nir_metadata_dominance); return progress; } bool ir2_nir_lower_scalar(nir_shader * shader) { bool progress = false; nir_foreach_function(function, shader) { if (function->impl) progress = lower_scalar_impl(function->impl) || progress; } return progress; }
29.491429
80
0.720984
4d4aaa0ef73d76bf92ee20a021dec37a362de416
14,566
h
C
itpp4.3.1-library/static-lib/include/itpp/fixed/fix_operators.h
XiaoSenLuo/c-cpp-math-library
380ef29901021ad30919127720a74c8d70f460ff
[ "BSD-2-Clause" ]
null
null
null
itpp4.3.1-library/static-lib/include/itpp/fixed/fix_operators.h
XiaoSenLuo/c-cpp-math-library
380ef29901021ad30919127720a74c8d70f460ff
[ "BSD-2-Clause" ]
null
null
null
itpp4.3.1-library/static-lib/include/itpp/fixed/fix_operators.h
XiaoSenLuo/c-cpp-math-library
380ef29901021ad30919127720a74c8d70f460ff
[ "BSD-2-Clause" ]
1
2021-12-10T09:43:54.000Z
2021-12-10T09:43:54.000Z
/*! * \file * \brief Definitions of a set of operators for Fix, Fixed, CFix and * CFixed classes * \author Johan Bergman * * ------------------------------------------------------------------------- * * Copyright (C) 1995-2010 (see AUTHORS file for a list of contributors) * * This file is part of IT++ - a C++ library of mathematical, signal * processing, speech processing, and communications classes and functions. * * IT++ is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any * later version. * * IT++ is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with IT++. If not, see <http://www.gnu.org/licenses/>. * * ------------------------------------------------------------------------- */ #ifndef FIX_OPERATORS_H #define FIX_OPERATORS_H #include <itpp/fixed/cfix.h> #include <itpp/fixed/fix_functions.h> #include <itpp/itexports.h> namespace itpp { //! \addtogroup fixed //!@{ ///////////////////////////////// // Operators for Fix and Fixed // ///////////////////////////////// //! Fix + Fix ITPP_EXPORT Fix operator+(const Fix &x, const Fix &y); //! Fix - Fix ITPP_EXPORT Fix operator-(const Fix &x, const Fix &y); //! Fix * Fix ITPP_EXPORT Fix operator*(const Fix &x, const Fix &y); //! Fix / Fix using quantization mode \c TRN ITPP_EXPORT Fix operator/(const Fix &x, const Fix &y); //! Fix + int ITPP_EXPORT Fix operator+(const Fix &x, const int y); //! Fix - int ITPP_EXPORT Fix operator-(const Fix &x, const int y); //! Fix * int ITPP_EXPORT Fix operator*(const Fix &x, const int y); //! Fix / int using quantization mode \c TRN ITPP_EXPORT Fix operator/(const Fix &x, const int y); //! int + Fix ITPP_EXPORT Fix operator+(const int x, const Fix &y); //! int - Fix ITPP_EXPORT Fix operator-(const int x, const Fix &y); //! int * Fix ITPP_EXPORT Fix operator*(const int x, const Fix &y); //! int / Fix using quantization mode \c TRN ITPP_EXPORT Fix operator/(const int x, const Fix &y); //! fixvec + int inline fixvec operator+(const fixvec &v, const int s) {return v + Fix(s);} //! int + fixvec inline fixvec operator+(const int s, const fixvec &v) {return Fix(s) + v;} //! fixvec - int inline fixvec operator-(const fixvec &v, const int s) {return v - Fix(s);} //! int - fixvec inline fixvec operator-(const int s, const fixvec &v) {return Fix(s) - v;} //! fixvec * int inline fixvec operator*(const fixvec &v, const int s) {return v * Fix(s);} //! int * fixvec inline fixvec operator*(const int s, const fixvec &v) {return Fix(s) * v;} //! fixvec / int using quantization mode \c TRN inline fixvec operator/(const fixvec &v, const int s) {return v / Fix(s);} //! fixmat + int inline fixmat operator+(const fixmat &v, const int s) {return v + Fix(s);} //! int + fixmat inline fixmat operator+(const int s, const fixmat &v) {return Fix(s) + v;} //! fixmat - int inline fixmat operator-(const fixmat &v, const int s) {return v - Fix(s);} //! int - fixmat inline fixmat operator-(const int s, const fixmat &v) {return Fix(s) - v;} //! fixmat * int inline fixmat operator*(const fixmat &v, const int s) {return v * Fix(s);} //! int * fixmat inline fixmat operator*(const int s, const fixmat &v) {return Fix(s) * v;} //! fixmat / int using quantization mode \c TRN inline fixmat operator/(const fixmat &v, const int s) {return v / Fix(s);} //! fixvec + ivec ITPP_EXPORT fixvec operator+(const fixvec &a, const ivec &b); //! ivec + fixvec inline fixvec operator+(const ivec &a, const fixvec &b) {return b + a;} //! fixvec - ivec inline fixvec operator-(const fixvec &a, const ivec &b) {return a + (-b);} //! ivec - fixvec inline fixvec operator-(const ivec &a, const fixvec &b) {return (-b) + a;} //! fixvec * ivec ITPP_EXPORT Fix operator*(const fixvec &a, const ivec &b); //! ivec * fixvec inline Fix operator*(const ivec &a, const fixvec &b) {return b*a;} //! fixmat + imat ITPP_EXPORT fixmat operator+(const fixmat &a, const imat &b); //! imat + fixmat inline fixmat operator+(const imat &a, const fixmat &b) {return b + a;} //! fixmat - imat inline fixmat operator-(const fixmat &a, const imat &b) {return a + (-b);} //! imat - fixmat inline fixmat operator-(const imat &a, const fixmat &b) {return (-b) + a;} //! fixmat * imat ITPP_EXPORT fixmat operator*(const fixmat &a, const imat &b); //! imat * fixmat inline fixmat operator*(const imat &a, const fixmat &b) {return b*a;} /////////////////////////////////// // Operators for CFix and CFixed // /////////////////////////////////// //! CFix + CFix ITPP_EXPORT CFix operator+(const CFix &x, const CFix &y); //! CFix - CFix ITPP_EXPORT CFix operator-(const CFix &x, const CFix &y); //! CFix * CFix ITPP_EXPORT CFix operator*(const CFix &x, const CFix &y); //! CFix / CFix using quantization mode \c TRN ITPP_EXPORT CFix operator/(const CFix &x, const CFix &y); //! CFix + Fix ITPP_EXPORT CFix operator+(const CFix &x, const Fix &y); //! CFix - Fix ITPP_EXPORT CFix operator-(const CFix &x, const Fix &y); //! CFix * Fix ITPP_EXPORT CFix operator*(const CFix &x, const Fix &y); //! CFix / Fix using quantization mode \c TRN ITPP_EXPORT CFix operator/(const CFix &x, const Fix &y); //! Fix + CFix ITPP_EXPORT CFix operator+(const Fix &x, const CFix &y); //! Fix - CFix ITPP_EXPORT CFix operator-(const Fix &x, const CFix &y); //! Fix * CFix ITPP_EXPORT CFix operator*(const Fix &x, const CFix &y); //! Fix / CFix using quantization mode \c TRN ITPP_EXPORT CFix operator/(const Fix &x, const CFix &y); //! CFix + int ITPP_EXPORT CFix operator+(const CFix &x, const int y); //! CFix - int ITPP_EXPORT CFix operator-(const CFix &x, const int y); //! CFix * int ITPP_EXPORT CFix operator*(const CFix &x, const int y); //! CFix / int using quantization mode \c TRN ITPP_EXPORT CFix operator/(const CFix &x, const int y); //! int + CFix ITPP_EXPORT CFix operator+(const int x, const CFix &y); //! int - CFix ITPP_EXPORT CFix operator-(const int x, const CFix &y); //! int * CFix ITPP_EXPORT CFix operator*(const int x, const CFix &y); //! int / CFix using quantization mode \c TRN ITPP_EXPORT CFix operator/(const int x, const CFix &y); //! fixvec + CFix inline cfixvec operator+(const fixvec &v, const CFix &s) {return to<CFix>(v) + s;} //! CFix + fixvec inline cfixvec operator+(const CFix &s, const fixvec &v) {return s + to<CFix>(v);} //! fixvec - CFix inline cfixvec operator-(const fixvec &v, const CFix &s) {return to<CFix>(v) - s;} //! CFix - fixvec inline cfixvec operator-(const CFix &s, const fixvec &v) {return s - to<CFix>(v);} //! fixvec * CFix inline cfixvec operator*(const fixvec &v, const CFix &s) {return to<CFix>(v) * s;} //! CFix * fixvec inline cfixvec operator*(const CFix &s, const fixvec &v) {return s * to<CFix>(v);} //! fixvec / CFix using quantization mode \c TRN inline cfixvec operator/(const fixvec &v, const CFix &s) {return to<CFix>(v) / s;} //! fixmat + CFix inline cfixmat operator+(const fixmat &m, const CFix &s) {return to<CFix>(m) + s;} //! CFix + fixmat inline cfixmat operator+(const CFix &s, const fixmat &m) {return s + to<CFix>(m);} //! fixmat - CFix inline cfixmat operator-(const fixmat &m, const CFix &s) {return to<CFix>(m) - s;} //! CFix - fixmat inline cfixmat operator-(const CFix &s, const fixmat &m) {return s - to<CFix>(m);} //! fixmat * CFix inline cfixmat operator*(const fixmat &m, const CFix &s) {return to<CFix>(m) * s;} //! CFix * fixmat inline cfixmat operator*(const CFix &s, const fixmat &m) {return s * to<CFix>(m);} //! fixmat / CFix using quantization mode \c TRN inline cfixmat operator/(const fixmat &m, const CFix &s) {return to<CFix>(m) / s;} //! ivec + CFix inline cfixvec operator+(const ivec &v, const CFix &s) {return to<CFix>(to_vec(v)) + s;} //! CFix + ivec inline cfixvec operator+(const CFix &s, const ivec &v) {return s + to<CFix>(to_vec(v));} //! ivec - CFix inline cfixvec operator-(const ivec &v, const CFix &s) {return to<CFix>(to_vec(v)) - s;} //! CFix - ivec inline cfixvec operator-(const CFix &s, const ivec &v) {return s - to<CFix>(to_vec(v));} //! ivec * CFix inline cfixvec operator*(const ivec &v, const CFix &s) {return to<CFix>(to_vec(v)) * s;} //! CFix * ivec inline cfixvec operator*(const CFix &s, const ivec &v) {return s * to<CFix>(to_vec(v));} //! ivec / CFix using quantization mode \c TRN inline cfixvec operator/(const ivec &v, const CFix &s) {return to<CFix>(to_vec(v)) / s;} //! imat + CFix inline cfixmat operator+(const imat &m, const CFix &s) {return to<CFix>(to_mat(m)) + s;} //! CFix + imat inline cfixmat operator+(const CFix &s, const imat &m) {return s + to<CFix>(to_mat(m));} //! imat - CFix inline cfixmat operator-(const imat &m, const CFix &s) {return to<CFix>(to_mat(m)) - s;} //! CFix - imat inline cfixmat operator-(const CFix &s, const imat &m) {return s - to<CFix>(to_mat(m));} //! imat * CFix inline cfixmat operator*(const imat &m, const CFix &s) {return to<CFix>(to_mat(m)) * s;} //! CFix * imat inline cfixmat operator*(const CFix &s, const imat &m) {return s * to<CFix>(to_mat(m));} //! imat / CFix using quantization mode \c TRN inline cfixmat operator/(const imat &m, const CFix &s) {return to<CFix>(to_mat(m)) / s;} //! cfixvec + Fix inline cfixvec operator+(const cfixvec &v, const Fix &s) {return v + CFix(s);} //! Fix + cfixvec inline cfixvec operator+(const Fix &s, const cfixvec &v) {return CFix(s) + v;} //! cfixvec - Fix inline cfixvec operator-(const cfixvec &v, const Fix &s) {return v - CFix(s);} //! Fix - cfixvec inline cfixvec operator-(const Fix &s, const cfixvec &v) {return CFix(s) - v;} //! cfixvec * Fix inline cfixvec operator*(const cfixvec &v, const Fix &s) {return v * CFix(s);} //! Fix * cfixvec inline cfixvec operator*(const Fix &s, const cfixvec &v) {return CFix(s) * v;} //! cfixvec / Fix using quantization mode \c TRN inline cfixvec operator/(const cfixvec &v, const Fix &s) {return v / CFix(s);} //! cfixmat + Fix inline cfixmat operator+(const cfixmat &m, const Fix &s) {return m + CFix(s);} //! Fix + cfixmat inline cfixmat operator+(const Fix &s, const cfixmat &m) {return CFix(s) + m;} //! cfixmat - Fix inline cfixmat operator-(const cfixmat &m, const Fix &s) {return m - CFix(s);} //! Fix - cfixmat inline cfixmat operator-(const Fix &s, const cfixmat &m) {return CFix(s) - m;} //! cfixmat * Fix inline cfixmat operator*(const cfixmat &m, const Fix &s) {return m * CFix(s);} //! Fix * cfixmat inline cfixmat operator*(const Fix &s, const cfixmat &m) {return CFix(s) * m;} //! cfixmat / Fix using quantization mode \c TRN inline cfixmat operator/(const cfixmat &m, const Fix &s) {return m / CFix(s);} //! cfixvec + int inline cfixvec operator+(const cfixvec &v, const int s) {return v + CFix(s);} //! int + cfixvec inline cfixvec operator+(const int s, const cfixvec &v) {return CFix(s) + v;} //! cfixvec - int inline cfixvec operator-(const cfixvec &v, const int s) {return v - CFix(s);} //! int - cfixvec inline cfixvec operator-(const int s, const cfixvec &v) {return CFix(s) - v;} //! cfixvec * int inline cfixvec operator*(const cfixvec &v, const int s) {return v * CFix(s);} //! int * cfixvec inline cfixvec operator*(const int s, const cfixvec &v) {return CFix(s) * v;} //! cfixvec / int using quantization mode \c TRN inline cfixvec operator/(const cfixvec &v, const int s) {return v / CFix(s);} //! cfixmat + int inline cfixmat operator+(const cfixmat &m, const int s) {return m + CFix(s);} //! int + cfixmat inline cfixmat operator+(const int s, const cfixmat &m) {return CFix(s) + m;} //! cfixmat - int inline cfixmat operator-(const cfixmat &m, const int s) {return m - CFix(s);} //! int - cfixmat inline cfixmat operator-(const int s, const cfixmat &m) {return CFix(s) - m;} //! cfixmat * int inline cfixmat operator*(const cfixmat &m, const int s) {return m * CFix(s);} //! int * cfixmat inline cfixmat operator*(const int s, const cfixmat &m) {return CFix(s) * m;} //! cfixmat / int using quantization mode \c TRN inline cfixmat operator/(const cfixmat &m, const int s) {return m / CFix(s);} //! cfixvec + fixvec ITPP_EXPORT cfixvec operator+(const cfixvec &a, const fixvec &b); //! fixvec + cfixvec inline cfixvec operator+(const fixvec &a, const cfixvec &b) {return b + a;} //! cfixvec - fixvec inline cfixvec operator-(const cfixvec &a, const fixvec &b) {return a + (-b);} //! fixvec - cfixvec inline cfixvec operator-(const fixvec &a, const cfixvec &b) {return (-b) + a;} //! cfixvec * fixvec ITPP_EXPORT CFix operator*(const cfixvec &a, const fixvec &b); //! fixvec * cfixvec inline CFix operator*(const fixvec &a, const cfixvec &b) {return b*a;} //! cfixmat + fixmat ITPP_EXPORT cfixmat operator+(const cfixmat &a, const fixmat &b); //! fixmat + cfixmat inline cfixmat operator+(const fixmat &a, const cfixmat &b) {return b + a;} //! cfixmat - fixmat inline cfixmat operator-(const cfixmat &a, const fixmat &b) {return a + (-b);} //! fixmat - cfixmat inline cfixmat operator-(const fixmat &a, const cfixmat &b) {return (-b) + a;} //! cfixmat * fixmat ITPP_EXPORT cfixmat operator*(const cfixmat &a, const fixmat &b); //! fixmat * cfixmat inline cfixmat operator*(const fixmat &a, const cfixmat &b) {return b*a;} //! cfixvec + ivec ITPP_EXPORT cfixvec operator+(const cfixvec &a, const ivec &b); //! ivec + cfixvec inline cfixvec operator+(const ivec &a, const cfixvec &b) {return b + a;} //! cfixvec - ivec inline cfixvec operator-(const cfixvec &a, const ivec &b) {return a + (-b);} //! ivec - cfixvec inline cfixvec operator-(const ivec &a, const cfixvec &b) {return (-b) + a;} //! cfixvec * ivec ITPP_EXPORT CFix operator*(const cfixvec &a, const ivec &b); //! ivec * cfixvec inline CFix operator*(const ivec &a, const cfixvec &b) {return b*a;} //! cfixmat + imat ITPP_EXPORT cfixmat operator+(const cfixmat &a, const imat &b); //! imat + cfixmat inline cfixmat operator+(const imat &a, const cfixmat &b) {return b + a;} //! cfixmat - imat inline cfixmat operator-(const cfixmat &a, const imat &b) {return a + (-b);} //! imat - cfixmat inline cfixmat operator-(const imat &a, const cfixmat &b) {return (-b) + a;} //! cfixmat * imat ITPP_EXPORT cfixmat operator*(const cfixmat &a, const imat &b); //! imat * cfixmat inline cfixmat operator*(const imat &a, const cfixmat &b) {return b*a;} //!@} } // namespace itpp #endif // #ifndef FIX_OPERATORS_H
41.146893
88
0.668063
9e8d3ae06dcec129b3b5764d489ba77cd002bc02
1,458
h
C
lib/sonar.h
MightyPork/avr-7seg-shiftreg-mux
9424a8bf38ded92d48df015fae9699d4c351ecda
[ "MIT" ]
5
2015-05-01T22:38:29.000Z
2018-11-06T07:20:02.000Z
lib/sonar.h
MightyPork/avr-7seg-shiftreg-mux
9424a8bf38ded92d48df015fae9699d4c351ecda
[ "MIT" ]
null
null
null
lib/sonar.h
MightyPork/avr-7seg-shiftreg-mux
9424a8bf38ded92d48df015fae9699d4c351ecda
[ "MIT" ]
6
2015-05-01T22:38:31.000Z
2018-06-08T14:48:45.000Z
#pragma once // // Utilities for working with the HC-SR04 ultrasonic sensor // Can be easily modified to work with other similar modules // // It's required that you call the sonar_handle_* functions from your ISRs // See example program for more info. // #include <stdint.h> #include <stdbool.h> #include "iopins.h" // Calib constant for the module // CM = uS / _DIV_CONST #define _SNR_DIV_CONST 58 // Max module distance in MM #define _SNR_MAX_DIST 4000 // Trigger time in uS #define _SNR_TRIG_TIME 10 // Sonar data object typedef struct { PORT_P port; // Tx PORT uint8_t ntx; // Tx bit number PORT_P pin; // Rx PIN uint8_t nrx; // Rx bit number uint8_t bank; // Rx PCINT bank } sonar_t; extern volatile bool sonar_busy; extern volatile int16_t sonar_result; // Create a Sonar port // Args: sonar_t* so, Trig pin, Echo pin #define sonar_init(so, trig, echo) do { \ as_output(trig); \ as_input_pu(echo); \ _sonar_init_do(so, &_port(trig), _pn(trig), &_pin(echo), _pn(echo)); \ } while(0) // private, in header because of the macro. void _sonar_init_do(sonar_t* so, PORT_P port, uint8_t ntx, PORT_P pin, uint8_t nrx); /** * Start sonar measurement * Interrupts must be enabled * TIMER 1 will be used for the async measurement */ bool sonar_start(sonar_t* so); /** Handle TIMER1_OVF (returns true if consumed) */ bool sonar_handle_t1ovf(); /** Handle pin change interrupt (returns true if consumed) */ bool sonar_handle_pci();
21.441176
84
0.718793
3668c914325db01613d658ab79a4115d7da04d0f
2,766
h
C
aadcUser/src/KACADU_USView/USView.h
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
11
2016-04-30T14:55:20.000Z
2020-06-04T21:13:31.000Z
aadcUser/src/KACADU_USView/USView.h
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
null
null
null
aadcUser/src/KACADU_USView/USView.h
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
8
2016-04-30T14:58:18.000Z
2019-12-27T10:37:53.000Z
/** * * ADTF Template Project Filter. * * @file * Copyright &copy; Audi Electronics Venture GmbH. All rights reserved * * $Author: belkera $ * $Date: 2011-06-30 16:51:21 +0200 (Do, 30 Jun 2011) $ * $Revision: 26514 $ * * @remarks * */ #ifndef _US_VIEW_FILTER_H_ #define _US_VIEW_FILTER_H_ #include <oadrive_control/LateralController.h> #include <oadrive_core/Types.h> #include <oadrive_core/Trajectory2d.h> #include <oadrive_core/Interpolator.h> #include <oadrive_util/ConvertUs.h> #include <oadrive_util/BirdViewPosConv.h> #include <oadrive_core/ExtendedPose2d.h> #include <oadrive_world/ObjectFusion.h> #include <oadrive_world/EnvironmentDummy.h> #include <oadrive_core/Pose.h> #include <oadrive_world/EnvOctoMap.h> #include "stdafx.h" #define OID_ADTF_KACADU_USView "adtf.util.USView_filter" using namespace oadrive::world; //************************************************************************************************* class cUSViewFilter : public adtf::cFilter { ADTF_FILTER(OID_ADTF_KACADU_USView, "KACADU US View", adtf::OBJCAT_DataFilter); public: cUSViewFilter(const tChar* __info); virtual ~cUSViewFilter(); protected: tResult Init(tInitStage eStage, __exception); tResult Shutdown(tInitStage eStage, __exception); tResult transmitSpeed(cOutputPin & pin, tFloat32 value, tUInt32 timeStamp); // implements IPinEventSink tResult OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample); cInputPin mUltraInput; /*! descriptor for ultrasonic sensor data */ cObjectPtr<IMediaTypeDescription> mUltraInDescription; //Car Postion input adtf::cInputPin mPinPositionInput; cObjectPtr<IMediaTypeDescription> mPositionDescription; //visualisation Output adtf::cOutputPin mPinDrawPositionOutput; cObjectPtr<IMediaTypeDescription> mDrawPositionDescription; private: tResult sendDebugPoint( cv::Point2f pos, cv::Scalar color, float seconds ); oadrive::util::ConvertUs mConvertUs; oadrive::util::BirdViewPosConv mConvertCar; oadrive::core::ExtendedPose2d mCarPos; EnvironmentDummy mEnviroment; ObjectFusion mFusion; EnvOctoMap mEnvOcto; bool mIDsDrawPositionSet; tBufferID mSignalIDx; tBufferID mSignalIDy; tBufferID mSignalIDseconds; tBufferID mSignalIDred; tBufferID mSignalIDgreen; tBufferID mSignalIDblue; tTimeStamp mLastTime; int mSampleCount; }; //************************************************************************************************* #endif // _US_VIEW_FILTER_H_
30.395604
100
0.652205
9a4bfb4e63e34f797308d503ba35c7149ffd6fce
15,065
c
C
arch/mips/pci/pci-ar2315.c
jainsakshi2395/linux
7ccb860232bb83fb60cd6bcf5aaf0c008d903acb
[ "Linux-OpenIB" ]
1
2022-03-31T03:23:42.000Z
2022-03-31T03:23:42.000Z
arch/mips/pci/pci-ar2315.c
jainsakshi2395/linux
7ccb860232bb83fb60cd6bcf5aaf0c008d903acb
[ "Linux-OpenIB" ]
1
2021-01-27T01:29:47.000Z
2021-01-27T01:29:47.000Z
arch/mips/pci/pci-ar2315.c
jainsakshi2395/linux
7ccb860232bb83fb60cd6bcf5aaf0c008d903acb
[ "Linux-OpenIB" ]
null
null
null
// SPDX-License-Identifier: GPL-2.0-or-later /* */ /** * Both AR2315 and AR2316 chips have PCI interface unit, which supports DMA * and interrupt. PCI interface supports MMIO access method, but does not * seem to support I/O ports. * * Read/write operation in the region 0x80000000-0xBFFFFFFF causes * a memory read/write command on the PCI bus. 30 LSBs of address on * the bus are taken from memory read/write request and 2 MSBs are * determined by PCI unit configuration. * * To work with the configuration space instead of memory is necessary set * the CFG_SEL bit in the PCI_MISC_CONFIG register. * * Devices on the bus can perform DMA requests via chip BAR1. PCI host * controller BARs are programmend as if an external device is programmed. * Which means that during configuration, IDSEL pin of the chip should be * asserted. * * We know (and support) only one board that uses the PCI interface - * Fonera 2.0g (FON2202). It has a USB EHCI controller connected to the * AR2315 PCI bus. IDSEL pin of USB controller is connected to AD[13] line * and IDSEL pin of AR2315 is connected to AD[16] line. */ #include <linux/types.h> #include <linux/pci.h> #include <linux/platform_device.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/dma-direct.h> #include <linux/mm.h> #include <linux/delay.h> #include <linux/bitops.h> #include <linux/irq.h> #include <linux/irqdomain.h> #include <linux/io.h> #include <asm/paccess.h> /* * PCI Bus Interface Registers */ #define AR2315_PCI_1MS_REG 0x0008 #define AR2315_PCI_1MS_MASK 0x3FFFF /* # of AHB clk cycles in 1ms */ #define AR2315_PCI_MISC_CONFIG 0x000c #define AR2315_PCIMISC_TXD_EN 0x00000001 /* Enable TXD for fragments */ #define AR2315_PCIMISC_CFG_SEL 0x00000002 /* Mem or Config cycles */ #define AR2315_PCIMISC_GIG_MASK 0x0000000C /* bits 31-30 for pci req */ #define AR2315_PCIMISC_RST_MODE 0x00000030 #define AR2315_PCIRST_INPUT 0x00000000 /* 4:5=0 rst is input */ #define AR2315_PCIRST_LOW 0x00000010 /* 4:5=1 rst to GND */ #define AR2315_PCIRST_HIGH 0x00000020 /* 4:5=2 rst to VDD */ #define AR2315_PCIGRANT_EN 0x00000000 /* 6:7=0 early grant en */ #define AR2315_PCIGRANT_FRAME 0x00000040 /* 6:7=1 grant waits 4 frame */ #define AR2315_PCIGRANT_IDLE 0x00000080 /* 6:7=2 grant waits 4 idle */ #define AR2315_PCIGRANT_GAP 0x00000000 /* 6:7=2 grant waits 4 idle */ #define AR2315_PCICACHE_DIS 0x00001000 /* PCI external access cache * disable */ #define AR2315_PCI_OUT_TSTAMP 0x0010 #define AR2315_PCI_UNCACHE_CFG 0x0014 #define AR2315_PCI_IN_EN 0x0100 #define AR2315_PCI_IN_EN0 0x01 /* Enable chain 0 */ #define AR2315_PCI_IN_EN1 0x02 /* Enable chain 1 */ #define AR2315_PCI_IN_EN2 0x04 /* Enable chain 2 */ #define AR2315_PCI_IN_EN3 0x08 /* Enable chain 3 */ #define AR2315_PCI_IN_DIS 0x0104 #define AR2315_PCI_IN_DIS0 0x01 /* Disable chain 0 */ #define AR2315_PCI_IN_DIS1 0x02 /* Disable chain 1 */ #define AR2315_PCI_IN_DIS2 0x04 /* Disable chain 2 */ #define AR2315_PCI_IN_DIS3 0x08 /* Disable chain 3 */ #define AR2315_PCI_IN_PTR 0x0200 #define AR2315_PCI_OUT_EN 0x0400 #define AR2315_PCI_OUT_EN0 0x01 /* Enable chain 0 */ #define AR2315_PCI_OUT_DIS 0x0404 #define AR2315_PCI_OUT_DIS0 0x01 /* Disable chain 0 */ #define AR2315_PCI_OUT_PTR 0x0408 /* PCI interrupt status (write one to clear) */ #define AR2315_PCI_ISR 0x0500 #define AR2315_PCI_INT_TX 0x00000001 /* Desc In Completed */ #define AR2315_PCI_INT_TXOK 0x00000002 /* Desc In OK */ #define AR2315_PCI_INT_TXERR 0x00000004 /* Desc In ERR */ #define AR2315_PCI_INT_TXEOL 0x00000008 /* Desc In End-of-List */ #define AR2315_PCI_INT_RX 0x00000010 /* Desc Out Completed */ #define AR2315_PCI_INT_RXOK 0x00000020 /* Desc Out OK */ #define AR2315_PCI_INT_RXERR 0x00000040 /* Desc Out ERR */ #define AR2315_PCI_INT_RXEOL 0x00000080 /* Desc Out EOL */ #define AR2315_PCI_INT_TXOOD 0x00000200 /* Desc In Out-of-Desc */ #define AR2315_PCI_INT_DESCMASK 0x0000FFFF /* Desc Mask */ #define AR2315_PCI_INT_EXT 0x02000000 /* Extern PCI INTA */ #define AR2315_PCI_INT_ABORT 0x04000000 /* PCI bus abort event */ /* PCI interrupt mask */ #define AR2315_PCI_IMR 0x0504 /* Global PCI interrupt enable */ #define AR2315_PCI_IER 0x0508 #define AR2315_PCI_IER_DISABLE 0x00 /* disable pci interrupts */ #define AR2315_PCI_IER_ENABLE 0x01 /* enable pci interrupts */ #define AR2315_PCI_HOST_IN_EN 0x0800 #define AR2315_PCI_HOST_IN_DIS 0x0804 #define AR2315_PCI_HOST_IN_PTR 0x0810 #define AR2315_PCI_HOST_OUT_EN 0x0900 #define AR2315_PCI_HOST_OUT_DIS 0x0904 #define AR2315_PCI_HOST_OUT_PTR 0x0908 /* * PCI interrupts, which share IP5 * Keep ordered according to AR2315_PCI_INT_XXX bits */ #define AR2315_PCI_IRQ_EXT 25 #define AR2315_PCI_IRQ_ABORT 26 #define AR2315_PCI_IRQ_COUNT 27 /* Arbitrary size of memory region to access the configuration space */ #define AR2315_PCI_CFG_SIZE 0x00100000 #define AR2315_PCI_HOST_SLOT 3 #define AR2315_PCI_HOST_DEVID ((0xff18 << 16) | PCI_VENDOR_ID_ATHEROS) /* * We need some arbitrary non-zero value to be programmed to the BAR1 register * of PCI host controller to enable DMA. The same value should be used as the * offset to calculate the physical address of DMA buffer for PCI devices. */ #define AR2315_PCI_HOST_SDRAM_BASEADDR 0x20000000 /* ??? access BAR */ #define AR2315_PCI_HOST_MBAR0 0x10000000 /* RAM access BAR */ #define AR2315_PCI_HOST_MBAR1 AR2315_PCI_HOST_SDRAM_BASEADDR /* ??? access BAR */ #define AR2315_PCI_HOST_MBAR2 0x30000000 struct ar2315_pci_ctrl { void __iomem *cfg_mem; void __iomem *mmr_mem; unsigned irq; unsigned irq_ext; struct irq_domain *domain; struct pci_controller pci_ctrl; struct resource mem_res; struct resource io_res; }; static inline dma_addr_t ar2315_dev_offset(struct device *dev) { if (dev && dev_is_pci(dev)) return AR2315_PCI_HOST_SDRAM_BASEADDR; return 0; } dma_addr_t phys_to_dma(struct device *dev, phys_addr_t paddr) { return paddr + ar2315_dev_offset(dev); } phys_addr_t dma_to_phys(struct device *dev, dma_addr_t dma_addr) { return dma_addr - ar2315_dev_offset(dev); } static inline struct ar2315_pci_ctrl *ar2315_pci_bus_to_apc(struct pci_bus *bus) { struct pci_controller *hose = bus->sysdata; return container_of(hose, struct ar2315_pci_ctrl, pci_ctrl); } static inline u32 ar2315_pci_reg_read(struct ar2315_pci_ctrl *apc, u32 reg) { return __raw_readl(apc->mmr_mem + reg); } static inline void ar2315_pci_reg_write(struct ar2315_pci_ctrl *apc, u32 reg, u32 val) { __raw_writel(val, apc->mmr_mem + reg); } static inline void ar2315_pci_reg_mask(struct ar2315_pci_ctrl *apc, u32 reg, u32 mask, u32 val) { u32 ret = ar2315_pci_reg_read(apc, reg); ret &= ~mask; ret |= val; ar2315_pci_reg_write(apc, reg, ret); } static int ar2315_pci_cfg_access(struct ar2315_pci_ctrl *apc, unsigned devfn, int where, int size, u32 *ptr, bool write) { int func = PCI_FUNC(devfn); int dev = PCI_SLOT(devfn); u32 addr = (1 << (13 + dev)) | (func << 8) | (where & ~3); u32 mask = 0xffffffff >> 8 * (4 - size); u32 sh = (where & 3) * 8; u32 value, isr; /* Prevent access past the remapped area */ if (addr >= AR2315_PCI_CFG_SIZE || dev > 18) return PCIBIOS_DEVICE_NOT_FOUND; /* Clear pending errors */ ar2315_pci_reg_write(apc, AR2315_PCI_ISR, AR2315_PCI_INT_ABORT); /* Select Configuration access */ ar2315_pci_reg_mask(apc, AR2315_PCI_MISC_CONFIG, 0, AR2315_PCIMISC_CFG_SEL); mb(); /* PCI must see space change before we begin */ value = __raw_readl(apc->cfg_mem + addr); isr = ar2315_pci_reg_read(apc, AR2315_PCI_ISR); if (isr & AR2315_PCI_INT_ABORT) goto exit_err; if (write) { value = (value & ~(mask << sh)) | *ptr << sh; __raw_writel(value, apc->cfg_mem + addr); isr = ar2315_pci_reg_read(apc, AR2315_PCI_ISR); if (isr & AR2315_PCI_INT_ABORT) goto exit_err; } else { *ptr = (value >> sh) & mask; } goto exit; exit_err: ar2315_pci_reg_write(apc, AR2315_PCI_ISR, AR2315_PCI_INT_ABORT); if (!write) *ptr = 0xffffffff; exit: /* Select Memory access */ ar2315_pci_reg_mask(apc, AR2315_PCI_MISC_CONFIG, AR2315_PCIMISC_CFG_SEL, 0); return isr & AR2315_PCI_INT_ABORT ? PCIBIOS_DEVICE_NOT_FOUND : PCIBIOS_SUCCESSFUL; } static inline int ar2315_pci_local_cfg_rd(struct ar2315_pci_ctrl *apc, unsigned devfn, int where, u32 *val) { return ar2315_pci_cfg_access(apc, devfn, where, sizeof(u32), val, false); } static inline int ar2315_pci_local_cfg_wr(struct ar2315_pci_ctrl *apc, unsigned devfn, int where, u32 val) { return ar2315_pci_cfg_access(apc, devfn, where, sizeof(u32), &val, true); } static int ar2315_pci_cfg_read(struct pci_bus *bus, unsigned devfn, int where, int size, u32 *value) { struct ar2315_pci_ctrl *apc = ar2315_pci_bus_to_apc(bus); if (PCI_SLOT(devfn) == AR2315_PCI_HOST_SLOT) return PCIBIOS_DEVICE_NOT_FOUND; return ar2315_pci_cfg_access(apc, devfn, where, size, value, false); } static int ar2315_pci_cfg_write(struct pci_bus *bus, unsigned devfn, int where, int size, u32 value) { struct ar2315_pci_ctrl *apc = ar2315_pci_bus_to_apc(bus); if (PCI_SLOT(devfn) == AR2315_PCI_HOST_SLOT) return PCIBIOS_DEVICE_NOT_FOUND; return ar2315_pci_cfg_access(apc, devfn, where, size, &value, true); } static struct pci_ops ar2315_pci_ops = { .read = ar2315_pci_cfg_read, .write = ar2315_pci_cfg_write, }; static int ar2315_pci_host_setup(struct ar2315_pci_ctrl *apc) { unsigned devfn = PCI_DEVFN(AR2315_PCI_HOST_SLOT, 0); int res; u32 id; res = ar2315_pci_local_cfg_rd(apc, devfn, PCI_VENDOR_ID, &id); if (res != PCIBIOS_SUCCESSFUL || id != AR2315_PCI_HOST_DEVID) return -ENODEV; /* Program MBARs */ ar2315_pci_local_cfg_wr(apc, devfn, PCI_BASE_ADDRESS_0, AR2315_PCI_HOST_MBAR0); ar2315_pci_local_cfg_wr(apc, devfn, PCI_BASE_ADDRESS_1, AR2315_PCI_HOST_MBAR1); ar2315_pci_local_cfg_wr(apc, devfn, PCI_BASE_ADDRESS_2, AR2315_PCI_HOST_MBAR2); /* Run */ ar2315_pci_local_cfg_wr(apc, devfn, PCI_COMMAND, PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_SPECIAL | PCI_COMMAND_INVALIDATE | PCI_COMMAND_PARITY | PCI_COMMAND_SERR | PCI_COMMAND_FAST_BACK); return 0; } static void ar2315_pci_irq_handler(struct irq_desc *desc) { struct ar2315_pci_ctrl *apc = irq_desc_get_handler_data(desc); u32 pending = ar2315_pci_reg_read(apc, AR2315_PCI_ISR) & ar2315_pci_reg_read(apc, AR2315_PCI_IMR); int ret = 0; if (pending) ret = generic_handle_domain_irq(apc->domain, __ffs(pending)); if (!pending || ret) spurious_interrupt(); } static void ar2315_pci_irq_mask(struct irq_data *d) { struct ar2315_pci_ctrl *apc = irq_data_get_irq_chip_data(d); ar2315_pci_reg_mask(apc, AR2315_PCI_IMR, BIT(d->hwirq), 0); } static void ar2315_pci_irq_mask_ack(struct irq_data *d) { struct ar2315_pci_ctrl *apc = irq_data_get_irq_chip_data(d); u32 m = BIT(d->hwirq); ar2315_pci_reg_mask(apc, AR2315_PCI_IMR, m, 0); ar2315_pci_reg_write(apc, AR2315_PCI_ISR, m); } static void ar2315_pci_irq_unmask(struct irq_data *d) { struct ar2315_pci_ctrl *apc = irq_data_get_irq_chip_data(d); ar2315_pci_reg_mask(apc, AR2315_PCI_IMR, 0, BIT(d->hwirq)); } static struct irq_chip ar2315_pci_irq_chip = { .name = "AR2315-PCI", .irq_mask = ar2315_pci_irq_mask, .irq_mask_ack = ar2315_pci_irq_mask_ack, .irq_unmask = ar2315_pci_irq_unmask, }; static int ar2315_pci_irq_map(struct irq_domain *d, unsigned irq, irq_hw_number_t hw) { irq_set_chip_and_handler(irq, &ar2315_pci_irq_chip, handle_level_irq); irq_set_chip_data(irq, d->host_data); return 0; } static struct irq_domain_ops ar2315_pci_irq_domain_ops = { .map = ar2315_pci_irq_map, }; static void ar2315_pci_irq_init(struct ar2315_pci_ctrl *apc) { ar2315_pci_reg_mask(apc, AR2315_PCI_IER, AR2315_PCI_IER_ENABLE, 0); ar2315_pci_reg_mask(apc, AR2315_PCI_IMR, (AR2315_PCI_INT_ABORT | AR2315_PCI_INT_EXT), 0); apc->irq_ext = irq_create_mapping(apc->domain, AR2315_PCI_IRQ_EXT); irq_set_chained_handler_and_data(apc->irq, ar2315_pci_irq_handler, apc); /* Clear any pending Abort or external Interrupts * and enable interrupt processing */ ar2315_pci_reg_write(apc, AR2315_PCI_ISR, AR2315_PCI_INT_ABORT | AR2315_PCI_INT_EXT); ar2315_pci_reg_mask(apc, AR2315_PCI_IER, 0, AR2315_PCI_IER_ENABLE); } static int ar2315_pci_probe(struct platform_device *pdev) { struct ar2315_pci_ctrl *apc; struct device *dev = &pdev->dev; struct resource *res; int irq, err; apc = devm_kzalloc(dev, sizeof(*apc), GFP_KERNEL); if (!apc) return -ENOMEM; irq = platform_get_irq(pdev, 0); if (irq < 0) return -EINVAL; apc->irq = irq; apc->mmr_mem = devm_platform_ioremap_resource_byname(pdev, "ar2315-pci-ctrl"); if (IS_ERR(apc->mmr_mem)) return PTR_ERR(apc->mmr_mem); res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "ar2315-pci-ext"); if (!res) return -EINVAL; apc->mem_res.name = "AR2315 PCI mem space"; apc->mem_res.parent = res; apc->mem_res.start = res->start; apc->mem_res.end = res->end; apc->mem_res.flags = IORESOURCE_MEM; /* Remap PCI config space */ apc->cfg_mem = devm_ioremap(dev, res->start, AR2315_PCI_CFG_SIZE); if (!apc->cfg_mem) { dev_err(dev, "failed to remap PCI config space\n"); return -ENOMEM; } /* Reset the PCI bus by setting bits 5-4 in PCI_MCFG */ ar2315_pci_reg_mask(apc, AR2315_PCI_MISC_CONFIG, AR2315_PCIMISC_RST_MODE, AR2315_PCIRST_LOW); msleep(100); /* Bring the PCI out of reset */ ar2315_pci_reg_mask(apc, AR2315_PCI_MISC_CONFIG, AR2315_PCIMISC_RST_MODE, AR2315_PCIRST_HIGH | AR2315_PCICACHE_DIS | 0x8); ar2315_pci_reg_write(apc, AR2315_PCI_UNCACHE_CFG, 0x1E | /* 1GB uncached */ (1 << 5) | /* Enable uncached */ (0x2 << 30) /* Base: 0x80000000 */); ar2315_pci_reg_read(apc, AR2315_PCI_UNCACHE_CFG); msleep(500); err = ar2315_pci_host_setup(apc); if (err) return err; apc->domain = irq_domain_add_linear(NULL, AR2315_PCI_IRQ_COUNT, &ar2315_pci_irq_domain_ops, apc); if (!apc->domain) { dev_err(dev, "failed to add IRQ domain\n"); return -ENOMEM; } ar2315_pci_irq_init(apc); /* PCI controller does not support I/O ports */ apc->io_res.name = "AR2315 IO space"; apc->io_res.start = 0; apc->io_res.end = 0; apc->io_res.flags = IORESOURCE_IO; apc->pci_ctrl.pci_ops = &ar2315_pci_ops; apc->pci_ctrl.mem_resource = &apc->mem_res; apc->pci_ctrl.io_resource = &apc->io_res; register_pci_controller(&apc->pci_ctrl); dev_info(dev, "register PCI controller\n"); return 0; } static struct platform_driver ar2315_pci_driver = { .probe = ar2315_pci_probe, .driver = { .name = "ar2315-pci", }, }; static int __init ar2315_pci_init(void) { return platform_driver_register(&ar2315_pci_driver); } arch_initcall(ar2315_pci_init); int pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { struct ar2315_pci_ctrl *apc = ar2315_pci_bus_to_apc(dev->bus); return slot ? 0 : apc->irq_ext; } int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; }
28.860153
80
0.746897
2c778409e3b830355463a099cbca235174ca9141
49,672
c
C
sys/bus/u4b/net/uhso.c
cooljeanius/DragonFlyBSD
4c4e823ecc4019d4536be9493e38fef118f9a8cf
[ "BSD-3-Clause" ]
null
null
null
sys/bus/u4b/net/uhso.c
cooljeanius/DragonFlyBSD
4c4e823ecc4019d4536be9493e38fef118f9a8cf
[ "BSD-3-Clause" ]
null
null
null
sys/bus/u4b/net/uhso.c
cooljeanius/DragonFlyBSD
4c4e823ecc4019d4536be9493e38fef118f9a8cf
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 2010 Fredrik Lindberg <fli@shapeshifter.se> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/types.h> #include <sys/sockio.h> #include <sys/mbuf.h> #include <sys/malloc.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/socket.h> #include <sys/tty.h> #include <sys/sysctl.h> #include <sys/condvar.h> #include <sys/sx.h> #include <sys/proc.h> #include <sys/conf.h> #include <sys/bus.h> #include <sys/systm.h> #include <sys/limits.h> #include <machine/bus.h> #include <net/if.h> #include <net/if_types.h> #include <net/netisr.h> #include <net/bpf.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <dev/usb/usb.h> #include <dev/usb/usbdi.h> #include <dev/usb/usbdi_util.h> #include <dev/usb/usb_cdc.h> #include "usbdevs.h" #define USB_DEBUG_VAR uhso_debug #include <dev/usb/usb_debug.h> #include <dev/usb/usb_process.h> #include <dev/usb/usb_busdma.h> #include <dev/usb/usb_msctest.h> #include <dev/usb/serial/usb_serial.h> struct uhso_tty { struct uhso_softc *ht_sc; struct usb_xfer *ht_xfer[3]; int ht_muxport; /* Mux. port no */ int ht_open; char ht_name[32]; }; struct uhso_softc { device_t sc_dev; struct usb_device *sc_udev; struct mtx sc_mtx; uint32_t sc_type; /* Interface definition */ int sc_radio; struct usb_xfer *sc_xfer[3]; uint8_t sc_iface_no; uint8_t sc_iface_index; /* Control pipe */ struct usb_xfer * sc_ctrl_xfer[2]; uint8_t sc_ctrl_iface_no; /* Network */ struct usb_xfer *sc_if_xfer[2]; struct ifnet *sc_ifp; struct mbuf *sc_mwait; /* Partial packet */ size_t sc_waitlen; /* No. of outstanding bytes */ struct ifqueue sc_rxq; struct callout sc_c; /* TTY related structures */ struct ucom_super_softc sc_super_ucom; int sc_ttys; struct uhso_tty *sc_tty; struct ucom_softc *sc_ucom; int sc_msr; int sc_lsr; int sc_line; }; #define UHSO_MAX_MTU 2048 /* * There are mainly two type of cards floating around. * The first one has 2,3 or 4 interfaces with a multiplexed serial port * and packet interface on the first interface and bulk serial ports * on the others. * The second type of card has several other interfaces, their purpose * can be detected during run-time. */ #define UHSO_IFACE_SPEC(usb_type, port, port_type) \ (((usb_type) << 24) | ((port) << 16) | (port_type)) #define UHSO_IFACE_USB_TYPE(x) ((x >> 24) & 0xff) #define UHSO_IFACE_PORT(x) ((x >> 16) & 0xff) #define UHSO_IFACE_PORT_TYPE(x) (x & 0xff) /* * USB interface types */ #define UHSO_IF_NET 0x01 /* Network packet interface */ #define UHSO_IF_MUX 0x02 /* Multiplexed serial port */ #define UHSO_IF_BULK 0x04 /* Bulk interface */ /* * Port types */ #define UHSO_PORT_UNKNOWN 0x00 #define UHSO_PORT_SERIAL 0x01 /* Serial port */ #define UHSO_PORT_NETWORK 0x02 /* Network packet interface */ /* * Multiplexed serial port destination sub-port names */ #define UHSO_MPORT_TYPE_CTL 0x00 /* Control port */ #define UHSO_MPORT_TYPE_APP 0x01 /* Application */ #define UHSO_MPORT_TYPE_PCSC 0x02 #define UHSO_MPORT_TYPE_GPS 0x03 #define UHSO_MPORT_TYPE_APP2 0x04 /* Secondary application */ #define UHSO_MPORT_TYPE_MAX UHSO_MPORT_TYPE_APP2 #define UHSO_MPORT_TYPE_NOMAX 8 /* Max number of mux ports */ /* * Port definitions * Note that these definitions are arbitrary and do not match the values * returned by the auto config descriptor. */ #define UHSO_PORT_TYPE_UNKNOWN 0x00 #define UHSO_PORT_TYPE_CTL 0x01 #define UHSO_PORT_TYPE_APP 0x02 #define UHSO_PORT_TYPE_APP2 0x03 #define UHSO_PORT_TYPE_MODEM 0x04 #define UHSO_PORT_TYPE_NETWORK 0x05 #define UHSO_PORT_TYPE_DIAG 0x06 #define UHSO_PORT_TYPE_DIAG2 0x07 #define UHSO_PORT_TYPE_GPS 0x08 #define UHSO_PORT_TYPE_GPSCTL 0x09 #define UHSO_PORT_TYPE_PCSC 0x0a #define UHSO_PORT_TYPE_MSD 0x0b #define UHSO_PORT_TYPE_VOICE 0x0c #define UHSO_PORT_TYPE_MAX 0x0c static eventhandler_tag uhso_etag; /* Overall port type */ static char *uhso_port[] = { "Unknown", "Serial", "Network", "Network/Serial" }; /* * Map between interface port type read from device and description type. * The position in this array is a direct map to the auto config * descriptor values. */ static unsigned char uhso_port_map[] = { UHSO_PORT_TYPE_UNKNOWN, UHSO_PORT_TYPE_DIAG, UHSO_PORT_TYPE_GPS, UHSO_PORT_TYPE_GPSCTL, UHSO_PORT_TYPE_APP, UHSO_PORT_TYPE_APP2, UHSO_PORT_TYPE_CTL, UHSO_PORT_TYPE_NETWORK, UHSO_PORT_TYPE_MODEM, UHSO_PORT_TYPE_MSD, UHSO_PORT_TYPE_PCSC, UHSO_PORT_TYPE_VOICE }; static char uhso_port_map_max = sizeof(uhso_port_map) / sizeof(char); static unsigned char uhso_mux_port_map[] = { UHSO_PORT_TYPE_CTL, UHSO_PORT_TYPE_APP, UHSO_PORT_TYPE_PCSC, UHSO_PORT_TYPE_GPS, UHSO_PORT_TYPE_APP2 }; static char *uhso_port_type[] = { "Unknown", /* Not a valid port */ "Control", "Application", "Application (Secondary)", "Modem", "Network", "Diagnostic", "Diagnostic (Secondary)", "GPS", "GPS Control", "PC Smartcard", "MSD", "Voice", }; static char *uhso_port_type_sysctl[] = { "unknown", "control", "application", "application", "modem", "network", "diagnostic", "diagnostic", "gps", "gps_control", "pcsc", "msd", "voice", }; #define UHSO_STATIC_IFACE 0x01 #define UHSO_AUTO_IFACE 0x02 /* ifnet device unit allocations */ static struct unrhdr *uhso_ifnet_unit = NULL; static const STRUCT_USB_HOST_ID uhso_devs[] = { #define UHSO_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } /* Option GlobeTrotter MAX 7.2 with upgraded firmware */ UHSO_DEV(OPTION, GTMAX72, UHSO_STATIC_IFACE), /* Option GlobeSurfer iCON 7.2 */ UHSO_DEV(OPTION, GSICON72, UHSO_STATIC_IFACE), /* Option iCON 225 */ UHSO_DEV(OPTION, GTHSDPA, UHSO_STATIC_IFACE), /* Option GlobeSurfer iCON HSUPA */ UHSO_DEV(OPTION, GSICONHSUPA, UHSO_STATIC_IFACE), /* Option GlobeTrotter HSUPA */ UHSO_DEV(OPTION, GTHSUPA, UHSO_STATIC_IFACE), /* GE40x */ UHSO_DEV(OPTION, GE40X, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_1, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_2, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_3, UHSO_AUTO_IFACE), /* Option GlobeSurfer iCON 401 */ UHSO_DEV(OPTION, ICON401, UHSO_AUTO_IFACE), /* Option GlobeTrotter Module 382 */ UHSO_DEV(OPTION, GMT382, UHSO_AUTO_IFACE), /* Option iCON EDGE */ UHSO_DEV(OPTION, ICONEDGE, UHSO_STATIC_IFACE), /* Option Module HSxPA */ UHSO_DEV(OPTION, MODHSXPA, UHSO_STATIC_IFACE), /* Option iCON 321 */ UHSO_DEV(OPTION, ICON321, UHSO_STATIC_IFACE), /* Option iCON 322 */ UHSO_DEV(OPTION, GTICON322, UHSO_STATIC_IFACE), /* Option iCON 505 */ UHSO_DEV(OPTION, ICON505, UHSO_AUTO_IFACE), /* Option iCON 452 */ UHSO_DEV(OPTION, ICON505, UHSO_AUTO_IFACE), #undef UHSO_DEV }; static SYSCTL_NODE(_hw_usb, OID_AUTO, uhso, CTLFLAG_RW, 0, "USB uhso"); static int uhso_autoswitch = 1; SYSCTL_INT(_hw_usb_uhso, OID_AUTO, auto_switch, CTLFLAG_RW, &uhso_autoswitch, 0, "Automatically switch to modem mode"); #ifdef USB_DEBUG #ifdef UHSO_DEBUG static int uhso_debug = UHSO_DEBUG; #else static int uhso_debug = -1; #endif SYSCTL_INT(_hw_usb_uhso, OID_AUTO, debug, CTLFLAG_RW, &uhso_debug, 0, "Debug level"); #define UHSO_DPRINTF(n, x, ...) {\ if (uhso_debug >= n) {\ printf("%s: " x, __func__, ##__VA_ARGS__);\ }\ } #else #define UHSO_DPRINTF(n, x, ...) #endif #ifdef UHSO_DEBUG_HEXDUMP # define UHSO_HEXDUMP(_buf, _len) do { \ { \ size_t __tmp; \ const char *__buf = (const char *)_buf; \ for (__tmp = 0; __tmp < _len; __tmp++) \ printf("%02hhx ", *__buf++); \ printf("\n"); \ } \ } while(0) #else # define UHSO_HEXDUMP(_buf, _len) #endif enum { UHSO_MUX_ENDPT_INTR = 0, UHSO_MUX_ENDPT_MAX }; enum { UHSO_CTRL_READ = 0, UHSO_CTRL_WRITE, UHSO_CTRL_MAX }; enum { UHSO_IFNET_READ = 0, UHSO_IFNET_WRITE, UHSO_IFNET_MAX }; enum { UHSO_BULK_ENDPT_READ = 0, UHSO_BULK_ENDPT_WRITE, UHSO_BULK_ENDPT_INTR, UHSO_BULK_ENDPT_MAX }; static usb_callback_t uhso_mux_intr_callback; static usb_callback_t uhso_mux_read_callback; static usb_callback_t uhso_mux_write_callback; static usb_callback_t uhso_bs_read_callback; static usb_callback_t uhso_bs_write_callback; static usb_callback_t uhso_bs_intr_callback; static usb_callback_t uhso_ifnet_read_callback; static usb_callback_t uhso_ifnet_write_callback; /* Config used for the default control pipes */ static const struct usb_config uhso_ctrl_config[UHSO_CTRL_MAX] = { [UHSO_CTRL_READ] = { .type = UE_CONTROL, .endpoint = 0x00, .direction = UE_DIR_ANY, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = sizeof(struct usb_device_request) + 1024, .callback = &uhso_mux_read_callback }, [UHSO_CTRL_WRITE] = { .type = UE_CONTROL, .endpoint = 0x00, .direction = UE_DIR_ANY, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = sizeof(struct usb_device_request) + 1024, .timeout = 1000, .callback = &uhso_mux_write_callback } }; /* Config for the multiplexed serial ports */ static const struct usb_config uhso_mux_config[UHSO_MUX_ENDPT_MAX] = { [UHSO_MUX_ENDPT_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .short_xfer_ok = 1 }, .bufsize = 0, .callback = &uhso_mux_intr_callback, } }; /* Config for the raw IP-packet interface */ static const struct usb_config uhso_ifnet_config[UHSO_IFNET_MAX] = { [UHSO_IFNET_READ] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = MCLBYTES, .callback = &uhso_ifnet_read_callback }, [UHSO_IFNET_WRITE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = MCLBYTES, .timeout = 5 * USB_MS_HZ, .callback = &uhso_ifnet_write_callback } }; /* Config for interfaces with normal bulk serial ports */ static const struct usb_config uhso_bs_config[UHSO_BULK_ENDPT_MAX] = { [UHSO_BULK_ENDPT_READ] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = 4096, .callback = &uhso_bs_read_callback }, [UHSO_BULK_ENDPT_WRITE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = 8192, .callback = &uhso_bs_write_callback }, [UHSO_BULK_ENDPT_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .short_xfer_ok = 1 }, .bufsize = 0, .callback = &uhso_bs_intr_callback, } }; static int uhso_probe_iface(struct uhso_softc *, int, int (*probe)(struct usb_device *, int)); static int uhso_probe_iface_auto(struct usb_device *, int); static int uhso_probe_iface_static(struct usb_device *, int); static int uhso_attach_muxserial(struct uhso_softc *, struct usb_interface *, int type); static int uhso_attach_bulkserial(struct uhso_softc *, struct usb_interface *, int type); static int uhso_attach_ifnet(struct uhso_softc *, struct usb_interface *, int type); static void uhso_test_autoinst(void *, struct usb_device *, struct usb_attach_arg *); static int uhso_driver_loaded(struct module *, int, void *); static int uhso_radio_sysctl(SYSCTL_HANDLER_ARGS); static int uhso_radio_ctrl(struct uhso_softc *, int); static void uhso_ucom_start_read(struct ucom_softc *); static void uhso_ucom_stop_read(struct ucom_softc *); static void uhso_ucom_start_write(struct ucom_softc *); static void uhso_ucom_stop_write(struct ucom_softc *); static void uhso_ucom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uhso_ucom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uhso_ucom_cfg_set_rts(struct ucom_softc *, uint8_t); static void uhso_if_init(void *); static void uhso_if_start(struct ifnet *, struct ifaltq_subque *); static void uhso_if_stop(struct uhso_softc *); static int uhso_if_ioctl(struct ifnet *, u_long, caddr_t); static int uhso_if_output(struct ifnet *, struct mbuf *, struct sockaddr *, struct route *); static void uhso_if_rxflush(void *); static device_probe_t uhso_probe; static device_attach_t uhso_attach; static device_detach_t uhso_detach; static device_method_t uhso_methods[] = { DEVMETHOD(device_probe, uhso_probe), DEVMETHOD(device_attach, uhso_attach), DEVMETHOD(device_detach, uhso_detach), { 0, 0 } }; static driver_t uhso_driver = { "uhso", uhso_methods, sizeof(struct uhso_softc) }; static devclass_t uhso_devclass; DRIVER_MODULE(uhso, uhub, uhso_driver, uhso_devclass, uhso_driver_loaded, 0); MODULE_DEPEND(uhso, ucom, 1, 1, 1); MODULE_DEPEND(uhso, usb, 1, 1, 1); MODULE_VERSION(uhso, 1); static struct ucom_callback uhso_ucom_callback = { .ucom_cfg_get_status = &uhso_ucom_cfg_get_status, .ucom_cfg_set_dtr = &uhso_ucom_cfg_set_dtr, .ucom_cfg_set_rts = &uhso_ucom_cfg_set_rts, .ucom_start_read = uhso_ucom_start_read, .ucom_stop_read = uhso_ucom_stop_read, .ucom_start_write = uhso_ucom_start_write, .ucom_stop_write = uhso_ucom_stop_write }; static int uhso_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); int error; if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bDeviceClass != 0xff) return (ENXIO); error = usbd_lookup_id_by_uaa(uhso_devs, sizeof(uhso_devs), uaa); if (error != 0) return (error); /* * Probe device to see if we are able to attach * to this interface or not. */ if (USB_GET_DRIVER_INFO(uaa) == UHSO_AUTO_IFACE) { if (uhso_probe_iface_auto(uaa->device, uaa->info.bIfaceNum) == 0) return (ENXIO); } return (error); } static int uhso_attach(device_t self) { struct uhso_softc *sc = device_get_softc(self); struct usb_attach_arg *uaa = device_get_ivars(self); struct usb_config_descriptor *cd; struct usb_interface_descriptor *id; struct sysctl_ctx_list *sctx; struct sysctl_oid *soid; struct sysctl_oid *tree = NULL, *tty_node; struct ucom_softc *ucom; struct uhso_tty *ht; int i, error, port; void *probe_f; usb_error_t uerr; char *desc; sc->sc_dev = self; sc->sc_udev = uaa->device; mtx_init(&sc->sc_mtx, "uhso", NULL, MTX_DEF); sc->sc_ucom = NULL; sc->sc_ttys = 0; sc->sc_radio = 1; cd = usbd_get_config_descriptor(uaa->device); id = usbd_get_interface_descriptor(uaa->iface); sc->sc_ctrl_iface_no = id->bInterfaceNumber; sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = uaa->info.bIfaceIndex; /* Setup control pipe */ uerr = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_ctrl_xfer, uhso_ctrl_config, UHSO_CTRL_MAX, sc, &sc->sc_mtx); if (uerr) { device_printf(self, "Failed to setup control pipe: %s\n", usbd_errstr(uerr)); goto out; } if (USB_GET_DRIVER_INFO(uaa) == UHSO_STATIC_IFACE) probe_f = uhso_probe_iface_static; else if (USB_GET_DRIVER_INFO(uaa) == UHSO_AUTO_IFACE) probe_f = uhso_probe_iface_auto; else goto out; error = uhso_probe_iface(sc, uaa->info.bIfaceNum, probe_f); if (error != 0) goto out; sctx = device_get_sysctl_ctx(sc->sc_dev); soid = device_get_sysctl_tree(sc->sc_dev); SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "type", CTLFLAG_RD, uhso_port[UHSO_IFACE_PORT(sc->sc_type)], 0, "Port available at this interface"); SYSCTL_ADD_PROC(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "radio", CTLTYPE_INT | CTLFLAG_RW, sc, 0, uhso_radio_sysctl, "I", "Enable radio"); /* * The default interface description on most Option devices isn't * very helpful. So we skip device_set_usb_desc and set the * device description manually. */ device_set_desc_copy(self, uhso_port_type[UHSO_IFACE_PORT_TYPE(sc->sc_type)]); /* Announce device */ device_printf(self, "<%s port> at <%s %s> on %s\n", uhso_port_type[UHSO_IFACE_PORT_TYPE(sc->sc_type)], usb_get_manufacturer(uaa->device), usb_get_product(uaa->device), device_get_nameunit(device_get_parent(self))); if (sc->sc_ttys > 0) { SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "ports", CTLFLAG_RD, &sc->sc_ttys, 0, "Number of attached serial ports"); tree = SYSCTL_ADD_NODE(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "port", CTLFLAG_RD, NULL, "Serial ports"); } /* * Loop through the number of found TTYs and create sysctl * nodes for them. */ for (i = 0; i < sc->sc_ttys; i++) { ht = &sc->sc_tty[i]; ucom = &sc->sc_ucom[i]; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) port = uhso_mux_port_map[ht->ht_muxport]; else port = UHSO_IFACE_PORT_TYPE(sc->sc_type); desc = uhso_port_type_sysctl[port]; tty_node = SYSCTL_ADD_NODE(sctx, SYSCTL_CHILDREN(tree), OID_AUTO, desc, CTLFLAG_RD, NULL, ""); ht->ht_name[0] = 0; if (sc->sc_ttys == 1) snprintf(ht->ht_name, 32, "cuaU%d", ucom->sc_super->sc_unit); else { snprintf(ht->ht_name, 32, "cuaU%d.%d", ucom->sc_super->sc_unit, ucom->sc_subunit); } desc = uhso_port_type[port]; SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(tty_node), OID_AUTO, "tty", CTLFLAG_RD, ht->ht_name, 0, ""); SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(tty_node), OID_AUTO, "desc", CTLFLAG_RD, desc, 0, ""); if (bootverbose) device_printf(sc->sc_dev, "\"%s\" port at %s\n", desc, ht->ht_name); } return (0); out: uhso_detach(sc->sc_dev); return (ENXIO); } static int uhso_detach(device_t self) { struct uhso_softc *sc = device_get_softc(self); int i; usbd_transfer_unsetup(sc->sc_xfer, 3); usbd_transfer_unsetup(sc->sc_ctrl_xfer, UHSO_CTRL_MAX); if (sc->sc_ttys > 0) { ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); for (i = 0; i < sc->sc_ttys; i++) { if (sc->sc_tty[i].ht_muxport != -1) { usbd_transfer_unsetup(sc->sc_tty[i].ht_xfer, UHSO_CTRL_MAX); } } free(sc->sc_tty, M_USBDEV); free(sc->sc_ucom, M_USBDEV); } if (sc->sc_ifp != NULL) { callout_drain(&sc->sc_c); free_unr(uhso_ifnet_unit, sc->sc_ifp->if_dunit); mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); bpfdetach(sc->sc_ifp); if_detach(sc->sc_ifp); if_free(sc->sc_ifp); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_if_xfer, UHSO_IFNET_MAX); } mtx_destroy(&sc->sc_mtx); return (0); } static void uhso_test_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; if (uaa->dev_state != UAA_DEV_READY || !uhso_autoswitch) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usbd_lookup_id_by_uaa(uhso_devs, sizeof(uhso_devs), uaa)) return; /* no device match */ if (usb_msc_eject(udev, 0, MSC_EJECT_REZERO) == 0) { /* success, mark the udev as disappearing */ uaa->dev_state = UAA_DEV_EJECTING; } } static int uhso_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: /* register our autoinstall handler */ uhso_etag = EVENTHANDLER_REGISTER(usb_dev_configured, uhso_test_autoinst, NULL, EVENTHANDLER_PRI_ANY); /* create our unit allocator for inet devs */ uhso_ifnet_unit = new_unrhdr(0, INT_MAX, NULL); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, uhso_etag); delete_unrhdr(uhso_ifnet_unit); break; default: return (EOPNOTSUPP); } return (0); } /* * Probe the interface type by querying the device. The elements * of an array indicates the capabilities of a particular interface. * Returns a bit mask with the interface capabilities. */ static int uhso_probe_iface_auto(struct usb_device *udev, int index) { struct usb_device_request req; usb_error_t uerr; uint16_t actlen = 0; char port; char buf[17] = {0}; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = 0x86; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 17); uerr = usbd_do_request_flags(udev, NULL, &req, buf, 0, &actlen, USB_MS_HZ); if (uerr != 0) { printf("%s: usbd_do_request_flags failed, %s\n", __func__, usbd_errstr(uerr)); return (0); } UHSO_DPRINTF(1, "actlen=%d\n", actlen); UHSO_HEXDUMP(buf, 17); if (index < 0 || index > 16) { UHSO_DPRINTF(0, "Index %d out of range\n", index); return (0); } UHSO_DPRINTF(1, "index=%d, type=%x[%s]\n", index, buf[index], uhso_port_type[(int)uhso_port_map[(int)buf[index]]]); if (buf[index] >= uhso_port_map_max) port = 0; else port = uhso_port_map[(int)buf[index]]; switch (port) { case UHSO_PORT_TYPE_NETWORK: return (UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, port)); case UHSO_PORT_TYPE_DIAG: case UHSO_PORT_TYPE_DIAG2: case UHSO_PORT_TYPE_CTL: case UHSO_PORT_TYPE_APP: case UHSO_PORT_TYPE_APP2: case UHSO_PORT_TYPE_MODEM: return (UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, port)); case UHSO_PORT_TYPE_MSD: return (0); case UHSO_PORT_TYPE_UNKNOWN: default: return (0); } return (0); } /* * Returns the capabilities of interfaces for devices that don't * support the automatic query. * Returns a bit mask with the interface capabilities. */ static int uhso_probe_iface_static(struct usb_device *udev, int index) { struct usb_config_descriptor *cd; cd = usbd_get_config_descriptor(udev); if (cd->bNumInterface <= 3) { /* Cards with 3 or less interfaces */ switch (index) { case 0: return UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, UHSO_PORT_TYPE_NETWORK); case 1: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG); case 2: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_MODEM); } } else { /* Cards with 4 interfaces */ switch (index) { case 0: return UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, UHSO_PORT_TYPE_NETWORK); case 1: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG2); case 2: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_MODEM); case 3: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG); } } return (0); } /* * Probes an interface for its particular capabilities and attaches if * it's a supported interface. */ static int uhso_probe_iface(struct uhso_softc *sc, int index, int (*probe)(struct usb_device *, int)) { struct usb_interface *iface; int type, error; UHSO_DPRINTF(1, "Probing for interface %d, probe_func=%p\n", index, probe); type = probe(sc->sc_udev, index); UHSO_DPRINTF(1, "Probe result %x\n", type); if (type <= 0) return (ENXIO); sc->sc_type = type; iface = usbd_get_iface(sc->sc_udev, index); if (UHSO_IFACE_PORT_TYPE(type) == UHSO_PORT_TYPE_NETWORK) { error = uhso_attach_ifnet(sc, iface, type); if (error) { UHSO_DPRINTF(1, "uhso_attach_ifnet failed"); return (ENXIO); } /* * If there is an additional interrupt endpoint on this * interface then we most likely have a multiplexed serial port * available. */ if (iface->idesc->bNumEndpoints < 3) { sc->sc_type = UHSO_IFACE_SPEC( UHSO_IFACE_USB_TYPE(type) & ~UHSO_IF_MUX, UHSO_IFACE_PORT(type) & ~UHSO_PORT_SERIAL, UHSO_IFACE_PORT_TYPE(type)); return (0); } UHSO_DPRINTF(1, "Trying to attach mux. serial\n"); error = uhso_attach_muxserial(sc, iface, type); if (error == 0 && sc->sc_ttys > 0) { error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); mtx_unlock(&sc->sc_mtx); } } else if ((UHSO_IFACE_USB_TYPE(type) & UHSO_IF_BULK) && UHSO_IFACE_PORT(type) & UHSO_PORT_SERIAL) { error = uhso_attach_bulkserial(sc, iface, type); if (error) return (ENXIO); error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); } else { UHSO_DPRINTF(0, "Unknown type %x\n", type); return (ENXIO); } return (0); } static int uhso_radio_ctrl(struct uhso_softc *sc, int onoff) { struct usb_device_request req; usb_error_t uerr; req.bmRequestType = UT_VENDOR; req.bRequest = onoff ? 0x82 : 0x81; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); uerr = usbd_do_request(sc->sc_udev, NULL, &req, NULL); if (uerr != 0) { device_printf(sc->sc_dev, "usbd_do_request_flags failed: %s\n", usbd_errstr(uerr)); return (-1); } return (onoff); } static int uhso_radio_sysctl(SYSCTL_HANDLER_ARGS) { struct uhso_softc *sc = arg1; int error, radio; radio = sc->sc_radio; error = sysctl_handle_int(oidp, &radio, 0, req); if (error) return (error); if (radio != sc->sc_radio) { radio = radio != 0 ? 1 : 0; error = uhso_radio_ctrl(sc, radio); if (error != -1) sc->sc_radio = radio; } return (0); } /* * Expands allocated memory to fit an additional TTY. * Two arrays are kept with matching indexes, one for ucom and one * for our private data. */ static int uhso_alloc_tty(struct uhso_softc *sc) { sc->sc_ttys++; sc->sc_tty = reallocf(sc->sc_tty, sizeof(struct uhso_tty) * sc->sc_ttys, M_USBDEV, M_WAITOK | M_ZERO); if (sc->sc_tty == NULL) return (-1); sc->sc_ucom = reallocf(sc->sc_ucom, sizeof(struct ucom_softc) * sc->sc_ttys, M_USBDEV, M_WAITOK | M_ZERO); if (sc->sc_ucom == NULL) return (-1); sc->sc_tty[sc->sc_ttys - 1].ht_sc = sc; UHSO_DPRINTF(1, "Allocated TTY %d\n", sc->sc_ttys - 1); return (sc->sc_ttys - 1); } /* * Attach a multiplexed serial port * Data is read/written with requests on the default control pipe. An interrupt * endpoint returns when there is new data to be read. */ static int uhso_attach_muxserial(struct uhso_softc *sc, struct usb_interface *iface, int type) { struct usb_descriptor *desc; int i, port, tty; usb_error_t uerr; /* * The class specific interface (type 0x24) descriptor subtype field * contains a bitmask that specifies which (and how many) ports that * are available through this multiplexed serial port. */ desc = usbd_find_descriptor(sc->sc_udev, NULL, iface->idesc->bInterfaceNumber, UDESC_CS_INTERFACE, 0xff, 0, 0); if (desc == NULL) { UHSO_DPRINTF(0, "Failed to find UDESC_CS_INTERFACE\n"); return (ENXIO); } UHSO_DPRINTF(1, "Mux port mask %x\n", desc->bDescriptorSubtype); if (desc->bDescriptorSubtype == 0) return (ENXIO); /* * The bitmask is one octet, loop through the number of * bits that are set and create a TTY for each. */ for (i = 0; i < 8; i++) { port = (1 << i); if ((port & desc->bDescriptorSubtype) == port) { UHSO_DPRINTF(2, "Found mux port %x (%d)\n", port, i); tty = uhso_alloc_tty(sc); if (tty < 0) return (ENOMEM); sc->sc_tty[tty].ht_muxport = i; uerr = usbd_transfer_setup(sc->sc_udev, &sc->sc_iface_index, sc->sc_tty[tty].ht_xfer, uhso_ctrl_config, UHSO_CTRL_MAX, sc, &sc->sc_mtx); if (uerr) { device_printf(sc->sc_dev, "Failed to setup control pipe: %s\n", usbd_errstr(uerr)); return (ENXIO); } } } /* Setup the intr. endpoint */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_mux_config, 1, sc, &sc->sc_mtx); if (uerr) return (ENXIO); return (0); } /* * Interrupt callback for the multiplexed serial port. Indicates * which serial port has data waiting. */ static void uhso_mux_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_page_cache *pc; struct usb_page_search res; struct uhso_softc *sc = usbd_xfer_softc(xfer); unsigned int i, mux; UHSO_DPRINTF(3, "status %d\n", USB_GET_STATE(xfer)); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* * The multiplexed port number can be found at the first byte. * It contains a bit mask, we transform this in to an integer. */ pc = usbd_xfer_get_frame(xfer, 0); usbd_get_page(pc, 0, &res); i = *((unsigned char *)res.buffer); mux = 0; while (i >>= 1) { mux++; } UHSO_DPRINTF(3, "mux port %d (%d)\n", mux, i); if (mux > UHSO_MPORT_TYPE_NOMAX) break; /* Issue a read for this serial port */ usbd_xfer_set_priv( sc->sc_tty[mux].ht_xfer[UHSO_CTRL_READ], &sc->sc_tty[mux]); usbd_transfer_start(sc->sc_tty[mux].ht_xfer[UHSO_CTRL_READ]); break; case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_mux_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct usb_device_request req; struct uhso_tty *ht; int actlen, len; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d\n", USB_GET_STATE(xfer)); ht = usbd_xfer_get_priv(xfer); UHSO_DPRINTF(3, "ht=%p open=%d\n", ht, ht->ht_open); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* Got data, send to ucom */ pc = usbd_xfer_get_frame(xfer, 1); len = usbd_xfer_frame_len(xfer, 1); UHSO_DPRINTF(3, "got %d bytes on mux port %d\n", len, ht->ht_muxport); if (len <= 0) { usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); break; } /* Deliver data if the TTY is open, discard otherwise */ if (ht->ht_open) ucom_put_data(&sc->sc_ucom[ht->ht_muxport], pc, 0, len); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: memset(&req, 0, sizeof(struct usb_device_request)); req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UCDC_GET_ENCAPSULATED_RESPONSE; USETW(req.wValue, 0); USETW(req.wIndex, ht->ht_muxport); USETW(req.wLength, 1024); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, 1024); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_mux_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct uhso_tty *ht; struct usb_page_cache *pc; struct usb_device_request req; int actlen; struct usb_page_search res; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); ht = usbd_xfer_get_priv(xfer); UHSO_DPRINTF(3, "status=%d, using mux port %d\n", USB_GET_STATE(xfer), ht->ht_muxport); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: UHSO_DPRINTF(3, "wrote %zd data bytes to muxport %d\n", actlen - sizeof(struct usb_device_request) , ht->ht_muxport); /* FALLTHROUGH */ case USB_ST_SETUP: pc = usbd_xfer_get_frame(xfer, 1); if (ucom_get_data(&sc->sc_ucom[ht->ht_muxport], pc, 0, 32, &actlen)) { usbd_get_page(pc, 0, &res); memset(&req, 0, sizeof(struct usb_device_request)); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SEND_ENCAPSULATED_COMMAND; USETW(req.wValue, 0); USETW(req.wIndex, ht->ht_muxport); USETW(req.wLength, actlen); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, actlen); usbd_xfer_set_frames(xfer, 2); UHSO_DPRINTF(3, "Prepared %d bytes for transmit " "on muxport %d\n", actlen, ht->ht_muxport); usbd_transfer_submit(xfer); } break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; break; } } static int uhso_attach_bulkserial(struct uhso_softc *sc, struct usb_interface *iface, int type) { usb_error_t uerr; int tty; /* Try attaching RD/WR/INTR first */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_bs_config, UHSO_BULK_ENDPT_MAX, sc, &sc->sc_mtx); if (uerr) { /* Try only RD/WR */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_bs_config, UHSO_BULK_ENDPT_MAX - 1, sc, &sc->sc_mtx); } if (uerr) { UHSO_DPRINTF(0, "usbd_transfer_setup failed"); return (-1); } tty = uhso_alloc_tty(sc); if (tty < 0) { usbd_transfer_unsetup(sc->sc_xfer, UHSO_BULK_ENDPT_MAX); return (ENOMEM); } sc->sc_tty[tty].ht_muxport = -1; return (0); } static void uhso_bs_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom[0], pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_bs_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom[0], pc, 0, 8192, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } break; break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_bs_cfg(struct uhso_softc *sc) { struct usb_device_request req; usb_error_t uerr; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); uerr = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom[0], &req, NULL, 0, 1000); if (uerr != 0) { device_printf(sc->sc_dev, "failed to set ctrl line state to " "0x%02x: %s\n", sc->sc_line, usbd_errstr(uerr)); } } static void uhso_bs_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; struct usb_cdc_notification cdc; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < UCDC_NOTIFICATION_LENGTH) { UHSO_DPRINTF(0, "UCDC notification too short: %d\n", actlen); goto tr_setup; } else if (actlen > sizeof(struct usb_cdc_notification)) { UHSO_DPRINTF(0, "UCDC notification too large: %d\n", actlen); actlen = sizeof(struct usb_cdc_notification); } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &cdc, actlen); if (UGETW(cdc.wIndex) != sc->sc_iface_no) { UHSO_DPRINTF(0, "Interface mismatch, got %d expected %d\n", UGETW(cdc.wIndex), sc->sc_iface_no); goto tr_setup; } if (cdc.bmRequestType == UCDC_NOTIFICATION && cdc.bNotification == UCDC_N_SERIAL_STATE) { UHSO_DPRINTF(2, "notify = 0x%02x\n", cdc.data[0]); sc->sc_msr = 0; sc->sc_lsr = 0; if (cdc.data[0] & UCDC_N_SERIAL_RI) sc->sc_msr |= SER_RI; if (cdc.data[0] & UCDC_N_SERIAL_DSR) sc->sc_msr |= SER_DSR; if (cdc.data[0] & UCDC_N_SERIAL_DCD) sc->sc_msr |= SER_DCD; ucom_status_change(&sc->sc_ucom[0]); } case USB_ST_SETUP: tr_setup: default: if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_ucom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uhso_softc *sc = ucom->sc_parent; *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uhso_ucom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uhso_softc *sc = ucom->sc_parent; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; if (onoff) sc->sc_line |= UCDC_LINE_DTR; else sc->sc_line &= ~UCDC_LINE_DTR; uhso_bs_cfg(sc); } static void uhso_ucom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uhso_softc *sc = ucom->sc_parent; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; if (onoff) sc->sc_line |= UCDC_LINE_RTS; else sc->sc_line &= ~UCDC_LINE_RTS; uhso_bs_cfg(sc); } static void uhso_ucom_start_read(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; UHSO_DPRINTF(3, "unit=%d, subunit=%d\n", ucom->sc_super->sc_unit, ucom->sc_subunit); if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { sc->sc_tty[ucom->sc_subunit].ht_open = 1; usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { sc->sc_tty[0].ht_open = 1; usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_READ]); if (sc->sc_xfer[UHSO_BULK_ENDPT_INTR] != NULL) usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_INTR]); } } static void uhso_ucom_stop_read(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { sc->sc_tty[ucom->sc_subunit].ht_open = 0; usbd_transfer_stop( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_READ]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { sc->sc_tty[0].ht_open = 0; usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_READ]); if (sc->sc_xfer[UHSO_BULK_ENDPT_INTR] != NULL) usbd_transfer_stop(sc->sc_xfer[UHSO_BULK_ENDPT_INTR]); } } static void uhso_ucom_start_write(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { UHSO_DPRINTF(3, "local unit %d\n", ucom->sc_subunit); usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); usbd_xfer_set_priv( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE], &sc->sc_tty[ucom->sc_subunit]); usbd_transfer_start( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_WRITE]); } } static void uhso_ucom_stop_write(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { usbd_transfer_stop( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { usbd_transfer_stop(sc->sc_xfer[UHSO_BULK_ENDPT_WRITE]); } } static int uhso_attach_ifnet(struct uhso_softc *sc, struct usb_interface *iface, int type) { struct ifnet *ifp; usb_error_t uerr; struct sysctl_ctx_list *sctx; struct sysctl_oid *soid; unsigned int devunit; uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_if_xfer, uhso_ifnet_config, UHSO_IFNET_MAX, sc, &sc->sc_mtx); if (uerr) { UHSO_DPRINTF(0, "usbd_transfer_setup failed: %s\n", usbd_errstr(uerr)); return (-1); } sc->sc_ifp = ifp = if_alloc(IFT_OTHER); if (sc->sc_ifp == NULL) { device_printf(sc->sc_dev, "if_alloc() failed\n"); return (-1); } callout_init_mtx(&sc->sc_c, &sc->sc_mtx, 0); mtx_lock(&sc->sc_mtx); callout_reset(&sc->sc_c, 1, uhso_if_rxflush, sc); mtx_unlock(&sc->sc_mtx); /* * We create our own unit numbers for ifnet devices because the * USB interface unit numbers can be at arbitrary positions yielding * odd looking device names. */ devunit = alloc_unr(uhso_ifnet_unit); if_initname(ifp, device_get_name(sc->sc_dev), devunit); ifp->if_mtu = UHSO_MAX_MTU; ifp->if_ioctl = uhso_if_ioctl; ifp->if_init = uhso_if_init; ifp->if_start = uhso_if_start; ifp->if_output = uhso_if_output; ifp->if_flags = IFF_BROADCAST | IFF_MULTICAST | IFF_NOARP; ifp->if_softc = sc; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); if_attach(ifp); bpfattach(ifp, DLT_RAW, 0); sctx = device_get_sysctl_ctx(sc->sc_dev); soid = device_get_sysctl_tree(sc->sc_dev); /* Unlocked read... */ SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "netif", CTLFLAG_RD, ifp->if_xname, 0, "Attached network interface"); return (0); } static void uhso_ifnet_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct mbuf *m; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status=%d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen > 0 && (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING)) { pc = usbd_xfer_get_frame(xfer, 0); m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR); usbd_copy_out(pc, 0, mtod(m, uint8_t *), actlen); m->m_pkthdr.len = m->m_len = actlen; /* Enqueue frame for further processing */ _IF_ENQUEUE(&sc->sc_rxq, m); if (!callout_pending(&sc->sc_c) || !callout_active(&sc->sc_c)) { callout_schedule(&sc->sc_c, 1); } } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } /* * Deferred RX processing, called with mutex locked. * * Each frame we receive might contain several small ip-packets as well * as partial ip-packets. We need to separate/assemble them into individual * packets before sending them to the ip-layer. */ static void uhso_if_rxflush(void *arg) { struct uhso_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint8_t *cp; struct mbuf *m, *m0, *mwait; struct ip *ip; #ifdef INET6 struct ip6_hdr *ip6; #endif uint16_t iplen; int len, isr; m = NULL; mwait = sc->sc_mwait; for (;;) { if (m == NULL) { _IF_DEQUEUE(&sc->sc_rxq, m); if (m == NULL) break; UHSO_DPRINTF(3, "dequeue m=%p, len=%d\n", m, m->m_len); } mtx_unlock(&sc->sc_mtx); /* Do we have a partial packet waiting? */ if (mwait != NULL) { m0 = mwait; mwait = NULL; UHSO_DPRINTF(3, "partial m0=%p(%d), concat w/ m=%p(%d)\n", m0, m0->m_len, m, m->m_len); len = m->m_len + m0->m_len; /* Concat mbufs and fix headers */ m_cat(m0, m); m0->m_pkthdr.len = len; m->m_flags &= ~M_PKTHDR; m = m_pullup(m0, sizeof(struct ip)); if (m == NULL) { ifp->if_ierrors++; UHSO_DPRINTF(0, "m_pullup failed\n"); mtx_lock(&sc->sc_mtx); continue; } UHSO_DPRINTF(3, "Constructed mbuf=%p, len=%d\n", m, m->m_pkthdr.len); } cp = mtod(m, uint8_t *); ip = (struct ip *)cp; #ifdef INET6 ip6 = (struct ip6_hdr *)cp; #endif /* Check for IPv4 */ if (ip->ip_v == IPVERSION) { iplen = htons(ip->ip_len); isr = NETISR_IP; } #ifdef INET6 /* Check for IPv6 */ else if ((ip6->ip6_vfc & IPV6_VERSION_MASK) == IPV6_VERSION) { iplen = htons(ip6->ip6_plen); isr = NETISR_IPV6; } #endif else { UHSO_DPRINTF(0, "got unexpected ip version %d, " "m=%p, len=%d\n", (*cp & 0xf0) >> 4, m, m->m_len); ifp->if_ierrors++; UHSO_HEXDUMP(cp, 4); m_freem(m); m = NULL; mtx_lock(&sc->sc_mtx); continue; } if (iplen == 0) { UHSO_DPRINTF(0, "Zero IP length\n"); ifp->if_ierrors++; m_freem(m); m = NULL; mtx_lock(&sc->sc_mtx); continue; } UHSO_DPRINTF(3, "m=%p, len=%d, cp=%p, iplen=%d\n", m, m->m_pkthdr.len, cp, iplen); m0 = NULL; /* More IP packets in this mbuf */ if (iplen < m->m_pkthdr.len) { m0 = m; /* * Allocate a new mbuf for this IP packet and * copy the IP-packet into it. */ m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR); memcpy(mtod(m, uint8_t *), mtod(m0, uint8_t *), iplen); m->m_pkthdr.len = m->m_len = iplen; /* Adjust the size of the original mbuf */ m_adj(m0, iplen); m0 = m_defrag(m0, M_WAIT); UHSO_DPRINTF(3, "New mbuf=%p, len=%d/%d, m0=%p, " "m0_len=%d/%d\n", m, m->m_pkthdr.len, m->m_len, m0, m0->m_pkthdr.len, m0->m_len); } else if (iplen > m->m_pkthdr.len) { UHSO_DPRINTF(3, "Deferred mbuf=%p, len=%d\n", m, m->m_pkthdr.len); mwait = m; m = NULL; mtx_lock(&sc->sc_mtx); continue; } ifp->if_ipackets++; m->m_pkthdr.rcvif = ifp; /* Dispatch to IP layer */ BPF_MTAP(sc->sc_ifp, m); M_SETFIB(m, ifp->if_fib); netisr_dispatch(isr, m); m = m0 != NULL ? m0 : NULL; mtx_lock(&sc->sc_mtx); } sc->sc_mwait = mwait; } static void uhso_ifnet_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct usb_page_cache *pc; struct mbuf *m; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: ifp->if_opackets++; ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; case USB_ST_SETUP: tr_setup: IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; ifp->if_drv_flags |= IFF_DRV_OACTIVE; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); pc = usbd_xfer_get_frame(xfer, 0); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_transfer_submit(xfer); BPF_MTAP(ifp, m); m_freem(m); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static int uhso_if_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct uhso_softc *sc; sc = ifp->if_softc; switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { uhso_if_init(sc); } } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) { mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); mtx_unlock(&sc->sc_mtx); } } break; case SIOCSIFADDR: case SIOCSIFDSTADDR: case SIOCADDMULTI: case SIOCDELMULTI: break; default: return (EINVAL); } return (0); } static void uhso_if_init(void *priv) { struct uhso_softc *sc = priv; struct ifnet *ifp = sc->sc_ifp; mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); ifp = sc->sc_ifp; ifp->if_flags |= IFF_UP; ifp->if_drv_flags |= IFF_DRV_RUNNING; mtx_unlock(&sc->sc_mtx); UHSO_DPRINTF(2, "ifnet initialized\n"); } static int uhso_if_output(struct ifnet *ifp, struct mbuf *m0, struct sockaddr *dst, struct route *ro) { int error; /* Only IPv4/6 support */ if (dst->sa_family != AF_INET #ifdef INET6 && dst->sa_family != AF_INET6 #endif ) { return (EAFNOSUPPORT); } error = (ifp->if_transmit)(ifp, m0); if (error) { ifp->if_oerrors++; return (ENOBUFS); } ifp->if_opackets++; return (0); } static void uhso_if_start(struct ifnet *ifp, struct ifaltq_subque *ifsq) { struct uhso_softc *sc = ifp->if_softc; ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { UHSO_DPRINTF(1, "Not running\n"); return; } mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_if_xfer[UHSO_IFNET_READ]); usbd_transfer_start(sc->sc_if_xfer[UHSO_IFNET_WRITE]); mtx_unlock(&sc->sc_mtx); UHSO_DPRINTF(3, "interface started\n"); } static void uhso_if_stop(struct uhso_softc *sc) { usbd_transfer_stop(sc->sc_if_xfer[UHSO_IFNET_READ]); usbd_transfer_stop(sc->sc_if_xfer[UHSO_IFNET_WRITE]); sc->sc_ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); }
25.979079
80
0.703515
d68d66109725a6743e7a6bfd5ca42d9956d97a7b
81
c
C
src/curses/raw.c
ung-org/lib-c
55fc64c7ffd7792bc88451a736c2e94e5865282f
[ "MIT" ]
null
null
null
src/curses/raw.c
ung-org/lib-c
55fc64c7ffd7792bc88451a736c2e94e5865282f
[ "MIT" ]
null
null
null
src/curses/raw.c
ung-org/lib-c
55fc64c7ffd7792bc88451a736c2e94e5865282f
[ "MIT" ]
null
null
null
#include <curses.h> int raw(void) { return ERR; } /* XOPEN(4) LINK(curses) */
6.75
19
0.604938
04dddb5e22c7cc6da414d3b15be2d26cff72a5db
1,442
h
C
ui/views/animation/animation_abort_handle.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
ui/views/animation/animation_abort_handle.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
ui/views/animation/animation_abort_handle.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2021 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 UI_VIEWS_ANIMATION_ANIMATION_ABORT_HANDLE_H_ #define UI_VIEWS_ANIMATION_ANIMATION_ABORT_HANDLE_H_ #include <set> #include "base/gtest_prod_util.h" #include "ui/views/animation/animation_builder.h" #include "ui/views/views_export.h" namespace ui { class Layer; } // namespace ui namespace views { // A handle that aborts associated animations on destruction. // Caveat: ALL properties will be aborted on handle destruction, // including those not initiated by the builder. class VIEWS_EXPORT AnimationAbortHandle { public: ~AnimationAbortHandle(); void OnObserverDeleted(); private: friend class AnimationBuilder; FRIEND_TEST_ALL_PREFIXES(AnimationBuilderTest, AbortHandle); enum class AnimationState { kNotStarted, kRunning, kEnded }; explicit AnimationAbortHandle(AnimationBuilder::Observer* observer); // Called when an animation is created for `layer`. void AddLayer(ui::Layer* layer); void OnAnimationStarted(); void OnAnimationEnded(); AnimationState animation_state() const { return animation_state_; } AnimationBuilder::Observer* observer_; std::set<ui::Layer*> layers_; AnimationState animation_state_ = AnimationState::kNotStarted; }; } // namespace views #endif // UI_VIEWS_ANIMATION_ANIMATION_ABORT_HANDLE_H_
27.207547
73
0.781553
e70f0e2afa898dffaef40cf0a5acd124ba6a1b7f
18,182
c
C
third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/tests/nameshm1.c
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/tests/nameshm1.c
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/tests/nameshm1.c
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape Portable Runtime (NSPR). * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ** File: nameshm1.c -- Test Named Shared Memory ** ** Description: ** nameshm1 tests Named Shared Memory. nameshm1 performs two tests of ** named shared memory. ** ** The first test is a basic test. The basic test operates as a single ** process. The process exercises all the API elements of the facility. ** This test also attempts to write to all locations in the shared ** memory. ** ** The second test is a client-server test. The client-server test ** creates a new instance of nameshm1, passing the -C argument to the ** new process; this creates the client-side process. The server-side ** (the instance of nameshm1 created from the command line) and the ** client-side interact via inter-process semaphores to verify that the ** shared memory segment can be read and written by both sides in a ** synchronized maner. ** ** Note: Because this test runs in two processes, the log files created ** by the test are not in chronological sequence; makes it hard to read. ** As a temporary circumvention, I changed the definition(s) of the ** _PUT_LOG() macro in prlog.c to force a flushall(), or equivalent. ** This causes the log entries to be emitted in true chronological ** order. ** ** Synopsis: nameshm1 [options] [name] ** ** Options: ** -d Enables debug trace via PR_LOG() ** -v Enables verbose mode debug trace via PR_LOG() ** -w Causes the basic test to attempt to write to the segment ** mapped as read-only. When this option is specified, the ** test should crash with a seg-fault; this is a destructive ** test and is considered successful when it seg-faults. ** ** -C Causes nameshm1 to start as the client-side of a ** client-server pair of processes. Only the instance ** of nameshm1 operating as the server-side process should ** specify the -C option when creating the client-side process; ** the -C option should not be specified at the command line. ** The client-side uses the shared memory segment created by ** the server-side to communicate with the server-side ** process. ** ** -p <n> Specify the number of iterations the client-server tests ** should perform. Default: 1000. ** ** -s <n> Size, in KBytes (1024), of the shared memory segment. ** Default: (10 * 1024) ** ** -i <n> Number of client-side iterations. Default: 3 ** ** name specifies the name of the shared memory segment to be used. ** Default: /tmp/xxxNSPRshm ** ** ** See also: prshm.h ** ** /lth. Aug-1999. */ #include <plgetopt.h> #include <nspr.h> #include <stdlib.h> #include <string.h> #include <private/primpl.h> #define SEM_NAME1 "/tmp/nameshmSEM1" #define SEM_NAME2 "/tmp/nameshmSEM2" #define SEM_MODE 0666 #define SHM_MODE 0666 #define NameSize (1024) PRIntn debug = 0; PRIntn failed_already = 0; PRLogModuleLevel msgLevel = PR_LOG_NONE; PRLogModuleInfo *lm; /* command line options */ PRIntn optDebug = 0; PRIntn optVerbose = 0; PRUint32 optWriteRO = 0; /* test write to read-only memory. should crash */ PRUint32 optClient = 0; PRUint32 optCreate = 1; PRUint32 optAttachRW = 1; PRUint32 optAttachRO = 1; PRUint32 optClose = 1; PRUint32 optDelete = 1; PRInt32 optPing = 1000; PRUint32 optSize = (10 * 1024 ); PRInt32 optClientIterations = 3; char optName[NameSize] = "/tmp/xxxNSPRshm"; char buf[1024] = ""; static void BasicTest( void ) { PRSharedMemory *shm; char *addr; /* address of shared memory segment */ PRUint32 i; PRInt32 rc; PR_LOG( lm, msgLevel, ( "nameshm1: Begin BasicTest" )); if ( PR_FAILURE == PR_DeleteSharedMemory( optName )) { PR_LOG( lm, msgLevel, ("nameshm1: Initial PR_DeleteSharedMemory() failed. No problem")); } else PR_LOG( lm, msgLevel, ("nameshm1: Initial PR_DeleteSharedMemory() success")); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE ); if ( NULL == shm ) { PR_LOG( lm, msgLevel, ( "nameshm1: RW Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RW Create: success: %p", shm )); addr = PR_AttachSharedMemory( shm , 0 ); if ( NULL == addr ) { PR_LOG( lm, msgLevel, ( "nameshm1: RW Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RW Attach: success: %p", addr )); /* fill memory with i */ for ( i = 0; i < optSize ; i++ ) { *(addr + i) = i; } rc = PR_DetachSharedMemory( shm, addr ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RW Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RW Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RW Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RW Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RW Delete: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RW Delete: success: " )); PR_LOG( lm, msgLevel, ("nameshm1: BasicTest(): Passed")); return; } /* end BasicTest() */ static void ReadOnlyTest( void ) { PRSharedMemory *shm; char *roAddr; /* read-only address of shared memory segment */ PRInt32 rc; PR_LOG( lm, msgLevel, ( "nameshm1: Begin ReadOnlyTest" )); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE); if ( NULL == shm ) { PR_LOG( lm, msgLevel, ( "nameshm1: RO Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RO Create: success: %p", shm )); roAddr = PR_AttachSharedMemory( shm , PR_SHM_READONLY ); if ( NULL == roAddr ) { PR_LOG( lm, msgLevel, ( "nameshm1: RO Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RO Attach: success: %p", roAddr )); if ( optWriteRO ) { *roAddr = 0x00; /* write to read-only memory */ failed_already = 1; PR_LOG( lm, msgLevel, ("nameshm1: Wrote to read-only memory segment!")); return; } rc = PR_DetachSharedMemory( shm, roAddr ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RO Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RO Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RO Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RO Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: RO Destroy: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: RO Destroy: success: " )); PR_LOG( lm, msgLevel, ("nameshm1: ReadOnlyTest(): Passed")); return; } /* end ReadOnlyTest() */ static void DoClient( void ) { PRStatus rc; PRSem *sem1, *sem2; PRSharedMemory *shm; PRUint32 *addr; PRInt32 i; PR_LOG( lm, msgLevel, ("nameshm1: DoClient(): Starting")); sem1 = PR_OpenSemaphore( SEM_NAME1, 0, 0, 0 ); PR_ASSERT( sem1 ); sem2 = PR_OpenSemaphore( SEM_NAME2, 0, 0, 0 ); PR_ASSERT( sem1 ); shm = PR_OpenSharedMemory( optName, optSize, 0, SHM_MODE ); if ( NULL == shm ) { PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Create: success: %p", shm )); addr = PR_AttachSharedMemory( shm , 0 ); if ( NULL == addr ) { PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Attach: success: %p", addr )); PR_LOG( lm, msgLevel, ( "Client found: %s", addr)); PR_Sleep(PR_SecondsToInterval(4)); for ( i = 0 ; i < optPing ; i++ ) { rc = PR_WaitSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); (*addr)++; PR_ASSERT( (*addr % 2) == 0 ); if ( optVerbose ) PR_LOG( lm, msgLevel, ( "nameshm1: Client ping: %d, i: %d", *addr, i)); rc = PR_PostSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); } rc = PR_CloseSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_CloseSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_DetachSharedMemory( shm, addr ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: DoClient(): Close: success: " )); return; } /* end DoClient() */ static void ClientServerTest( void ) { PRStatus rc; PRSem *sem1, *sem2; PRProcess *proc; PRInt32 exit_status; PRSharedMemory *shm; PRUint32 *addr; PRInt32 i; char *child_argv[8]; char buf[24]; PR_LOG( lm, msgLevel, ( "nameshm1: Begin ClientServerTest" )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Destroy: failed. No problem")); } else PR_LOG( lm, msgLevel, ( "nameshm1: Server: Destroy: success" )); shm = PR_OpenSharedMemory( optName, optSize, (PR_SHM_CREATE | PR_SHM_EXCL), SHM_MODE); if ( NULL == shm ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Create: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: Server: Create: success: %p", shm )); addr = PR_AttachSharedMemory( shm , 0 ); if ( NULL == addr ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Attach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: Server: Attach: success: %p", addr )); sem1 = PR_OpenSemaphore( SEM_NAME1, PR_SEM_CREATE, SEM_MODE, 0 ); PR_ASSERT( sem1 ); sem2 = PR_OpenSemaphore( SEM_NAME2, PR_SEM_CREATE, SEM_MODE, 1 ); PR_ASSERT( sem1 ); strcpy( (char*)addr, "FooBar" ); child_argv[0] = "nameshm1"; child_argv[1] = "-C"; child_argv[2] = "-p"; sprintf( buf, "%d", optPing ); child_argv[3] = buf; child_argv[4] = optName; child_argv[5] = NULL; proc = PR_CreateProcess(child_argv[0], child_argv, NULL, NULL); PR_ASSERT( proc ); PR_Sleep( PR_SecondsToInterval(4)); *addr = 1; for ( i = 0 ; i < optPing ; i++ ) { rc = PR_WaitSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); (*addr)++; PR_ASSERT( (*addr % 2) == 1 ); if ( optVerbose ) PR_LOG( lm, msgLevel, ( "nameshm1: Server pong: %d, i: %d", *addr, i)); rc = PR_PostSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); } rc = PR_WaitProcess( proc, &exit_status ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_CloseSemaphore( sem1 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_CloseSemaphore( sem2 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_DeleteSemaphore( SEM_NAME1 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_DeleteSemaphore( SEM_NAME2 ); PR_ASSERT( PR_FAILURE != rc ); rc = PR_DetachSharedMemory( shm, addr ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Detach: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: Server: Detach: success: " )); rc = PR_CloseSharedMemory( shm ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Close: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: Server: Close: success: " )); rc = PR_DeleteSharedMemory( optName ); if ( PR_FAILURE == rc ) { PR_LOG( lm, msgLevel, ( "nameshm1: Server: Destroy: Error: %ld. OSError: %ld", PR_GetError(), PR_GetOSError())); failed_already = 1; return; } PR_LOG( lm, msgLevel, ( "nameshm1: Server: Destroy: success" )); return; } /* end ClientServerTest() */ PRIntn main(PRIntn argc, char *argv[]) { { /* ** Get command line options */ PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "Cdvw:s:p:i:"); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { if (PL_OPT_BAD == os) continue; switch (opt->option) { case 'v': /* debug mode */ optVerbose = 1; /* no break! fall into debug option */ case 'd': /* debug mode */ debug = 1; msgLevel = PR_LOG_DEBUG; break; case 'w': /* try writing to memory mapped read-only */ optWriteRO = 1; break; case 'C': optClient = 1; break; case 's': optSize = atol(opt->value) * 1024; break; case 'p': optPing = atol(opt->value); break; case 'i': optClientIterations = atol(opt->value); break; default: strcpy( optName, opt->value ); break; } } PL_DestroyOptState(opt); } lm = PR_NewLogModule("Test"); /* Initialize logging */ PR_LOG( lm, msgLevel, ( "nameshm1: Starting" )); if ( optClient ) { DoClient(); } else { BasicTest(); if ( failed_already != 0 ) goto Finished; ReadOnlyTest(); if ( failed_already != 0 ) goto Finished; ClientServerTest(); } Finished: if ( debug ) printf("%s\n", (failed_already)? "FAIL" : "PASS" ); return( (failed_already)? 1 : 0 ); } /* main() */ /* end instrumt.c */
30.303333
106
0.570729
30dc3fc23c0681d2968c4eb4605d1058b2a39db6
1,575
h
C
Library/Base/inc/power-saving.h
gicking/STM8_templates
c077e23f8cc5f6eb4b301eecb91d2d121f905719
[ "Apache-2.0" ]
29
2015-10-30T08:05:14.000Z
2021-08-09T10:29:43.000Z
Library/Base/inc/power-saving.h
gicking/STM8_templates
c077e23f8cc5f6eb4b301eecb91d2d121f905719
[ "Apache-2.0" ]
6
2017-12-22T15:44:54.000Z
2018-12-17T09:55:13.000Z
Library/Base/inc/power-saving.h
gicking/STM8_templates
c077e23f8cc5f6eb4b301eecb91d2d121f905719
[ "Apache-2.0" ]
10
2016-04-19T07:30:26.000Z
2020-05-11T21:44:29.000Z
/** \file power-saving.h \author G. Icking-Konert \date 2018-01-20 \version 0.1 \brief declaration of functions/macros for low-power modes declaration of functions/macros for low-power modes Optional functionality via #define: - see ISR of respective wake peripheral! */ /*----------------------------------------------------------------------------- MODULE DEFINITION FOR MULTIPLE INCLUSION -----------------------------------------------------------------------------*/ #ifndef _POWER_SAVING_H_ #define _POWER_SAVING_H_ /*----------------------------------------------------------------------------- INCLUDE FILES -----------------------------------------------------------------------------*/ #include <stdint.h> #include "stm8as.h" #include "config.h" #include "awu.h" /*----------------------------------------------------------------------------- DECLARATION OF GLOBAL FUNCTIONS -----------------------------------------------------------------------------*/ /// enter WAIT mode: only stop CPU, wake via any interrupt void lowPower_Wait(void); /// enter HALT mode: all clocks off, wake only via EXINT void lowPower_Halt(void); /// enter active HALT mode: only LSI active, wake via AWU or EXINT void lowPower_HaltAWU(uint16_t ms); /*----------------------------------------------------------------------------- END OF MODULE DEFINITION FOR MULTIPLE INLUSION -----------------------------------------------------------------------------*/ #endif // _POWER_SAVING_H_
32.142857
80
0.412698
bdd4b5c76b31f719237c3d0834c2ef4c2f90353d
29,732
h
C
mobiledevice.h
RuudPuts/mobiledevice
626d54c4be8d0657e5a95c04ba5ae405a7478c16
[ "MIT" ]
null
null
null
mobiledevice.h
RuudPuts/mobiledevice
626d54c4be8d0657e5a95c04ba5ae405a7478c16
[ "MIT" ]
null
null
null
mobiledevice.h
RuudPuts/mobiledevice
626d54c4be8d0657e5a95c04ba5ae405a7478c16
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------------- * MobileDevice.h - interface to MobileDevice.framework * * Adapted from http://theiphonewiki.com/wiki/index.php?title=MobileDevice_Library * ------------------------------------------------------------------------- */ #ifndef MOBILEDEVICE_H #define MOBILEDEVICE_H #ifdef __cplusplus extern "C" { #endif #ifndef __GNUC__ #pragma pack #define __PACK #else #define __PACK __attribute__((__packed__)) #endif #if defined(WIN32) #define __DLLIMPORT [DllImport("iTunesMobileDevice.dll")] using namespace System::Runtime::InteropServices; #include <CoreFoundation.h> typedef unsigned int mach_error_t; #elif defined(__APPLE__) #define __DLLIMPORT #include <CoreFoundation/CoreFoundation.h> #include <mach/error.h> #endif /* Error codes */ #define MDERR_APPLE_MOBILE (err_system(0x3a)) #define MDERR_IPHONE (err_sub(0)) /* Apple Mobile (AM*) errors */ #define MDERR_OK ERR_SUCCESS #define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01) #define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03) #define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04) #define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b) #define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25) /* Apple File Connection (AFC*) errors */ #define MDERR_AFC_OUT_OF_MEMORY 0x03 /* USBMux errors */ #define MDERR_USBMUX_ARG_NULL 0x16 #define MDERR_USBMUX_FAILED 0xffffffff /* Messages passed to device notification callbacks: passed as part of * am_device_notification_callback_info. */ #define ADNCI_MSG_CONNECTED 1 #define ADNCI_MSG_DISCONNECTED 2 #define ADNCI_MSG_UNSUBSCRIBED 3 #define AMD_IPHONE_PRODUCT_ID 0x1290 //#define AMD_IPHONE_SERIAL "" /* Services, found in /System/Library/Lockdown/Services.plist */ #define AMSVC_AFC CFSTR("com.apple.afc") #define AMSVC_BACKUP CFSTR("com.apple.mobilebackup") #define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy") #define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount") #define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy") #define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr") #define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update") #define AMSVC_SYNC CFSTR("com.apple.mobilesync") #define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr") #define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay") #define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler") typedef unsigned int service_conn_t; typedef unsigned int afc_error_t; typedef unsigned int usbmux_error_t; struct am_recovery_device; struct am_device_notification_callback_info { struct am_device *dev; /* 0 device */ unsigned int msg; /* 4 one of ADNCI_MSG_* */ struct am_device_notification* subscription; } __PACK; /* The type of the device restore notification callback functions. * TODO: change to correct type. */ typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *); /* This is a CoreFoundation object of class AMRecoveryModeDevice. */ struct am_recovery_device { unsigned char unknown0[8]; /* 0 */ am_restore_device_notification_callback callback; /* 8 */ void *user_info; /* 12 */ unsigned char unknown1[12]; /* 16 */ unsigned int readwrite_pipe; /* 28 */ unsigned char read_pipe; /* 32 */ unsigned char write_ctrl_pipe; /* 33 */ unsigned char read_unknown_pipe; /* 34 */ unsigned char write_file_pipe; /* 35 */ unsigned char write_input_pipe; /* 36 */ } __PACK; /* A CoreFoundation object of class AMRestoreModeDevice. */ struct am_restore_device { unsigned char unknown[32]; int port; } __PACK; /* The type of the device notification callback function. */ typedef void(*am_device_notification_callback)(struct am_device_notification_callback_info *, int cookie); /* The type of the _AMDDeviceAttached function. * TODO: change to correct type. */ typedef void *amd_device_attached_callback; /* Structure that contains internal data used by AMDevice... functions. Never try * to access its members directly! Use AMDeviceCopyDeviceIdentifier, * AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */ struct am_device { unsigned char unknown0[16]; /* 0 - zero */ unsigned int device_id; /* 16 */ unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */ char *serial; /* 24 - set to UDID, Unique Device Identifier */ unsigned int unknown1; /* 28 */ unsigned int unknown2; /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease*/ unsigned int lockdown_conn; /* 36 */ unsigned char unknown3[8]; /* 40 */ #if (__ITUNES_VER > 740) unsigned int unknown4; /* 48 - used to store CriticalSection Handle*/ #endif #if (__ITUNES_VER >= 800) unsigned char unknown5[24]; /* 52 */ #endif } __PACK; struct am_device_notification { unsigned int unknown0; /* 0 */ unsigned int unknown1; /* 4 */ unsigned int unknown2; /* 8 */ am_device_notification_callback callback; /* 12 */ unsigned int cookie; /* 16 */ } __PACK; struct afc_connection { unsigned int handle; /* 0 */ unsigned int unknown0; /* 4 */ unsigned char unknown1; /* 8 */ unsigned char padding[3]; /* 9 */ unsigned int unknown2; /* 12 */ unsigned int unknown3; /* 16 */ unsigned int unknown4; /* 20 */ unsigned int fs_block_size; /* 24 */ unsigned int sock_block_size; /* 28: always 0x3c */ unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */ void *afc_lock; /* 36 */ unsigned int context; /* 40 */ } __PACK; struct afc_device_info { unsigned char unknown[12]; /* 0 */ } __PACK; struct afc_directory { unsigned char unknown[0]; /* size unknown */ } __PACK; struct afc_dictionary { unsigned char unknown[0]; /* size unknown */ } __PACK; typedef unsigned long long afc_file_ref; struct usbmux_listener_1 { /* offset value in iTunes */ unsigned int unknown0; /* 0 1 */ unsigned char *unknown1; /* 4 ptr, maybe device? */ amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */ unsigned int unknown3; /* 12 */ unsigned int unknown4; /* 16 */ unsigned int unknown5; /* 20 */ } __PACK; struct usbmux_listener_2 { unsigned char unknown0[4144]; } __PACK; struct am_bootloader_control_packet { unsigned char opcode; /* 0 */ unsigned char length; /* 1 */ unsigned char magic[2]; /* 2: 0x34, 0x12 */ unsigned char payload[0]; /* 4 */ } __PACK; /* ---------------------------------------------------------------------------- * Public routines * ------------------------------------------------------------------------- */ /* Registers a notification with the current run loop. The callback gets * copied into the notification struct, as well as being registered with the * current run loop. Cookie gets copied into cookie in the same. * (Cookie is a user info parameter that gets passed as an arg to * the callback) unused0 and unused1 are both 0 when iTunes calls this. * * Never try to acces directly or copy contents of dev and subscription fields * in am_device_notification_callback_info. Treat them as abstract handles. * When done with connection use AMDeviceRelease to free resources allocated for am_device. * * Returns: * MDERR_OK if successful * MDERR_SYSCALL if CFRunLoopAddSource() failed * MDERR_OUT_OF_MEMORY if we ran out of memory */ __DLLIMPORT mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback callback, unsigned int unused0, unsigned int unused1, unsigned int cookie, struct am_device_notification **subscription); /* Unregisters notifications. Buggy (iTunes 8.2): if you subscribe, unsubscribe and subscribe again, arriving notifications will contain cookie and subscription from 1st call to subscribe, not the 2nd one. iTunes calls this function only once on exit. */ __DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(struct am_device_notification* subscription); /* Returns device_id field of am_device structure */ __DLLIMPORT unsigned int AMDeviceGetConnectionID(struct am_device *device); /* Returns serial field of am_device structure */ __DLLIMPORT CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device); /* Connects to the iPhone. Pass in the am_device structure that the * notification callback will give to you. * * Returns: * MDERR_OK if successfully connected * MDERR_SYSCALL if setsockopt() failed * MDERR_QUERY_FAILED if the daemon query failed * MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff */ __DLLIMPORT mach_error_t AMDeviceConnect(struct am_device *device); /* Calls PairingRecordPath() on the given device, than tests whether the path * which that function returns exists. During the initial connect, the path * returned by that function is '/', and so this returns 1. * * Returns: * 0 if the path did not exist * 1 if it did */ __DLLIMPORT mach_error_t AMDeviceIsPaired(struct am_device *device); __DLLIMPORT mach_error_t AMDevicePair(struct am_device *device); /* iTunes calls this function immediately after testing whether the device is * paired. It creates a pairing file and establishes a Lockdown connection. * * Returns: * MDERR_OK if successful * MDERR_INVALID_ARGUMENT if the supplied device is null * MDERR_DICT_NOT_LOADED if the load_dict() call failed */ __DLLIMPORT mach_error_t AMDeviceValidatePairing(struct am_device *device); /* Creates a Lockdown session and adjusts the device structure appropriately * to indicate that the session has been started. iTunes calls this function * after validating pairing. * * Returns: * MDERR_OK if successful * MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established * MDERR_DICT_NOT_LOADED if the load_dict() call failed */ __DLLIMPORT mach_error_t AMDeviceStartSession(struct am_device *device); /* Reads various device settings. One of domain or cfstring arguments should be NULL. * * ActivationPublicKey * ActivationState * ActivationStateAcknowledged * ActivityURL * BasebandBootloaderVersion * BasebandSerialNumber * BasebandStatus * BasebandVersion * BluetoothAddress * BuildVersion * CPUArchitecture * DeviceCertificate * DeviceClass * DeviceColor * DeviceName * DevicePublicKey * DieID * FirmwareVersion * HardwareModel * HardwarePlatform * HostAttached * IMLockdownEverRegisteredKey * IntegratedCircuitCardIdentity * InternationalMobileEquipmentIdentity * InternationalMobileSubscriberIdentity * iTunesHasConnected * MLBSerialNumber * MobileSubscriberCountryCode * MobileSubscriberNetworkCode * ModelNumber * PartitionType * PasswordProtected * PhoneNumber * ProductionSOC * ProductType * ProductVersion * ProtocolVersion * ProximitySensorCalibration * RegionInfo * SBLockdownEverRegisteredKey * SerialNumber * SIMStatus * SoftwareBehavior * SoftwareBundleVersion * SupportedDeviceFamilies * TelephonyCapability * TimeIntervalSince1970 * TimeZone * TimeZoneOffsetFromUTC * TrustedHostAttached * UniqueChipID * UniqueDeviceID * UseActivityURL * UseRaptorCerts * Uses24HourClock * WeDelivered * WiFiAddress * // Updated by DiAifU 14.10.2010 for iOS5 and iTunes 5.0 * * Possible values for domain: * com.apple.mobile.battery */ __DLLIMPORT CFStringRef AMDeviceCopyValue(struct am_device *device, CFStringRef domain, CFStringRef cfstring); /* Starts a service and returns a socket file descriptor that can be used in order to further * access the service. You should stop the session and disconnect before using * the service. iTunes calls this function after starting a session. It starts * the service and the SSL connection. service_name should be one of the AMSVC_* * constants. * * Returns: * MDERR_OK if successful * MDERR_SYSCALL if the setsockopt() call failed * MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established */ __DLLIMPORT mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef service_name, int *socket_fd); /* Stops a session. You should do this before accessing services. * * Returns: * MDERR_OK if successful * MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established */ __DLLIMPORT mach_error_t AMDeviceStopSession(struct am_device *device); /* Decrements reference counter and, if nothing left, releases resources hold * by connection, invalidates pointer to device */ __DLLIMPORT void AMDeviceRelease(struct am_device *device); /* Increments reference counter */ __DLLIMPORT void AMDeviceRetain(struct am_device *device); /* Opens an Apple File Connection. You must start the appropriate service * first with AMDeviceStartService(). In iTunes, io_timeout is 0. * * Returns: * MDERR_OK if successful * MDERR_AFC_OUT_OF_MEMORY if malloc() failed */ __DLLIMPORT afc_error_t AFCConnectionOpen(int socket_fd, unsigned int io_timeout, struct afc_connection **conn); /* Copy an enviromental variable value from iBoot */ __DLLIMPORT CFStringRef AMRecoveryModeCopyEnvironmentVariable(struct am_recovery_device *rdev, CFStringRef var); /* Pass in a pointer to an afc_dictionary structure. It will be filled. You can * iterate it using AFCKeyValueRead. When done use AFCKeyValueClose. Possible keys: * FSFreeBytes - free bytes on system device for afc2, user device for afc * FSBlockSize - filesystem block size * FSTotalBytes - size of device * Model - iPhone1,1 etc. */ __DLLIMPORT afc_error_t AFCDeviceInfoOpen(struct afc_connection *conn, struct afc_dictionary **info); /* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric * value, or if the file '/AFCDEBUG' is present and contains a value. */ #if defined(__APPLE__) void AFCPlatformInitialize(); #endif /* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in. * Note that this normally only accesses the iTunes sandbox/partition as the * root, which is /var/root/Media. Pathnames are specified with '/' delimiters * as in Unix style. Use UTF-8 to specify non-ASCII symbols in path. * * Returns: * MDERR_OK if successful */ __DLLIMPORT afc_error_t AFCDirectoryOpen(struct afc_connection *conn, char *path, struct afc_directory **dir); /* Acquires the next entry in a directory previously opened with * AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end * of the directory has been reached. '.' and '..' will be returned as the * first two entries in each directory except the root; you may want to skip * over them. * * Returns: * MDERR_OK if successful, even if no entries remain */ __DLLIMPORT afc_error_t AFCDirectoryRead(struct afc_connection *conn, struct afc_directory *dir, char **dirent); __DLLIMPORT afc_error_t AFCDirectoryClose(struct afc_connection *conn, struct afc_directory *dir); __DLLIMPORT afc_error_t AFCDirectoryCreate(struct afc_connection *conn, char *dirname); __DLLIMPORT afc_error_t AFCRemovePath(struct afc_connection *conn, char *dirname); __DLLIMPORT afc_error_t AFCRenamePath(struct afc_connection *conn, char *oldpath, char *newpath); #if (__ITUNES_VER >= 800) /* Creates symbolic or hard link * linktype - int64: 1 means hard link, 2 - soft (symbolic) link * target - absolute or relative path to link target * linkname - absolute path where to create new link */ __DLLIMPORT afc_error_t AFCLinkPath(struct afc_connection *conn, long long int linktype, const char *target, const char *linkname); #endif /* Opens file for reading or writing without locking it in any way. afc_file_ref should not be shared between threads - * opening file in one thread and closing it in another will lead to possible crash. * path - UTF-8 encoded absolute path to file * mode 2 = read, mode 3 = write; unknown = 0 * ref - receives file handle */ __DLLIMPORT afc_error_t AFCFileRefOpen(struct afc_connection *conn, char *path, unsigned long long int mode, afc_file_ref *ref); /* Reads specified amount (len) of bytes from file into buf. Puts actual count of read bytes into len on return */ __DLLIMPORT afc_error_t AFCFileRefRead(struct afc_connection *conn, afc_file_ref ref, void *buf, unsigned int *len); /* Writes specified amount (len) of bytes from buf into file. */ __DLLIMPORT afc_error_t AFCFileRefWrite(struct afc_connection *conn, afc_file_ref ref, void *buf, unsigned int len); /* Moves the file pointer to a specified location. * offset - Number of bytes from origin (int64) * origin - 0 = from beginning, 1 = from current position, 2 = from end */ __DLLIMPORT afc_error_t AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref, unsigned long long offset, int origin, int unused); /* Gets the current position of a file pointer into offset argument. */ __DLLIMPORT afc_error_t AFCFileRefTell(struct afc_connection *conn, afc_file_ref ref, unsigned long long* offset); /* Truncates a file at the specified offset. */ __DLLIMPORT afc_error_t AFCFileRefSetFileSize(struct afc_connection *conn, afc_file_ref ref, unsigned long long offset); __DLLIMPORT afc_error_t AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref); __DLLIMPORT afc_error_t AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref); __DLLIMPORT afc_error_t AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref); /* Opens dictionary describing specified file or directory (iTunes below 8.2 allowed using AFCGetFileInfo to get the same information) */ __DLLIMPORT afc_error_t AFCFileInfoOpen(struct afc_connection *conn, char *path, struct afc_dictionary **info); /* Reads next entry from dictionary. When last entry is read, function returns NULL in key argument Possible keys: "st_size": val - size in bytes "st_blocks": val - size in blocks "st_nlink": val - number of hardlinks "st_ifmt": val - "S_IFDIR" for folders "S_IFLNK" for symlinks "LinkTarget": val - path to symlink target */ __DLLIMPORT afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char ** val); /* Closes dictionary */ __DLLIMPORT afc_error_t AFCKeyValueClose(struct afc_dictionary *dict); /* Returns the context field of the given AFC connection. */ __DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn); /* Returns the fs_block_size field of the given AFC connection. */ __DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn); /* Returns the io_timeout field of the given AFC connection. In iTunes this is * 0. */ __DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn); /* Returns the sock_block_size field of the given AFC connection. */ __DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn); /* Closes the given AFC connection. */ __DLLIMPORT afc_error_t AFCConnectionClose(struct afc_connection *conn); /* Registers for device notifications related to the restore process. unknown0 * is zero when iTunes calls this. In iTunes, * the callbacks are located at: * 1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0) * 2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg) * 3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0) * 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg) */ __DLLIMPORT unsigned int AMRestoreRegisterForDeviceNotifications( am_restore_device_notification_callback dfu_connect_callback, am_restore_device_notification_callback recovery_connect_callback, am_restore_device_notification_callback dfu_disconnect_callback, am_restore_device_notification_callback recovery_disconnect_callback, unsigned int unknown0, void *user_info); /* Causes the restore functions to spit out (unhelpful) progress messages to * the file specified by the given path. iTunes always calls this right before * restoring with a path of * "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an * unused number. */ __DLLIMPORT unsigned int AMRestoreEnableFileLogging(char *path); /* Initializes a new option dictionary to default values. Pass the constant * kCFAllocatorDefault as the allocator. The option dictionary looks as * follows: * { * NORImageType => 'production', * AutoBootDelay => 0, * KernelCacheType => 'Release', * UpdateBaseband => true, * DFUFileType => 'RELEASE', * SystemImageType => 'User', * CreateFilesystemPartitions => true, * FlashNOR => true, * RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress' * BootImageType => 'User' * } * * Returns: * the option dictionary if successful * NULL if out of memory */ __DLLIMPORT CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator); /* ---------------------------------------------------------------------------- * Less-documented public routines * ------------------------------------------------------------------------- */ __DLLIMPORT unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device * rdev, CFDictionaryRef opts, void *callback, void *user_info); __DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device * rdev, CFDictionaryRef opts, void *callback, void *user_info); __DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0, unsigned int connection_id, unsigned int unknown1); __DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path, CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int unknown0, CFStringRef *firmware_dir_path, CFStringRef * kernelcache_restore_path, unsigned int unknown1, CFStringRef * ramdisk_path); __DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev); // Added by JB 30.07.2008 __DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device); __DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device); /* to use this, start the service "com.apple.mobile.notification_proxy", handle will be the socket to use */ typedef void (*notify_callback)(CFStringRef notification, void* data); __DLLIMPORT mach_error_t AMDPostNotification(service_conn_t socket, CFStringRef notification, CFStringRef userinfo); __DLLIMPORT mach_error_t AMDObserveNotification(service_conn_t socket, CFStringRef notification); __DLLIMPORT mach_error_t AMDListenForNotifications(service_conn_t socket, notify_callback cb, void* data); __DLLIMPORT mach_error_t AMDShutdownNotificationProxy(service_conn_t socket); /*edits by geohot*/ __DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device); __DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict); __DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring); /* additional functions by imkira * it looks like unknown0 is actually a AMServiceConnection, but it can be NULL */ int AMDeviceSecureTransferPath(int unknown0, struct am_device *device, CFURLRef url, CFDictionaryRef options, void *callback, int callback_arg); int AMDeviceSecureInstallApplication(int unknown0, struct am_device *device, CFURLRef url, CFDictionaryRef options, void *callback, int callback_arg); int AMDeviceSecureUninstallApplication(int unknown0, struct am_device *device, CFStringRef bundle_id, int unknown1, void *callback, int callback_arg); int AMDeviceLookupApplications(struct am_device *device, int unknown0, CFDictionaryRef* apps); /* obtained from http://theiphonewiki.com/wiki/index.php?title=USBMuxConnectByPort */ int USBMuxConnectByPort(int connectionID, int iPhone_port_network_byte_order, int* outHandle); /* ---------------------------------------------------------------------------- * Semi-private routines * ------------------------------------------------------------------------- */ /* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure * pointer, which will be filled with the resulting usbmux_listener_2. * * Returns: * MDERR_OK if completed successfully * MDERR_USBMUX_ARG_NULL if one of the arguments was NULL * MDERR_USBMUX_FAILED if the listener was not created successfully */ __DLLIMPORT usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct usbmux_listener_2 **eax_fp12); /* ---------------------------------------------------------------------------- * Less-documented semi-private routines * ------------------------------------------------------------------------- */ __DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *); /* ---------------------------------------------------------------------------- * Private routines - here be dragons * ------------------------------------------------------------------------- */ /* AMRestorePerformRestoreModeRestore() calls this function with a dictionary * in order to perform certain special restore operations * (RESTORED_OPERATION_*). It is thought that this function might enable * significant access to the phone. */ /* typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev, CFDictionaryRef op) __attribute__ ((regparm(2))); t_performOperation _performOperation = (t_performOperation)0x3c39fa4b; */ /* ---------------------------------------------------------------------------- * Less-documented private routines * ------------------------------------------------------------------------- */ /* typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port) __attribute__ ((regparm(2))); t_socketForPort _socketForPort = (t_socketForPort)(void *)0x3c39f36c; typedef void (*t_restored_send_message)(int port, CFDictionaryRef msg); t_restored_send_message _restored_send_message = (t_restored_send_message)0x3c3a4e40; typedef CFDictionaryRef (*t_restored_receive_message)(int port); t_restored_receive_message _restored_receive_message = (t_restored_receive_message)0x3c3a4d40; typedef unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1, unsigned char *unknown2) __attribute__ ((regparm(3))); t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;; typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev, CFStringRef cmd) __attribute__ ((regparm(2))); t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b; typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned int read_pipe, unsigned char *data, unsigned int *len); t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8; typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned int write_pipe, void *data, unsigned int len); t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb; */ int performOperation(struct am_restore_device *rdev, CFMutableDictionaryRef message); int socketForPort(struct am_restore_device *rdev, unsigned int portnum); int sendCommandToDevice(struct am_recovery_device *rdev, CFStringRef cfs, int block); int sendFileToDevice(struct am_recovery_device *rdev, CFStringRef filename); #ifdef __cplusplus } #endif #endif /* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */
42.903319
121
0.684347
bdf889f57953e9c915d609e51fc490b8a768cf3a
43,935
c
C
src/mono/mono/mini/branch-opts.c
WeihanLi/runtime
79d478ae01d9a3e7548bf41a76d047158ed8a62b
[ "MIT" ]
12
2021-11-08T21:12:31.000Z
2022-01-11T03:43:34.000Z
src/mono/mono/mini/branch-opts.c
WeihanLi/runtime
79d478ae01d9a3e7548bf41a76d047158ed8a62b
[ "MIT" ]
27
2021-11-29T21:02:00.000Z
2022-03-29T11:05:52.000Z
src/mono/mono/mini/branch-opts.c
WeihanLi/runtime
79d478ae01d9a3e7548bf41a76d047158ed8a62b
[ "MIT" ]
3
2021-11-17T05:46:01.000Z
2022-02-19T06:17:34.000Z
/** * \file * Branch optimizations support * * Authors: * Patrik Torstensson (Patrik.Torstesson at gmail.com) * * (C) 2005 Ximian, Inc. http://www.ximian.com * Copyright 2011 Xamarin Inc. http://www.xamarin.com * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #include <mono/utils/mono-compiler.h> #ifndef DISABLE_JIT #include "mini.h" #include "mini-runtime.h" /* * Returns true if @bb is a basic block which falls through the next block. * TODO verify if it helps to check if the bb last ins is a branch to its successor. */ static gboolean mono_bb_is_fall_through (MonoCompile *cfg, MonoBasicBlock *bb) { return bb->next_bb && bb->next_bb->region == bb->region && /*fall throught between regions is not really interesting or useful*/ (bb->last_ins == NULL || !MONO_IS_BRANCH_OP (bb->last_ins)); /*and the last op can't be a branch too*/ } /* * Used by the arch code to replace the exception handling * with a direct branch. This is safe to do if the * exception object isn't used, no rethrow statement and * no filter statement (verify). * */ MonoInst * mono_branch_optimize_exception_target (MonoCompile *cfg, MonoBasicBlock *bb, const char * exname) { MonoMethodHeader *header = cfg->header; MonoExceptionClause *clause; MonoClass *exclass; int i; if (!(cfg->opt & MONO_OPT_EXCEPTION)) return NULL; if (bb->region == -1 || !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY)) return NULL; exclass = mono_class_load_from_name (mono_get_corlib (), "System", exname); /* search for the handler */ for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset)) { if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE && clause->data.catch_class && mono_class_is_assignable_from_internal (clause->data.catch_class, exclass)) { MonoBasicBlock *tbb; /* get the basic block for the handler and * check if the exception object is used. * Flag is set during method_to_ir due to * pop-op is optmized away in codegen (burg). */ tbb = cfg->cil_offset_to_bb [clause->handler_offset]; if (tbb && tbb->flags & BB_EXCEPTION_DEAD_OBJ && !(tbb->flags & BB_EXCEPTION_UNSAFE)) { MonoBasicBlock *targetbb = tbb; gboolean unsafe = FALSE; /* Check if this catch clause is ok to optimize by * looking for the BB_EXCEPTION_UNSAFE in every BB that * belongs to the same region. * * UNSAFE flag is set during method_to_ir (OP_RETHROW) */ while (!unsafe && tbb->next_bb && tbb->region == tbb->next_bb->region) { if (tbb->next_bb->flags & BB_EXCEPTION_UNSAFE) { unsafe = TRUE; break; } tbb = tbb->next_bb; } if (!unsafe) { MonoInst *jump; /* Create dummy inst to allow easier integration in * arch dependent code (opcode ignored) */ MONO_INST_NEW (cfg, jump, OP_BR); /* Allocate memory for our branch target */ jump->inst_i1 = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst)); jump->inst_true_bb = targetbb; if (cfg->verbose_level > 2) g_print ("found exception to optimize - returning branch to BB%d (%s) (instead of throw) for method %s:%s\n", targetbb->block_num, m_class_get_name (clause->data.catch_class), m_class_get_name (cfg->method->klass), cfg->method->name); return jump; } return NULL; } else { /* Branching to an outer clause could skip inner clauses */ return NULL; } } else { /* Branching to an outer clause could skip inner clauses */ return NULL; } } } return NULL; } #ifdef MONO_ARCH_HAVE_CMOV_OPS static const int int_cmov_opcodes [] = { OP_CMOV_IEQ, OP_CMOV_INE_UN, OP_CMOV_ILE, OP_CMOV_IGE, OP_CMOV_ILT, OP_CMOV_IGT, OP_CMOV_ILE_UN, OP_CMOV_IGE_UN, OP_CMOV_ILT_UN, OP_CMOV_IGT_UN }; static const int long_cmov_opcodes [] = { OP_CMOV_LEQ, OP_CMOV_LNE_UN, OP_CMOV_LLE, OP_CMOV_LGE, OP_CMOV_LLT, OP_CMOV_LGT, OP_CMOV_LLE_UN, OP_CMOV_LGE_UN, OP_CMOV_LLT_UN, OP_CMOV_LGT_UN }; static int br_to_br_un (int opcode) { switch (opcode) { case OP_IBGT: return OP_IBGT_UN; break; case OP_IBLE: return OP_IBLE_UN; break; case OP_LBGT: return OP_LBGT_UN; break; case OP_LBLE: return OP_LBLE_UN; break; default: g_assert_not_reached (); return -1; } } #endif /** * mono_replace_ins: * * Replace INS with its decomposition which is stored in a series of bblocks starting * at FIRST_BB and ending at LAST_BB. On enter, PREV points to the predecessor of INS. * On return, it will be set to the last ins of the decomposition. */ void mono_replace_ins (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, MonoInst **prev, MonoBasicBlock *first_bb, MonoBasicBlock *last_bb) { MonoInst *next = ins->next; if (next && next->opcode == OP_NOP) { /* Avoid NOPs following branches */ ins->next = next->next; next = next->next; } if (first_bb == last_bb) { /* * Only one replacement bb, merge the code into * the current bb. */ /* Delete links between the first_bb and its successors */ while (first_bb->out_count) mono_unlink_bblock (cfg, first_bb, first_bb->out_bb [0]); /* Head */ if (*prev) { (*prev)->next = first_bb->code; first_bb->code->prev = (*prev); } else { bb->code = first_bb->code; } /* Tail */ last_bb->last_ins->next = next; if (next) next->prev = last_bb->last_ins; else bb->last_ins = last_bb->last_ins; *prev = last_bb->last_ins; bb->needs_decompose |= first_bb->needs_decompose; } else { int i, count; MonoBasicBlock **tmp_bblocks, *tmp; MonoInst *last; /* Multiple BBs */ /* Set region/real_offset */ for (tmp = first_bb; tmp; tmp = tmp->next_bb) { tmp->region = bb->region; tmp->real_offset = bb->real_offset; } /* Split the original bb */ if (ins->next) ins->next->prev = NULL; ins->next = NULL; bb->last_ins = ins; /* Merge the second part of the original bb into the last bb */ if (last_bb->last_ins) { last_bb->last_ins->next = next; if (next) next->prev = last_bb->last_ins; } else { last_bb->code = next; } last_bb->needs_decompose |= bb->needs_decompose; if (next) { for (last = next; last->next != NULL; last = last->next) ; last_bb->last_ins = last; } for (i = 0; i < bb->out_count; ++i) mono_link_bblock (cfg, last_bb, bb->out_bb [i]); /* Merge the first (dummy) bb to the original bb */ if (*prev) { (*prev)->next = first_bb->code; first_bb->code->prev = (*prev); } else { bb->code = first_bb->code; } bb->last_ins = first_bb->last_ins; bb->needs_decompose |= first_bb->needs_decompose; /* Delete the links between the original bb and its successors */ tmp_bblocks = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * bb->out_count); memcpy (tmp_bblocks, bb->out_bb, sizeof (MonoBasicBlock*) * bb->out_count); count = bb->out_count; for (i = 0; i < count; ++i) mono_unlink_bblock (cfg, bb, tmp_bblocks [i]); /* Add links between the original bb and the first_bb's successors */ for (i = 0; i < first_bb->out_count; ++i) { MonoBasicBlock *out_bb = first_bb->out_bb [i]; mono_link_bblock (cfg, bb, out_bb); } /* Delete links between the first_bb and its successors */ for (i = 0; i < bb->out_count; ++i) { MonoBasicBlock *out_bb = bb->out_bb [i]; mono_unlink_bblock (cfg, first_bb, out_bb); } last_bb->next_bb = bb->next_bb; bb->next_bb = first_bb->next_bb; *prev = NULL; } } void mono_if_conversion (MonoCompile *cfg) { #ifdef MONO_ARCH_HAVE_CMOV_OPS MonoBasicBlock *bb; gboolean changed = FALSE; int filter = FILTER_NOP | FILTER_IL_SEQ_POINT; if (!(cfg->opt & MONO_OPT_CMOV)) return; // FIXME: Make this work with extended bblocks /* * This pass requires somewhat optimized IR code so it should be run after * local cprop/deadce. Also, it should be run before dominator computation, since * it changes control flow. */ for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { MonoBasicBlock *bb1, *bb2; restart: if (!(bb->out_count == 2 && !bb->extended)) continue; bb1 = bb->out_bb [0]; bb2 = bb->out_bb [1]; /* If either bb1 or bb2 is a try block, abort the optimization attempt. */ if (bb1->try_start || bb2->try_start) continue; /* Look for the IR code generated from cond ? a : b * which is: * BB: * b<cond> [BB1BB2] * BB1: * <var> <- <a> * br BB3 * BB2: * <var> <- <b> * br BB3 */ if (bb1->in_count == 1 && bb2->in_count == 1 && bb1->out_count == 1 && bb2->out_count == 1 && bb1->out_bb [0] == bb2->out_bb [0]) { MonoInst *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp; MonoBasicBlock *true_bb, *false_bb; gboolean simple, ret; int dreg, tmp_reg; CompType comp_type; branch = mono_bb_last_inst (bb, filter); if (!branch || branch->opcode == OP_BR_REG || branch->opcode == OP_BR) continue; /* Find the compare instruction */ compare = mono_inst_prev (branch, filter); if (!compare) continue; if (!MONO_IS_COND_BRANCH_OP (branch)) /* This can happen if a cond branch is optimized away */ continue; true_bb = branch->inst_true_bb; false_bb = branch->inst_false_bb; /* * Check that bb1 and bb2 are 'simple' and both assign to the same * variable. */ /* FIXME: Get rid of the nops earlier */ ins1 = mono_bb_first_inst (true_bb, filter); ins2 = mono_bb_first_inst (false_bb, filter); if (!(ins1 && ins2 && ins1->dreg == ins2->dreg && ins1->dreg != -1)) continue; simple = TRUE; for (tmp = ins1->next; tmp; tmp = tmp->next) if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR))) simple = FALSE; for (tmp = ins2->next; tmp; tmp = tmp->next) if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR))) simple = FALSE; if (!simple) continue; /* We move ins1/ins2 before the compare so they should have no side effect */ if (!(MONO_INS_HAS_NO_SIDE_EFFECT (ins1) && MONO_INS_HAS_NO_SIDE_EFFECT (ins2))) continue; /* Moving ins1/ins2 could change the comparison */ /* FIXME: */ if (!((compare->sreg1 != ins1->dreg) && (compare->sreg2 != ins1->dreg))) continue; /* FIXME: */ comp_type = mono_opcode_to_type (branch->opcode, compare->opcode); if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L))) continue; /* FIXME: */ /* ins->type might not be set */ if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i') continue; if (cfg->verbose_level > 2) { printf ("\tBranch -> CMove optimization in BB%d on\n", bb->block_num); printf ("\t\t"); mono_print_ins (compare); printf ("\t\t"); mono_print_ins (mono_inst_next (compare, filter)); printf ("\t\t"); mono_print_ins (ins1); printf ("\t\t"); mono_print_ins (ins2); } changed = TRUE; //printf ("HIT!\n"); /* Assignments to the return register must remain at the end of bbs */ if (cfg->ret) ret = ins1->dreg == cfg->ret->dreg; else ret = FALSE; tmp_reg = mono_alloc_dreg (cfg, STACK_I4); dreg = ins1->dreg; /* Rewrite ins1 to emit to tmp_reg */ ins1->dreg = tmp_reg; if (ret) { dreg = mono_alloc_dreg (cfg, STACK_I4); ins2->dreg = dreg; } /* Remove ins1/ins2 from bb1/bb2 */ MONO_REMOVE_INS (true_bb, ins1); MONO_REMOVE_INS (false_bb, ins2); /* Move ins1 and ins2 before the comparison */ /* ins1 comes first to avoid ins1 overwriting an argument of ins2 */ mono_bblock_insert_before_ins (bb, compare, ins2); mono_bblock_insert_before_ins (bb, ins2, ins1); /* Add cmov instruction */ MONO_INST_NEW (cfg, cmov, OP_NOP); cmov->dreg = dreg; cmov->sreg1 = dreg; cmov->sreg2 = tmp_reg; switch (mono_opcode_to_type (branch->opcode, compare->opcode)) { case CMP_TYPE_I: cmov->opcode = int_cmov_opcodes [mono_opcode_to_cond (branch->opcode)]; break; case CMP_TYPE_L: cmov->opcode = long_cmov_opcodes [mono_opcode_to_cond (branch->opcode)]; break; default: g_assert_not_reached (); } mono_bblock_insert_after_ins (bb, compare, cmov); if (ret) { /* Add an extra move */ MONO_INST_NEW (cfg, move, OP_MOVE); move->dreg = cfg->ret->dreg; move->sreg1 = dreg; mono_bblock_insert_after_ins (bb, cmov, move); } /* Rewrite the branch */ branch->opcode = OP_BR; branch->inst_target_bb = true_bb->out_bb [0]; mono_link_bblock (cfg, bb, branch->inst_target_bb); /* Reorder bblocks */ mono_unlink_bblock (cfg, bb, true_bb); mono_unlink_bblock (cfg, bb, false_bb); mono_unlink_bblock (cfg, true_bb, true_bb->out_bb [0]); mono_unlink_bblock (cfg, false_bb, false_bb->out_bb [0]); mono_remove_bblock (cfg, true_bb); mono_remove_bblock (cfg, false_bb); /* Merge bb and its successor if possible */ if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) && (bb->region == bb->out_bb [0]->region)) { mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]); goto restart; } } /* Look for the IR code generated from if (cond) <var> <- <a> * which is: * BB: * b<cond> [BB1BB2] * BB1: * <var> <- <a> * br BB2 */ if ((bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) || (bb1->in_count == 1 && bb1->out_count == 1 && bb1->out_bb [0] == bb2)) { MonoInst *compare, *branch, *ins1, *cmov, *tmp; gboolean simple; int dreg, tmp_reg; CompType comp_type; CompRelation cond; MonoBasicBlock *next_bb, *code_bb; /* code_bb is the bblock containing code, next_bb is the successor bblock */ if (bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) { code_bb = bb2; next_bb = bb1; } else { code_bb = bb1; next_bb = bb2; } ins1 = mono_bb_first_inst (code_bb, filter); if (!ins1) continue; /* Check that code_bb is simple */ simple = TRUE; for (tmp = ins1; tmp; tmp = tmp->next) if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR))) simple = FALSE; if (!simple) continue; /* We move ins1 before the compare so it should have no side effect */ if (!MONO_INS_HAS_NO_SIDE_EFFECT (ins1)) continue; branch = mono_bb_last_inst (bb, filter); if (!branch || branch->opcode == OP_BR_REG) continue; /* Find the compare instruction */ compare = mono_inst_prev (branch, filter); if (!compare) continue; if (!MONO_IS_COND_BRANCH_OP (branch)) /* This can happen if a cond branch is optimized away */ continue; /* FIXME: */ comp_type = mono_opcode_to_type (branch->opcode, compare->opcode); if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L))) continue; /* FIXME: */ /* ins->type might not be set */ if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i') continue; /* FIXME: */ if (cfg->ret && ins1->dreg == cfg->ret->dreg) continue; if (!(cfg->opt & MONO_OPT_DEADCE)) /* * It is possible that dreg is never set before, so we can't use * it as an sreg of the cmov instruction (#582322). */ continue; if (cfg->verbose_level > 2) { printf ("\tBranch -> CMove optimization (2) in BB%d on\n", bb->block_num); printf ("\t\t"); mono_print_ins (compare); printf ("\t\t"); mono_print_ins (mono_inst_next (compare, filter)); printf ("\t\t"); mono_print_ins (ins1); } changed = TRUE; //printf ("HIT!\n"); tmp_reg = mono_alloc_dreg (cfg, STACK_I4); dreg = ins1->dreg; /* Rewrite ins1 to emit to tmp_reg */ ins1->dreg = tmp_reg; /* Remove ins1 from code_bb */ MONO_REMOVE_INS (code_bb, ins1); /* Move ins1 before the comparison */ mono_bblock_insert_before_ins (bb, compare, ins1); /* Add cmov instruction */ MONO_INST_NEW (cfg, cmov, OP_NOP); cmov->dreg = dreg; cmov->sreg1 = dreg; cmov->sreg2 = tmp_reg; cond = mono_opcode_to_cond (branch->opcode); if (branch->inst_false_bb == code_bb) cond = mono_negate_cond (cond); switch (mono_opcode_to_type (branch->opcode, compare->opcode)) { case CMP_TYPE_I: cmov->opcode = int_cmov_opcodes [cond]; break; case CMP_TYPE_L: cmov->opcode = long_cmov_opcodes [cond]; break; default: g_assert_not_reached (); } mono_bblock_insert_after_ins (bb, compare, cmov); /* Rewrite the branch */ branch->opcode = OP_BR; branch->inst_target_bb = next_bb; mono_link_bblock (cfg, bb, branch->inst_target_bb); /* Nullify the branch at the end of code_bb */ if (code_bb->code) { branch = code_bb->code; MONO_DELETE_INS (code_bb, branch); } /* Reorder bblocks */ mono_unlink_bblock (cfg, bb, code_bb); mono_unlink_bblock (cfg, code_bb, next_bb); /* Merge bb and its successor if possible */ if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) && (bb->region == bb->out_bb [0]->region)) { mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]); /* * bbn might have fallen through to the next bb without a branch, * have to add one now (#474718). * FIXME: Maybe need to do this more generally in * merge_basic_blocks () ? */ if (!(bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) && bb->out_count) { MONO_INST_NEW (cfg, ins1, OP_BR); ins1->inst_target_bb = bb->out_bb [0]; MONO_ADD_INS (bb, ins1); } goto restart; } } } /* * Optimize checks like: if (v < 0 || v > limit) by changing then to unsigned * compares. This isn't really if conversion, but it easier to do here than in * optimize_branches () since the IR is already optimized. */ for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { MonoBasicBlock *bb1, *bb2, *next_bb; MonoInst *branch1, *branch2, *compare1, *ins, *next; /* Look for the IR code generated from if (<var> < 0 || v > <limit>) * after branch opts which is: * BB: * icompare_imm R [0] * int_blt [BB1BB2] * BB2: * icompare_imm R [<limit>] * int_ble [BB3BB1] */ if (!(bb->out_count == 2 && !bb->extended)) continue; bb1 = bb->out_bb [0]; bb2 = bb->out_bb [1]; // FIXME: Add more cases /* Check structure */ if (!(bb1->in_count == 2 && bb1->in_bb [0] == bb && bb1->in_bb [1] == bb2 && bb2->in_count == 1 && bb2->out_count == 2)) continue; next_bb = bb2; /* Check first branch */ branch1 = mono_bb_last_inst (bb, filter); if (!(branch1 && ((branch1->opcode == OP_IBLT) || (branch1->opcode == OP_LBLT)) && (branch1->inst_false_bb == next_bb))) continue; /* Check second branch */ branch2 = mono_bb_last_inst (next_bb, filter); if (!branch2) continue; /* mcs sometimes generates inverted branches */ if (((branch2->opcode == OP_IBGT) || (branch2->opcode == OP_LBGT)) && branch2->inst_true_bb == branch1->inst_true_bb) ; else if (((branch2->opcode == OP_IBLE) || (branch2->opcode == OP_LBLE)) && branch2->inst_false_bb == branch1->inst_true_bb) ; else continue; /* Check first compare */ compare1 = mono_inst_prev (mono_bb_last_inst (bb, filter), filter); if (!(compare1 && ((compare1->opcode == OP_ICOMPARE_IMM) || (compare1->opcode == OP_LCOMPARE_IMM)) && compare1->inst_imm == 0)) continue; /* Check second bblock */ ins = mono_bb_first_inst (next_bb, filter); if (!ins) continue; next = mono_inst_next (ins, filter); if (((ins->opcode == OP_ICOMPARE_IMM) || (ins->opcode == OP_LCOMPARE_IMM)) && ins->sreg1 == compare1->sreg1 && next == branch2) { /* The second arg must be positive */ if (ins->inst_imm < 0) continue; } else if (((ins->opcode == OP_LDLEN) || (ins->opcode == OP_STRLEN)) && ins->dreg != compare1->sreg1 && next && next->opcode == OP_ICOMPARE && next->sreg1 == compare1->sreg1 && next->sreg2 == ins->dreg && mono_inst_next (next, filter) == branch2) { /* Another common case: if (index < 0 || index > arr.Length) */ } else { continue; } if (cfg->verbose_level > 2) { printf ("\tSigned->unsigned compare optimization in BB%d on\n", bb->block_num); printf ("\t\t"); mono_print_ins (compare1); printf ("\t\t"); mono_print_ins (mono_inst_next (compare1, filter)); printf ("\t\t"); mono_print_ins (ins); } /* Rewrite the first compare+branch */ MONO_DELETE_INS (bb, compare1); branch1->opcode = OP_BR; mono_unlink_bblock (cfg, bb, branch1->inst_true_bb); mono_unlink_bblock (cfg, bb, branch1->inst_false_bb); branch1->inst_target_bb = next_bb; mono_link_bblock (cfg, bb, next_bb); /* Rewrite the second branch */ branch2->opcode = br_to_br_un (branch2->opcode); mono_merge_basic_blocks (cfg, bb, next_bb); } #if 0 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { MonoBasicBlock *bb1, *bb2; MonoInst *prev, *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp; gboolean simple, ret; int dreg, tmp_reg; CompType comp_type; /* Look for the IR code generated from if (cond) <var> <- <a> * after branch opts which is: * BB: * compare * b<cond> [BB1] * <var> <- <a> * BB1: */ if (!(bb->out_count == 1 && bb->extended && bb->code && bb->code->next && bb->code->next->next)) continue; mono_print_bb (bb, ""); /* Find the compare instruction */ prev = NULL; compare = bb->code; g_assert (compare); while (compare->next->next && compare->next->next != bb->last_ins) { prev = compare; compare = compare->next; } branch = compare->next; if (!MONO_IS_COND_BRANCH_OP (branch)) continue; } #endif if (changed) { if (cfg->opt & MONO_OPT_BRANCH) mono_optimize_branches (cfg); /* Merging bblocks could make some variables local */ mono_handle_global_vregs (cfg); if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP)) mono_local_cprop (cfg); if (cfg->opt & MONO_OPT_DEADCE) mono_local_deadce (cfg); } #endif } void mono_nullify_basic_block (MonoBasicBlock *bb) { bb->in_count = 0; bb->out_count = 0; bb->in_bb = NULL; bb->out_bb = NULL; bb->next_bb = NULL; bb->code = bb->last_ins = NULL; bb->cil_code = NULL; } static void replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) { int i; for (i = 0; i < bb->out_count; i++) { MonoBasicBlock *ob = bb->out_bb [i]; if (ob == orig) { if (!repl) { if (bb->out_count > 1) { bb->out_bb [i] = bb->out_bb [bb->out_count - 1]; } bb->out_count--; } else { bb->out_bb [i] = repl; } } } } static void replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) { int i; for (i = 0; i < bb->in_count; i++) { MonoBasicBlock *ib = bb->in_bb [i]; if (ib == orig) { if (!repl) { if (bb->in_count > 1) { bb->in_bb [i] = bb->in_bb [bb->in_count - 1]; } bb->in_count--; } else { bb->in_bb [i] = repl; } } } } static void replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) { MonoInst *ins; for (ins = bb->code; ins != NULL; ins = ins->next) { switch (ins->opcode) { case OP_BR: if (ins->inst_target_bb == orig) ins->inst_target_bb = repl; break; case OP_CALL_HANDLER: if (ins->inst_target_bb == orig) ins->inst_target_bb = repl; break; case OP_SWITCH: { int i; int n = GPOINTER_TO_INT (ins->klass); for (i = 0; i < n; i++ ) { if (ins->inst_many_bb [i] == orig) ins->inst_many_bb [i] = repl; } break; } default: if (MONO_IS_COND_BRANCH_OP (ins)) { if (ins->inst_true_bb == orig) ins->inst_true_bb = repl; if (ins->inst_false_bb == orig) ins->inst_false_bb = repl; } else if (MONO_IS_JUMP_TABLE (ins)) { int i; MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (ins); for (i = 0; i < table->table_size; i++ ) { if (table->table [i] == orig) table->table [i] = repl; } } break; } } } /** * Check if a bb is useless (is just made of NOPs and ends with an * unconditional branch, or nothing). * If it is so, unlink it from the CFG and nullify it, and return TRUE. * Otherwise, return FALSE; */ static gboolean remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) { MonoBasicBlock *target_bb = NULL; MonoInst *inst; /* Do not touch handlers */ if (bb->region != -1) { bb->not_useless = TRUE; return FALSE; } MONO_BB_FOR_EACH_INS (bb, inst) { switch (inst->opcode) { case OP_NOP: case OP_IL_SEQ_POINT: break; case OP_BR: target_bb = inst->inst_target_bb; break; default: bb->not_useless = TRUE; return FALSE; } } if (target_bb == NULL) { if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) { target_bb = bb->next_bb; } else { /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */ return FALSE; } } /* Do not touch BBs following a switch (they are the "default" branch) */ if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == OP_SWITCH)) { return FALSE; } /* Do not touch BBs following the entry BB and jumping to something that is not */ /* thiry "next" bb (the entry BB cannot contain the branch) */ if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) { return FALSE; } /* * Do not touch BBs following a try block as the code in * mini_method_compile needs them to compute the length of the try block. */ if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY)) return FALSE; /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */ if ((target_bb != NULL) && (target_bb != bb)) { int i; if (cfg->verbose_level > 1) { printf ("remove_block_if_useless, removed BB%d\n", bb->block_num); } /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */ while (bb->in_count) { MonoBasicBlock *in_bb = bb->in_bb [0]; mono_unlink_bblock (cfg, in_bb, bb); mono_link_bblock (cfg, in_bb, target_bb); replace_out_block_in_code (in_bb, bb, target_bb); } mono_unlink_bblock (cfg, bb, target_bb); if (previous_bb != cfg->bb_entry && mono_bb_is_fall_through (cfg, previous_bb)) { for (i = 0; i < previous_bb->out_count; i++) { if (previous_bb->out_bb [i] == target_bb) { MonoInst *jump; MONO_INST_NEW (cfg, jump, OP_BR); MONO_ADD_INS (previous_bb, jump); jump->cil_code = previous_bb->cil_code; jump->inst_target_bb = target_bb; break; } } } previous_bb->next_bb = bb->next_bb; mono_nullify_basic_block (bb); return TRUE; } else { return FALSE; } } void mono_merge_basic_blocks (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *bbn) { MonoInst *inst; MonoBasicBlock *prev_bb; int i; /* There may be only one control flow edge between two BBs that we merge, and it should connect these BBs together. */ g_assert (bb->out_count == 1 && bbn->in_count == 1 && bb->out_bb [0] == bbn && bbn->in_bb [0] == bb); bb->needs_decompose |= bbn->needs_decompose; bb->extended |= bbn->extended; mono_unlink_bblock (cfg, bb, bbn); for (i = 0; i < bbn->out_count; ++i) mono_link_bblock (cfg, bb, bbn->out_bb [i]); while (bbn->out_count) mono_unlink_bblock (cfg, bbn, bbn->out_bb [0]); /* Handle the branch at the end of the bb */ if (bb->has_call_handler) { for (inst = bb->code; inst != NULL; inst = inst->next) { if (inst->opcode == OP_CALL_HANDLER) { g_assert (inst->inst_target_bb == bbn); NULLIFY_INS (inst); } } } if (bb->has_jump_table) { for (inst = bb->code; inst != NULL; inst = inst->next) { if (MONO_IS_JUMP_TABLE (inst)) { int i; MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (inst); for (i = 0; i < table->table_size; i++ ) { /* Might be already NULL from a previous merge */ if (table->table [i]) g_assert (table->table [i] == bbn); table->table [i] = NULL; } /* Can't nullify this as later instructions depend on it */ } } } if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) { g_assert (bb->last_ins->inst_false_bb == bbn); bb->last_ins->inst_false_bb = NULL; bb->extended = TRUE; } else if (bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) { NULLIFY_INS (bb->last_ins); } bb->has_call_handler |= bbn->has_call_handler; bb->has_jump_table |= bbn->has_jump_table; if (bb->last_ins) { if (bbn->code) { bb->last_ins->next = bbn->code; bbn->code->prev = bb->last_ins; bb->last_ins = bbn->last_ins; } } else { bb->code = bbn->code; bb->last_ins = bbn->last_ins; } /* Check if the control flow predecessor is also the linear IL predecessor. */ if (bbn->in_bb [0]->next_bb == bbn) prev_bb = bbn->in_bb [0]; else /* If it isn't, look for one among all basic blocks. */ for (prev_bb = cfg->bb_entry; prev_bb && prev_bb->next_bb != bbn; prev_bb = prev_bb->next_bb) ; if (prev_bb) { prev_bb->next_bb = bbn->next_bb; } else { /* bbn might not be in the bb list yet */ if (bb->next_bb == bbn) bb->next_bb = bbn->next_bb; } mono_nullify_basic_block (bbn); /* * If bbn fell through to its next bblock, have to add a branch, since bb * will not fall though to the same bblock (#513931). */ if (bb->last_ins && bb->out_count == 1 && bb->out_bb [0] != bb->next_bb && !MONO_IS_BRANCH_OP (bb->last_ins)) { MONO_INST_NEW (cfg, inst, OP_BR); inst->inst_target_bb = bb->out_bb [0]; MONO_ADD_INS (bb, inst); } } static void move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb) { MonoBasicBlock *bbn, *next; next = bb->next_bb; /* Find the previous */ for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb) ; if (bbn->next_bb) { bbn->next_bb = bb->next_bb; } /* Find the last */ for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb) ; bbn->next_bb = bb; bb->next_bb = NULL; /* Add a branch */ if (next && (!bb->last_ins || ((bb->last_ins->opcode != OP_NOT_REACHED) && (bb->last_ins->opcode != OP_BR) && (bb->last_ins->opcode != OP_BR_REG) && (!MONO_IS_COND_BRANCH_OP (bb->last_ins))))) { MonoInst *ins; MONO_INST_NEW (cfg, ins, OP_BR); MONO_ADD_INS (bb, ins); mono_link_bblock (cfg, bb, next); ins->inst_target_bb = next; } } /* * mono_remove_block: * * Remove BB from the control flow graph */ void mono_remove_bblock (MonoCompile *cfg, MonoBasicBlock *bb) { MonoBasicBlock *tmp_bb; for (tmp_bb = cfg->bb_entry; tmp_bb && tmp_bb->next_bb != bb; tmp_bb = tmp_bb->next_bb) ; g_assert (tmp_bb); tmp_bb->next_bb = bb->next_bb; } void mono_remove_critical_edges (MonoCompile *cfg) { MonoBasicBlock *bb; MonoBasicBlock *previous_bb; if (cfg->verbose_level > 3) { for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { int i; printf ("remove_critical_edges, BEFORE BB%d (in:", bb->block_num); for (i = 0; i < bb->in_count; i++) { printf (" %d", bb->in_bb [i]->block_num); } printf (") (out:"); for (i = 0; i < bb->out_count; i++) { printf (" %d", bb->out_bb [i]->block_num); } printf (")"); if (bb->last_ins != NULL) { printf (" "); mono_print_ins (bb->last_ins); } printf ("\n"); } } for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) { if (bb->in_count > 1) { int in_bb_index; for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) { MonoBasicBlock *in_bb = bb->in_bb [in_bb_index]; /* * Have to remove non-critical edges whose source ends with a BR_REG * ins too, since inserting a computation before the BR_REG could * overwrite the sreg1 of the ins. */ if ((in_bb->out_count > 1) || (in_bb->out_count == 1 && in_bb->last_ins && in_bb->last_ins->opcode == OP_BR_REG)) { MonoBasicBlock *new_bb = (MonoBasicBlock *)mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); new_bb->block_num = cfg->num_bblocks++; // new_bb->real_offset = bb->real_offset; new_bb->region = bb->region; /* Do not alter the CFG while altering the BB list */ if (mono_bb_is_fall_through (cfg, previous_bb)) { if (previous_bb != cfg->bb_entry) { int i; /* Make sure previous_bb really falls through bb */ for (i = 0; i < previous_bb->out_count; i++) { if (previous_bb->out_bb [i] == bb) { MonoInst *jump; MONO_INST_NEW (cfg, jump, OP_BR); MONO_ADD_INS (previous_bb, jump); jump->cil_code = previous_bb->cil_code; jump->inst_target_bb = bb; break; } } } else { /* We cannot add any inst to the entry BB, so we must */ /* put a new BB in the middle to hold the OP_BR */ MonoInst *jump; MonoBasicBlock *new_bb_after_entry = (MonoBasicBlock *)mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); new_bb_after_entry->block_num = cfg->num_bblocks++; // new_bb_after_entry->real_offset = bb->real_offset; new_bb_after_entry->region = bb->region; MONO_INST_NEW (cfg, jump, OP_BR); MONO_ADD_INS (new_bb_after_entry, jump); jump->cil_code = bb->cil_code; jump->inst_target_bb = bb; mono_unlink_bblock (cfg, previous_bb, bb); mono_link_bblock (cfg, new_bb_after_entry, bb); mono_link_bblock (cfg, previous_bb, new_bb_after_entry); previous_bb->next_bb = new_bb_after_entry; previous_bb = new_bb_after_entry; if (cfg->verbose_level > 2) { printf ("remove_critical_edges, added helper BB%d jumping to BB%d\n", new_bb_after_entry->block_num, bb->block_num); } } } /* Insert new_bb in the BB list */ previous_bb->next_bb = new_bb; new_bb->next_bb = bb; previous_bb = new_bb; /* Setup in_bb and out_bb */ new_bb->in_bb = (MonoBasicBlock **)mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*)); new_bb->in_bb [0] = in_bb; new_bb->in_count = 1; new_bb->out_bb = (MonoBasicBlock **)mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*)); new_bb->out_bb [0] = bb; new_bb->out_count = 1; /* Relink in_bb and bb to (from) new_bb */ replace_out_block (in_bb, bb, new_bb); replace_out_block_in_code (in_bb, bb, new_bb); replace_in_block (bb, in_bb, new_bb); if (cfg->verbose_level > 2) { printf ("remove_critical_edges, removed critical edge from BB%d to BB%d (added BB%d)\n", in_bb->block_num, bb->block_num, new_bb->block_num); } } } } } if (cfg->verbose_level > 3) { for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { int i; printf ("remove_critical_edges, AFTER BB%d (in:", bb->block_num); for (i = 0; i < bb->in_count; i++) { printf (" %d", bb->in_bb [i]->block_num); } printf (") (out:"); for (i = 0; i < bb->out_count; i++) { printf (" %d", bb->out_bb [i]->block_num); } printf (")"); if (bb->last_ins != NULL) { printf (" "); mono_print_ins (bb->last_ins); } printf ("\n"); } } } /* * Optimizes the branches on the Control Flow Graph * */ void mono_optimize_branches (MonoCompile *cfg) { int i, count = 0, changed = FALSE; MonoBasicBlock *bb, *bbn; guint32 niterations; MonoInst *bbn_first_inst; int filter = FILTER_IL_SEQ_POINT; /* * Possibly some loops could cause the code below to go into an infinite * loop, see bug #53003 for an example. To prevent this, we put an upper * bound on the number of iterations. */ if (cfg->num_bblocks > 1000) niterations = cfg->num_bblocks * 2; else niterations = 1000; do { MonoBasicBlock *previous_bb; changed = FALSE; niterations --; /* we skip the entry block (exit is handled specially instead ) */ for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) { count ++; if (count == 1000) { mono_threads_safepoint (); count = 0; } /* dont touch code inside exception clauses */ if (bb->region != -1) continue; if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) { changed = TRUE; continue; } if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) { if (cfg->verbose_level > 2) g_print ("nullify block triggered %d\n", bbn->block_num); bb->next_bb = bbn->next_bb; for (i = 0; i < bbn->out_count; i++) replace_in_block (bbn->out_bb [i], bbn, NULL); mono_nullify_basic_block (bbn); changed = TRUE; } if (bb->out_count == 1) { bbn = bb->out_bb [0]; /* conditional branches where true and false targets are the same can be also replaced with OP_BR */ if (bb->last_ins && (bb->last_ins->opcode != OP_BR) && MONO_IS_COND_BRANCH_OP (bb->last_ins)) { bb->last_ins->opcode = OP_BR; bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb; changed = TRUE; if (cfg->verbose_level > 2) g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count); } if (bb->region == bbn->region && bb->next_bb == bbn) { /* the block are in sequence anyway ... */ /* branches to the following block can be removed */ if (bb->last_ins && bb->last_ins->opcode == OP_BR && !bbn->out_of_line) { NULLIFY_INS (bb->last_ins); changed = TRUE; if (cfg->verbose_level > 2) g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num); } if (bbn->in_count == 1 && !bb->extended) { if (bbn != cfg->bb_exit) { if (cfg->verbose_level > 2) g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num); mono_merge_basic_blocks (cfg, bb, bbn); changed = TRUE; continue; } //mono_print_bb_code (bb); } } } if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) { if (cfg->verbose_level > 2) { g_print ("nullify block triggered %d\n", bbn->block_num); } bb->next_bb = bbn->next_bb; for (i = 0; i < bbn->out_count; i++) replace_in_block (bbn->out_bb [i], bbn, NULL); mono_nullify_basic_block (bbn); changed = TRUE; continue; } if (bb->out_count == 1) { bbn = bb->out_bb [0]; if (bb->last_ins && bb->last_ins->opcode == OP_BR) { bbn = bb->last_ins->inst_target_bb; bbn_first_inst = mono_bb_first_inst (bbn, filter); if (bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR && bbn_first_inst->inst_target_bb != bbn && bbn_first_inst->inst_target_bb->region == bb->region) { if (cfg->verbose_level > 2) g_print ("branch to branch triggered %d -> %d -> %d\n", bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num); replace_in_block (bbn, bb, NULL); replace_out_block (bb, bbn, bbn_first_inst->inst_target_bb); mono_link_bblock (cfg, bb, bbn_first_inst->inst_target_bb); bb->last_ins->inst_target_bb = bbn_first_inst->inst_target_bb; changed = TRUE; continue; } } } else if (bb->out_count == 2) { if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) { int branch_result; MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL; if (bb->last_ins->flags & MONO_INST_CFOLD_TAKEN) branch_result = BRANCH_TAKEN; else if (bb->last_ins->flags & MONO_INST_CFOLD_NOT_TAKEN) branch_result = BRANCH_NOT_TAKEN; else branch_result = BRANCH_UNDEF; if (branch_result == BRANCH_TAKEN) { taken_branch_target = bb->last_ins->inst_true_bb; untaken_branch_target = bb->last_ins->inst_false_bb; } else if (branch_result == BRANCH_NOT_TAKEN) { taken_branch_target = bb->last_ins->inst_false_bb; untaken_branch_target = bb->last_ins->inst_true_bb; } if (taken_branch_target) { /* if mono_eval_cond_branch () is ever taken to handle * non-constant values to compare, issue a pop here. */ bb->last_ins->opcode = OP_BR; bb->last_ins->inst_target_bb = taken_branch_target; if (!bb->extended) mono_unlink_bblock (cfg, bb, untaken_branch_target); changed = TRUE; continue; } bbn = bb->last_ins->inst_true_bb; bbn_first_inst = mono_bb_first_inst (bbn, filter); if (bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR && bbn_first_inst->inst_target_bb->region == bb->region) { if (cfg->verbose_level > 2) g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num, bbn_first_inst->opcode); /* * Unlink, then relink bblocks to avoid various * tricky situations when the two targets of the branch * are equal, or will become equal after the change. */ mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb); mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb); bb->last_ins->inst_true_bb = bbn_first_inst->inst_target_bb; mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb); mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb); changed = TRUE; continue; } bbn = bb->last_ins->inst_false_bb; bbn_first_inst = mono_bb_first_inst (bbn, filter); if (bbn && bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR && bbn_first_inst->inst_target_bb->region == bb->region) { if (cfg->verbose_level > 2) g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num, bbn_first_inst->opcode); mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb); mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb); bb->last_ins->inst_false_bb = bbn_first_inst->inst_target_bb; mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb); mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb); changed = TRUE; continue; } bbn = bb->last_ins->inst_false_bb; /* * If bb is an extended bb, it could contain an inside branch to bbn. * FIXME: Enable the optimization if that is not true. * If bblocks_linked () is true, then merging bb and bbn * would require addition of an extra branch at the end of bbn * slowing down loops. */ if (bbn && bb->region == bbn->region && bbn->in_count == 1 && cfg->enable_extended_bblocks && bbn != cfg->bb_exit && !bb->extended && !bbn->out_of_line && !mono_bblocks_linked (bbn, bb)) { g_assert (bbn->in_bb [0] == bb); if (cfg->verbose_level > 2) g_print ("merge false branch target triggered BB%d -> BB%d\n", bb->block_num, bbn->block_num); mono_merge_basic_blocks (cfg, bb, bbn); changed = TRUE; continue; } } if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) { if (bb->last_ins->inst_false_bb && bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region) && !cfg->disable_out_of_line_bblocks) { /* Reverse the branch */ bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode); bbn = bb->last_ins->inst_false_bb; bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb; bb->last_ins->inst_true_bb = bbn; move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb); if (cfg->verbose_level > 2) g_print ("cbranch to throw block triggered %d.\n", bb->block_num); } } } } } while (changed && (niterations > 0)); } #else /* !DISABLE_JIT */ MONO_EMPTY_SOURCE_FILE (branch_opts); #endif /* !DISABLE_JIT */
29.50638
250
0.635211
0856bcfc3e8ad9802e9a81a567b51d4e82f8f04a
220
h
C
Example/testCocoaPod/testViewController.h
alotofleo2/cocoaPodTest
11062d14d57b57bd07e664188224232d375f822d
[ "MIT" ]
null
null
null
Example/testCocoaPod/testViewController.h
alotofleo2/cocoaPodTest
11062d14d57b57bd07e664188224232d375f822d
[ "MIT" ]
null
null
null
Example/testCocoaPod/testViewController.h
alotofleo2/cocoaPodTest
11062d14d57b57bd07e664188224232d375f822d
[ "MIT" ]
null
null
null
// // testViewController.h // testCocoaPod // // Created by alotofleo2 on 12/15/2017. // Copyright (c) 2017 alotofleo2. All rights reserved. // @import UIKit; @interface testViewController : UIViewController @end
15.714286
55
0.718182
ec826ac755a196cfe338167cefe2bf38ce332452
228
h
C
src/OzEngine/Core/Base.h
OzlFX/OzEngine
992606ed4f532da54749d2415d65986860b918dd
[ "Apache-2.0" ]
null
null
null
src/OzEngine/Core/Base.h
OzlFX/OzEngine
992606ed4f532da54749d2415d65986860b918dd
[ "Apache-2.0" ]
null
null
null
src/OzEngine/Core/Base.h
OzlFX/OzEngine
992606ed4f532da54749d2415d65986860b918dd
[ "Apache-2.0" ]
null
null
null
/** Contains the base for the program, including some files used in multiple files **/ #ifndef _BASE_H_ #define _BASE_H_ #include "PlatformDetection.h" #include <OzEngine/Utilities/Log.h> #include <memory> #endif // !_BASE_H_
22.8
86
0.754386
d3d0425b4892f46f84c396b5ab5f771955381c28
756
h
C
include/lsim/base/math_types.h
ivarsrb/landscape-sim
c7f8981b9dffa00f48080650ffc101037b538735
[ "MIT" ]
null
null
null
include/lsim/base/math_types.h
ivarsrb/landscape-sim
c7f8981b9dffa00f48080650ffc101037b538735
[ "MIT" ]
null
null
null
include/lsim/base/math_types.h
ivarsrb/landscape-sim
c7f8981b9dffa00f48080650ffc101037b538735
[ "MIT" ]
2
2021-08-31T19:45:36.000Z
2021-08-31T19:45:47.000Z
// // Created by Ivars Rusbergs in 2021 // // Commonly used mathematical types #ifndef LSIM_MATH_TYPES_H_ #define LSIM_MATH_TYPES_H_ #include <glm/glm.hpp> #include "types.h" namespace lsim { // GLM linear math types aliasing using Vec2 = glm::tvec2<F32>; using Vec3 = glm::tvec3<F32>; using Vec4 = glm::tvec4<F32>; using Vec2d = glm::tvec2<F64>; using Vec3d = glm::tvec3<F64>; using Vec4d = glm::tvec4<F64>; using Vec2u16 = glm::tvec2<uint16_t>; using Vec3u32 = glm::tvec3<uint32_t>; using Vec2i16 = glm::tvec2<int16_t>; using Vec2i32 = glm::tvec2<int32_t>; using Vec3i32 = glm::tvec3<int32_t>; using Mat3 = glm::tmat3x3<F32>; using Mat4 = glm::tmat4x4<F32>; using Mat3d = glm::tmat3x3<F64>; using Mat4d = glm::tmat4x4<F64>; } // namespace sc::t #endif
25.2
37
0.714286
d3d11992649b1f8f460542be936f928427279570
592
h
C
include/concepts/driver/workload_oblivious_input.h
llpilla/MOGSLib
c74695842579df67c0776bbf31e0c86288e33130
[ "Apache-2.0" ]
null
null
null
include/concepts/driver/workload_oblivious_input.h
llpilla/MOGSLib
c74695842579df67c0776bbf31e0c86288e33130
[ "Apache-2.0" ]
null
null
null
include/concepts/driver/workload_oblivious_input.h
llpilla/MOGSLib
c74695842579df67c0776bbf31e0c86288e33130
[ "Apache-2.0" ]
null
null
null
#pragma once #include <abstractions/driver.h> #include <concepts/implementation/workload_oblivious_input.h> namespace MOGSLib { template<RuntimeSystemEnum T> inline void workload_oblivious_input_driver(Concept::WorkloadObliviousInput<T>& concept) { static_assert(T == RuntimeSystemEnum::NoRTS, "Uninmplemented Driver for the WorkloadObliviousInput concept within the designated RTS."); } template<RuntimeSystemEnum T> struct Driver<Concept::WorkloadObliviousInput<T>, T> { static constexpr Initializer<Concept::WorkloadObliviousInput<T>> init = workload_oblivious_input_driver<T>; }; }
37
229
0.817568
037afb14dd22f5d0c09dc82513d7542f1fce31e9
7,250
c
C
test/src/test_with_clause_parser.c
wengyanqing/timescaledb
3e03ca0b02c9ac1dae885919d28a4e5faa0b33c1
[ "Apache-2.0" ]
null
null
null
test/src/test_with_clause_parser.c
wengyanqing/timescaledb
3e03ca0b02c9ac1dae885919d28a4e5faa0b33c1
[ "Apache-2.0" ]
null
null
null
test/src/test_with_clause_parser.c
wengyanqing/timescaledb
3e03ca0b02c9ac1dae885919d28a4e5faa0b33c1
[ "Apache-2.0" ]
null
null
null
/* * This file and its contents are licensed under the Apache License 2.0. * Please see the included NOTICE for copyright information and * LICENSE-APACHE for a copy of the license. */ #include <postgres.h> #include <fmgr.h> #include <funcapi.h> #include <access/htup_details.h> #include <commands/defrem.h> #include <catalog/pg_type.h> #include <utils/array.h> #include <utils/builtins.h> #include <utils/lsyscache.h> #include <utils/memutils.h> #include "export.h" #include "with_clause_parser.h" #define TS_TEST_FN(name) \ TS_FUNCTION_INFO_V1(name); \ Datum name(PG_FUNCTION_ARGS) static DefElem * def_elem_from_texts(Datum *texts, int nelems) { DefElem *elem = palloc0(sizeof(*elem)); switch (nelems) { case 1: elem->defname = text_to_cstring(DatumGetTextP(texts[0])); break; case 3: elem->arg = (Node *) makeString(text_to_cstring(DatumGetTextP(texts[2]))); /* FALLTHROUGH */ case 2: elem->defname = text_to_cstring(DatumGetTextP(texts[1])); elem->defnamespace = text_to_cstring(DatumGetTextP(texts[0])); break; default: elog(ERROR, "%d elements invalid for defelem", nelems); } return elem; } static List * def_elems_from_array(ArrayType *with_clause_array) { ArrayMetaState with_clause_meta = { .element_type = TEXTOID }; ArrayIterator with_clause_iter; Datum with_clause_datum; bool with_clause_null; List *def_elems = NIL; get_typlenbyvalalign(with_clause_meta.element_type, &with_clause_meta.typlen, &with_clause_meta.typbyval, &with_clause_meta.typalign); with_clause_iter = array_create_iterator(with_clause_array, 1, &with_clause_meta); while (array_iterate(with_clause_iter, &with_clause_datum, &with_clause_null)) { Datum *with_clause_fields; int with_clause_elems; ArrayType *with_clause = DatumGetArrayTypeP(with_clause_datum); Assert(!with_clause_null); deconstruct_array(with_clause, TEXTOID, with_clause_meta.typlen, with_clause_meta.typbyval, with_clause_meta.typalign, &with_clause_fields, NULL, &with_clause_elems); def_elems = lappend(def_elems, def_elem_from_texts(with_clause_fields, with_clause_elems)); } return def_elems; } typedef struct FilteredWithClauses { List *within; List *without; } FilteredWithClauses; static HeapTuple create_filter_tuple(TupleDesc tuple_desc, DefElem *d, bool within) { Datum *values = palloc0(sizeof(*values) * tuple_desc->natts); bool *nulls = palloc0(sizeof(*nulls) * tuple_desc->natts); Assert(tuple_desc->natts >= 4); if (d->defnamespace != NULL) values[0] = CStringGetTextDatum(d->defnamespace); else nulls[0] = true; if (d->defname != NULL) values[1] = CStringGetTextDatum(d->defname); else nulls[1] = true; if (d->arg != NULL) values[2] = CStringGetTextDatum(defGetString(d)); else nulls[2] = true; values[3] = BoolGetDatum(within); return heap_form_tuple(tuple_desc, values, nulls); } TS_TEST_FN(ts_test_with_clause_filter) { FuncCallContext *funcctx; FilteredWithClauses *filtered; MemoryContext oldcontext; if (SRF_IS_FIRSTCALL()) { ArrayType *with_clause_array; TupleDesc tupdesc; List *def_elems; funcctx = SRF_FIRSTCALL_INIT(); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); with_clause_array = DatumGetArrayTypeP(PG_GETARG_DATUM(0)); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context " "that cannot accept type record"))); funcctx->tuple_desc = BlessTupleDesc(tupdesc); def_elems = def_elems_from_array(with_clause_array); filtered = palloc(sizeof(*filtered)); filtered->within = NIL; filtered->without = NIL; ts_with_clause_filter(def_elems, &filtered->within, &filtered->without); funcctx->user_fctx = filtered; MemoryContextSwitchTo(oldcontext); } funcctx = SRF_PERCALL_SETUP(); filtered = funcctx->user_fctx; if (filtered->within != NIL) { HeapTuple tuple; DefElem *d = linitial(filtered->within); tuple = create_filter_tuple(funcctx->tuple_desc, d, true); filtered->within = list_delete_first(filtered->within); SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple)); } else if (filtered->without != NIL) { HeapTuple tuple; DefElem *d = linitial(filtered->without); tuple = create_filter_tuple(funcctx->tuple_desc, d, false); filtered->without = list_delete_first(filtered->without); SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple)); } else SRF_RETURN_DONE(funcctx); } typedef enum TestArgs { TestArgUnimpl = 0, TestArgBool, TestArgInt32, TestArgDefault, TestArgName, TestArgRegclass, } TestArgs; static WithClauseDefinition test_args[] = { [TestArgUnimpl] = { .arg_name = "unimplemented", .type_id = InvalidOid, }, [TestArgBool] = { .arg_name = "bool", .type_id = BOOLOID, }, [TestArgInt32] = { .arg_name = "int32", .type_id = INT4OID, }, [TestArgDefault] = { .arg_name = "default", .type_id = INT4OID, .default_val = Int32GetDatum(-100) }, [TestArgName] = { .arg_name = "name", .type_id = NAMEOID, }, [TestArgRegclass] = { .arg_name = "regclass", .type_id = REGCLASSOID }, }; typedef struct WithClauseValue { WithClauseResult *parsed; int i; } WithClauseValue; TS_TEST_FN(ts_test_with_clause_parse) { FuncCallContext *funcctx; MemoryContext oldcontext; Datum *values; bool *nulls; HeapTuple tuple; WithClauseValue *result; if (SRF_IS_FIRSTCALL()) { ArrayType *with_clause_array; List *def_elems; TupleDesc tupdesc; WithClauseResult *parsed; funcctx = SRF_FIRSTCALL_INIT(); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context " "that cannot accept type record"))); funcctx->tuple_desc = BlessTupleDesc(tupdesc); with_clause_array = DatumGetArrayTypeP(PG_GETARG_DATUM(0)); def_elems = def_elems_from_array(with_clause_array); parsed = ts_with_clauses_parse(def_elems, test_args, TS_ARRAY_LEN(test_args)); result = palloc(sizeof(*result)); result->parsed = parsed; result->i = 0; funcctx->user_fctx = result; MemoryContextSwitchTo(oldcontext); } funcctx = SRF_PERCALL_SETUP(); result = funcctx->user_fctx; if (result == NULL || result->i >= TS_ARRAY_LEN(test_args)) SRF_RETURN_DONE(funcctx); values = palloc0(sizeof(*values) * funcctx->tuple_desc->natts); nulls = palloc(sizeof(*nulls) * funcctx->tuple_desc->natts); memset(nulls, true, sizeof(*nulls) * funcctx->tuple_desc->natts); values[0] = CStringGetTextDatum(test_args[result->i].arg_name); nulls[0] = false; if (!result->parsed[result->i].is_default || result->i == TestArgDefault) { values[result->i + 1] = result->parsed[result->i].parsed; nulls[result->i + 1] = false; } tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls); result->i += 1; SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple)); }
27.255639
100
0.714207
83df156d8c3a779f71a18ff8bb9a6505ea693fa8
21,834
c
C
src/ppelib-resource-table.c
hpvb/pelib
2389b22274f0a6c8949336f0e45cda46dc3be9df
[ "Apache-2.0" ]
7
2021-02-27T17:54:24.000Z
2021-11-14T20:31:30.000Z
src/ppelib-resource-table.c
hpvb/pelib
2389b22274f0a6c8949336f0e45cda46dc3be9df
[ "Apache-2.0" ]
11
2021-03-02T00:56:38.000Z
2022-03-02T03:10:29.000Z
src/ppelib-resource-table.c
hpvb/pelib
2389b22274f0a6c8949336f0e45cda46dc3be9df
[ "Apache-2.0" ]
1
2021-03-01T23:33:56.000Z
2021-03-01T23:33:56.000Z
/* Copyright 2021 Hein-Pieter van Braam-Stewart * * This file is part of ppelib (Portable Portable Executable LIBrary) * * 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 <inttypes.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include "ppelib-internal.h" thread_local size_t t_max_size; thread_local uint32_t t_rscs_base; thread_local uint8_t t_parse_error_handled; typedef struct string_table_string { uint32_t offset; uint16_t bytes; const wchar_t *string; } string_table_string_t; typedef struct string_table { size_t size; size_t bytes; uint32_t base_offset; string_table_string_t *strings; } string_table_t; void free_resource_directory_table(ppelib_resource_table_t *table); void string_table_serialize(string_table_t *table, uint8_t *buffer) { for (size_t i = 0; i < table->size; ++i) { size_t offset = table->base_offset + table->strings[i].offset; const wchar_t *string = table->strings[i].string; size_t size = wcslen(string); if (size > UINT16_MAX) { ppelib_set_error("String too long"); return; } write_uint16_t(buffer + offset, (uint16_t)size); if (sizeof(wchar_t) == 2) { memcpy(buffer + offset + 2, string, size * 2); } else { for (uint16_t i = 0; i < size; ++i) { memcpy(buffer + offset + 2 + (i * 2), string + i, 2); } } } } string_table_string_t *string_table_find(string_table_t *table, wchar_t *string) { for (size_t i = 0; i < table->size; ++i) { if (wcscmp(string, table->strings[i].string) == 0) { return &table->strings[i]; } } return NULL; } void string_table_put(string_table_t *table, wchar_t *string) { size_t s_size = (wcslen(string) * 2) + 2; if (!s_size) { ppelib_set_error("String empty"); return; } if (s_size > UINT16_MAX) { ppelib_set_error("String size too long"); return; } if (string_table_find(table, string)) { return; } table->size++; table->bytes += s_size; table->strings = realloc(table->strings, sizeof(string_table_string_t) * table->size); table->strings[table->size - 1].string = string; table->strings[table->size - 1].bytes = (uint16_t)s_size; if (table->size > 1) { uint32_t prev_offset = table->strings[table->size - 2].offset; uint32_t prev_length = table->strings[table->size - 2].bytes; table->strings[table->size - 1].offset = prev_offset + prev_length; } else { table->strings[table->size - 1].offset = 0; } } void string_table_free(string_table_t *table) { free(table->strings); } size_t table_length(const ppelib_resource_table_t *resource_table, size_t in_size) { size_t subdirs_size = 0; for (uint32_t i = 0; i < resource_table->subdirectories_number; ++i) { subdirs_size += table_length(resource_table->subdirectories[i], in_size); } size_t entries_size = (resource_table->subdirectories_number + resource_table->data_entries_number) * 8; return in_size + subdirs_size + 16 + entries_size; } size_t table_data_entries_number(const ppelib_resource_table_t *resource_table, size_t in_size) { size_t subdirs_size = 0; for (uint32_t i = 0; i < resource_table->subdirectories_number; ++i) { subdirs_size += table_data_entries_number(resource_table->subdirectories[i], in_size); } return in_size + subdirs_size + resource_table->data_entries_number; } size_t write_tables(const ppelib_resource_table_t *resource_table, uint8_t *buffer, size_t offset, string_table_t *string_table, size_t *data_entries_offset, size_t *data_offset, size_t rscs_base) { size_t furthest = offset; size_t next_entry = 0; size_t number_of_name_entries = 0; size_t number_of_id_entries = 0; for (size_t i = 0; i < resource_table->subdirectories_number; ++i) { if (resource_table->subdirectories[i]->name) { number_of_name_entries++; } else { number_of_id_entries++; } } for (size_t i = 0; i < resource_table->data_entries_number; ++i) { if (resource_table->data_entries[i]->name) { number_of_name_entries++; } else { number_of_id_entries++; } } if (number_of_name_entries > UINT16_MAX) { ppelib_set_error("Too many name entries"); return 0; } if (number_of_id_entries > UINT16_MAX) { ppelib_set_error("Too many id entries"); return 0; } if (buffer) { uint8_t *table = buffer + offset; write_uint32_t(table + 0, resource_table->characteristics); write_uint32_t(table + 4, resource_table->time_date_stamp); write_uint16_t(table + 8, resource_table->major_version); write_uint16_t(table + 10, resource_table->minor_version); write_uint16_t(table + 12, (uint16_t)number_of_name_entries); write_uint16_t(table + 14, (uint16_t)number_of_id_entries); } offset += 16; furthest = MAX(furthest, offset); next_entry = offset + ((number_of_name_entries + number_of_id_entries) * 8); for (size_t i = 0; i < resource_table->subdirectories_number; ++i) { if (next_entry > UINT32_MAX) { ppelib_set_error("Sub-directory offset out of range"); return 0; } const ppelib_resource_table_t *t = resource_table->subdirectories[i]; uint32_t name_offset_or_id = 0; uint32_t entry_offset = (uint32_t)next_entry; next_entry += table_length(t, 0); if (t->name) { string_table_string_t *string = string_table_find(string_table, t->name); name_offset_or_id = (string_table->base_offset + string->offset) ^ HIGH_BIT32; } else { name_offset_or_id = t->resource_type; } if (buffer) { uint8_t *entry = buffer + offset; write_uint32_t(entry + 0, name_offset_or_id); write_uint32_t(entry + 4, entry_offset ^ HIGH_BIT32); } size_t t_furthest = write_tables(t, buffer, entry_offset, string_table, data_entries_offset, data_offset, rscs_base); offset += 8; furthest = MAX(furthest, t_furthest); furthest = MAX(furthest, offset); } for (uint32_t i = 0; i < resource_table->data_entries_number; ++i) { if (*data_entries_offset > UINT32_MAX) { ppelib_set_error("Data entry offset out of range"); return 0; } const ppelib_resource_data_t *d = resource_table->data_entries[i]; uint32_t name_offset_or_id = 0; uint32_t entry_offset = (uint32_t)*data_entries_offset; if (d->name) { string_table_string_t *string = string_table_find(string_table, d->name); name_offset_or_id = (string_table->base_offset + string->offset) ^ HIGH_BIT32; } else { name_offset_or_id = d->resource_type; } if (buffer) { uint8_t *entry = buffer + offset; write_uint32_t(entry + 0, name_offset_or_id); write_uint32_t(entry + 4, entry_offset); write_uint32_t(buffer + entry_offset + 0, (uint32_t)rscs_base + (uint32_t)*data_offset); write_uint32_t(buffer + entry_offset + 4, d->size); write_uint32_t(buffer + entry_offset + 8, d->codepage); write_uint32_t(buffer + entry_offset + 12, d->reserved); memcpy(buffer + *data_offset, d->data, d->size); } *data_entries_offset = entry_offset + 16; *data_offset = TO_NEAREST(*data_offset + d->size, 8); offset += 8; furthest = MAX(furthest, *data_offset); furthest = MAX(furthest, offset); } return furthest; } void fill_string_table(const ppelib_resource_table_t *resource_table, string_table_t *string_table) { if (resource_table->name) { string_table_put(string_table, resource_table->name); } for (size_t i = 0; i < resource_table->subdirectories_number; ++i) { fill_string_table(resource_table->subdirectories[i], string_table); } for (size_t i = 0; i < resource_table->data_entries_number; ++i) { if (resource_table->data_entries[i]->name) { string_table_put(string_table, resource_table->data_entries[i]->name); } } } size_t serialize_resource_table(const ppelib_resource_table_t *resource_table, uint8_t *buffer, size_t rscs_base) { ppelib_reset_error(); size_t furthest = 0; size_t string_table_offset = table_length(resource_table, 0); string_table_t string_table = {0}; if (string_table_offset > UINT32_MAX) { ppelib_set_error("String table too large"); return 0; } if (resource_table->data_entries_number + resource_table->subdirectories_number == 0) { return 0; } string_table.base_offset = (uint32_t)string_table_offset; size_t data_entries = table_data_entries_number(resource_table, 0); fill_string_table(resource_table, &string_table); if (ppelib_error_peek()) { string_table_free(&string_table); return 0; } size_t data_entries_offset = TO_NEAREST(string_table_offset + string_table.bytes, 4); size_t data_offset = data_entries_offset + (data_entries * 16); furthest = data_offset; if (buffer) { string_table_serialize(&string_table, buffer); } size_t tables_furthest = write_tables(resource_table, buffer, 0, &string_table, &data_entries_offset, &data_offset, rscs_base); string_table_free(&string_table); furthest = MAX(furthest, tables_furthest); return furthest; } wchar_t *get_string(uint8_t *buffer, size_t offset) { if (offset + 2 > t_max_size) { ppelib_set_error("Section too small for string"); t_parse_error_handled = 0; return NULL; } uint16_t size = read_uint16_t(buffer + offset + 0); if (offset + 2u + (size * 2u) > t_max_size) { ppelib_set_error("Section too small for string"); t_parse_error_handled = 0; return NULL; } wchar_t *string = calloc((size + 1u) * sizeof(wchar_t), 1); if (!string) { ppelib_set_error("Failed to allocate string"); t_parse_error_handled = 0; return NULL; } if (sizeof(wchar_t) == 2) { memcpy(string, buffer + 2u, size * 2u); } else { for (uint16_t i = 0; i < size; ++i) { memcpy(string + i, buffer + offset + 2 + (i * 2), 2); } } return string; } size_t parse_data_entry(ppelib_resource_data_t *data_entry, uint8_t *buffer, size_t offset) { uint32_t data_rva = read_uint32_t(buffer + offset + 0) - t_rscs_base; data_entry->size = read_uint32_t(buffer + offset + 4); data_entry->codepage = read_uint32_t(buffer + offset + 8); data_entry->reserved = read_uint32_t(buffer + offset + 12); if (data_rva > t_max_size || data_entry->size > t_max_size || data_rva + data_entry->size > t_max_size) { ppelib_set_error("Section too small for resource data entry data"); t_parse_error_handled = 0; return 0; } data_entry->data = malloc(data_entry->size); if (!data_entry->data) { ppelib_set_error("Failed to allocate resource data"); t_parse_error_handled = 0; return 0; } memcpy(data_entry->data, buffer + data_rva, data_entry->size); return data_rva + data_entry->size; } size_t parse_directory_table(ppelib_resource_table_t *resource_table, uint8_t *buffer, size_t offset, size_t depth) { depth++; if (depth > 10) { ppelib_set_error("Parse depth (10) exceeded"); t_parse_error_handled = 0; return 0; } size_t size = 0; uint8_t *table = buffer + offset; resource_table->characteristics = read_uint32_t(table + 0); resource_table->time_date_stamp = read_uint32_t(table + 4); resource_table->major_version = read_uint16_t(table + 8); resource_table->minor_version = read_uint16_t(table + 10); uint16_t number_of_name_entries = read_uint16_t(table + 12); uint16_t number_of_id_entries = read_uint16_t(table + 14); size_t min_space = ((uint32_t)(number_of_name_entries + number_of_id_entries)) * 8u; if (offset + 16 + min_space > t_max_size) { ppelib_set_error("Section too small for resource table (no space for directory contents)"); t_parse_error_handled = 0; return 0; } uint8_t *entries = table + 16; for (uint16_t i = 0; i < number_of_name_entries + number_of_id_entries; ++i) { uint32_t name_offset_or_id = read_uint32_t(entries + 0); uint32_t entry_offset = read_uint32_t(entries + 4); entries += 8; wchar_t *name = NULL; if (CHECK_BIT(name_offset_or_id, HIGH_BIT32)) { name = get_string(buffer, name_offset_or_id ^ HIGH_BIT32); if (ppelib_error_peek()) { return 0; } } if (CHECK_BIT(entry_offset, HIGH_BIT32)) { entry_offset = entry_offset ^ HIGH_BIT32; if (offset + 16 + entry_offset + 16 > t_max_size) { free(name); ppelib_set_error("Section too small for sub-directory"); t_parse_error_handled = 0; return 0; } resource_table->subdirectories_number++; size_t subdirs = resource_table->subdirectories_number; void *oldptr = resource_table->subdirectories; resource_table->subdirectories = realloc(resource_table->subdirectories, sizeof(void *) * subdirs); if (!resource_table->subdirectories) { resource_table->subdirectories = oldptr; resource_table->subdirectories_number--; ppelib_set_error("Failed to allocate resource sub-directory entry"); return 0; } resource_table->subdirectories[subdirs - 1] = calloc(sizeof(ppelib_resource_table_t), 1); ppelib_resource_table_t *subdir = resource_table->subdirectories[subdirs - 1]; if (!subdir) { ppelib_set_error("Failed to allocate resource sub-directory entry"); t_parse_error_handled = 0; return 0; } if (name) { subdir->name = name; } else { subdir->resource_type = name_offset_or_id; } size_t subdir_size = parse_directory_table(subdir, buffer, entry_offset, depth); if (ppelib_error_peek()) { if (!t_parse_error_handled) { t_parse_error_handled = 1; free(name); resource_table->subdirectories_number--; subdirs = resource_table->subdirectories_number; free_resource_directory_table(resource_table->subdirectories[subdirs]); free(resource_table->subdirectories[subdirs]); resource_table->subdirectories = realloc(resource_table->subdirectories, sizeof(void *) * subdirs); } return 0; } size = MAX(size, subdir_size); } else { if (offset + 16 + entry_offset + 16 > t_max_size) { free(name); ppelib_set_error("Section too small for data entry"); t_parse_error_handled = 0; return 0; } resource_table->data_entries_number++; size_t datas = resource_table->data_entries_number; void *oldptr = resource_table->data_entries; resource_table->data_entries = realloc(resource_table->data_entries, sizeof(void *) * datas); if (!resource_table->data_entries) { resource_table->data_entries = oldptr; resource_table->data_entries_number--; ppelib_set_error("Failed to allocate resource data entry"); return 0; } resource_table->data_entries[datas - 1] = calloc(sizeof(ppelib_resource_data_t), 1); ppelib_resource_data_t *data_entry = resource_table->data_entries[datas - 1]; if (!data_entry) { ppelib_set_error("Failed to allocate resource data entry"); return 0; } if (name) { data_entry->name = name; } else { data_entry->resource_type = name_offset_or_id; } size_t data_size = parse_data_entry(data_entry, buffer, entry_offset); if (ppelib_error_peek()) { if (!t_parse_error_handled) { t_parse_error_handled = 1; free(name); resource_table->data_entries_number--; free(resource_table->data_entries[resource_table->data_entries_number]); resource_table->data_entries = realloc(resource_table->data_entries, sizeof(void *) * resource_table->data_entries_number); return 0; } } size = MAX(size, data_size); } } return size; } EXPORT_SYM void ppelib_update_resource_table(ppelib_file_t *pe) { ppelib_reset_error(); size_t old_resource_table_size = 0; uint32_t table_offset = 0; uint16_t section_index = 0; ppelib_section_t *section = NULL; size_t resource_table_size = serialize_resource_table(&pe->resource_table, NULL, 0); if (ppelib_error_peek()) { return; } if (resource_table_size > UINT32_MAX) { ppelib_error("Resource table too big"); return; } if (pe->header.number_of_rva_and_sizes > DIR_RESOURCE_TABLE) { old_resource_table_size = pe->data_directories[DIR_RESOURCE_TABLE].size; table_offset = pe->data_directories[DIR_RESOURCE_TABLE].offset; section = pe->data_directories[DIR_RESOURCE_TABLE].section; } else { pe->data_directories = realloc(pe->data_directories, sizeof(ppelib_data_directory_t) * (DIR_RESOURCE_TABLE + 1)); memset(pe->data_directories + pe->header.number_of_rva_and_sizes, 0, sizeof(ppelib_data_directory_t) * (DIR_RESOURCE_TABLE + 1 - pe->header.number_of_rva_and_sizes)); pe->header.number_of_rva_and_sizes = DIR_RESOURCE_TABLE + 1; } if (section) { uint16_t section_index = 0; if (old_resource_table_size != resource_table_size) { section_index = ppelib_section_find_index(pe, section); if (ppelib_error_peek()) { section = NULL; goto invalid_section; } } if (old_resource_table_size > resource_table_size) { size_t diff = old_resource_table_size - resource_table_size; size_t start = table_offset + diff; ppelib_section_excise(pe, section_index, start, start + diff); if (ppelib_error_peek()) { return; } } else { size_t diff = resource_table_size - old_resource_table_size; ppelib_section_insert_capacity(pe, section_index, diff, table_offset); if (ppelib_error_peek()) { return; } } } invalid_section: if (!section && resource_table_size) { section_index = ppelib_section_create(pe, ".rscs", 0, (uint32_t)resource_table_size, IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, NULL); if (ppelib_error_peek()) { return; } section = pe->sections[section_index]; } if (resource_table_size) { //memset(section->contents + table_offset, 0, resource_table_size); serialize_resource_table(&pe->resource_table, section->contents + table_offset, section->virtual_address); } pe->data_directories[DIR_RESOURCE_TABLE].size = (uint32_t)resource_table_size; pe->data_directories[DIR_RESOURCE_TABLE].offset = table_offset; } size_t parse_resource_table(ppelib_file_t *pe) { ppelib_reset_error(); t_parse_error_handled = 0; if (pe->header.number_of_rva_and_sizes < DIR_RESOURCE_TABLE) { ppelib_set_error("No resource table found (too few directory entries)."); } ppelib_section_t *section = pe->data_directories[DIR_RESOURCE_TABLE].section; size_t table_offset = pe->data_directories[DIR_RESOURCE_TABLE].offset; size_t table_size = pe->data_directories[DIR_RESOURCE_TABLE].size; if (!table_size) { ppelib_set_error("No resource table found. (no size)"); return 0; } if (!section) { ppelib_set_error("Resource table not in section"); return 0; } if (table_offset + table_size > section->contents_size) { ppelib_set_error("Section too small for table. (offset + size too large)"); return 0; } memset(&pe->resource_table, 0, sizeof(ppelib_resource_table_t)); pe->resource_table.root = 1; uint8_t *data_table = section->contents + table_offset; if (table_offset + 16 > section->contents_size) { ppelib_set_error("Section too small for table. (No room for directory table)"); return 0; } t_max_size = section->contents_size; if (pe->data_directories[DIR_RESOURCE_TABLE].orig_rva > UINT32_MAX) { ppelib_set_error("Data directory offset out of range"); return 0; } t_rscs_base = (uint32_t)section->virtual_address; return parse_directory_table(&pe->resource_table, data_table, 0, 0); } void free_resource_directory_table(ppelib_resource_table_t *table) { for (size_t i = 0; i < table->data_entries_number; ++i) { free(table->data_entries[i]->data); free(table->data_entries[i]->name); free(table->data_entries[i]); } free(table->data_entries); table->data_entries_number = 0; for (size_t i = 0; i < table->subdirectories_number; ++i) { free_resource_directory_table(table->subdirectories[i]); free(table->subdirectories[i]->name); free(table->subdirectories[i]); } free(table->subdirectories); table->subdirectories_number = 0; } void free_resource_directory(ppelib_file_t *pe) { free_resource_directory_table(&pe->resource_table); } void print_resource_directory_data(const ppelib_resource_data_t *data, uint32_t indent) { for (uint32_t i = 0; i < indent; ++i) { printf(" "); } if (data->name) { printf("Data: Name(%ls) Size(%i) Codepage(0x%08X (%s))\n", data->name, data->size, data->codepage, map_lookup(data->codepage, ppelib_charsets_types_map)); } else { printf("Data: Type(0x%08X: (%s)) Size(%i) Codepage(0x%08X (%s))\n", data->resource_type, map_lookup(data->resource_type, ppelib_resource_types_map), data->size, data->codepage, map_lookup(data->codepage, ppelib_charsets_types_map)); } } void print_resource_table(const ppelib_resource_table_t *table, uint32_t indent) { for (uint32_t i = 0; i < indent; ++i) { printf(" "); } if (table->name) { printf("Dir: Name(%ls) subdirs(%u) data_entries(%u)\n", table->name, (uint16_t)table->subdirectories_number, (uint16_t)table->data_entries_number); } else { printf("Dir: Type(0x%08X: (%s)) subdirs(%u) data_entries(%u)\n", table->resource_type, map_lookup(table->resource_type, ppelib_resource_types_map), (uint16_t)table->subdirectories_number, (uint16_t)table->data_entries_number); } for (size_t i = 0; i < table->subdirectories_number; ++i) { print_resource_table(table->subdirectories[i], indent + 2u); } for (size_t i = 0; i < table->data_entries_number; ++i) { print_resource_directory_data(table->data_entries[i], indent + 2u); } } EXPORT_SYM ppelib_resource_table_t *ppelib_get_resource_table(ppelib_file_t *pe) { ppelib_reset_error(); return &pe->resource_table; } EXPORT_SYM void ppelib_print_resource_table(const ppelib_resource_table_t *resource_table) { ppelib_reset_error(); print_resource_table(resource_table, 0); }
29.746594
117
0.725016
23a821bd2419c59f10284ebd0712e5cbc8a5f5d5
85
h
C
consts.h
qicosmos/qimq
0b32ee3efe6974f1559b9c13831bfc8a89b45369
[ "MIT" ]
23
2020-02-10T09:59:19.000Z
2021-05-19T06:36:32.000Z
consts.h
qicosmos/qimq
0b32ee3efe6974f1559b9c13831bfc8a89b45369
[ "MIT" ]
1
2020-03-01T01:52:31.000Z
2020-03-03T12:28:01.000Z
consts.h
qicosmos/qimq
0b32ee3efe6974f1559b9c13831bfc8a89b45369
[ "MIT" ]
5
2020-02-26T11:41:31.000Z
2020-03-07T15:00:30.000Z
#pragma once #include <string> namespace qimq { static std::string EMPTY_STR = ""; }
17
35
0.705882
26c25b7ca69260252e75d03829477b06055ff271
4,492
h
C
kratos/includes/fill_communicator.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
null
null
null
kratos/includes/fill_communicator.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
null
null
null
kratos/includes/fill_communicator.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Ruben Zorrilla // #if !defined(KRATOS_FILL_COMMUNICATOR_H_INCLUDED ) #define KRATOS_FILL_COMMUNICATOR_H_INCLUDED // System includes // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Base class defining the API for the fill communicator utilities /** The objective of this class is to set the API for the derived ParallelFillCommunicator utilities */ class KRATOS_API(KRATOS_CORE) FillCommunicator { public: ///@name Type Definitions ///@{ /// Pointer definition of FillCommunicator KRATOS_CLASS_POINTER_DEFINITION(FillCommunicator); ///@} ///@name Life Cycle ///@{ /// Constructor. FillCommunicator(ModelPart& rModelPart); FillCommunicator( ModelPart& rModelPart, const DataCommunicator& rDataComm); /// Copy constructor. FillCommunicator(FillCommunicator const& rOther) = delete; /// Destructor. virtual ~FillCommunicator() = default; ///@} ///@name Operators ///@{ /// Assignment operator. FillCommunicator& operator=(FillCommunicator const& rOther) = delete; ///@} ///@name Operations ///@{ /** * @brief Execute the communicator fill * This method is intended to perform the communicator filling In the current serial case it does nothing. * For the parallel implementation see ParallelFillCommunicator. */ virtual void Execute(); /** * @brief Function to print DETAILED mesh information * WARNING: to be used for debugging only as many informations are plotted */ void PrintDebugInfo(); /** * @brief Function to print mesh information of the provided model part * This function is intended to check and print some mesh information * In the current serial case it is almost empty and only basic checks are performed * @param rModelPart Reference to the model part to be checked */ virtual void PrintModelPartDebugInfo(const ModelPart& rModelPart); ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const; /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const; /// Print object's data. virtual void PrintData(std::ostream& rOStream) const; ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ const DataCommunicator& mrDataComm; ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ModelPart& GetBaseModelPart() { return mrBaseModelPart; } ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ModelPart& mrBaseModelPart; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class FillCommunicator ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream & operator >>( std::istream& rIStream, FillCommunicator& rThis) { return rIStream; } /// output stream function inline std::ostream & operator <<( std::ostream& rOStream, const FillCommunicator& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_FILL_COMMUNICATOR_H_INCLUDED defined
17.754941
110
0.586598
c17c073426316725d84503bb86699cc7b77ce476
455
h
C
FrequentItems.h
JoshuaEng/FLINNG
ba660a6ea293b91c6d9d6b15f58f80dab507bfe2
[ "MIT" ]
4
2021-06-24T10:08:40.000Z
2021-12-02T12:24:36.000Z
FrequentItems.h
JoshuaEng/FLINNG
ba660a6ea293b91c6d9d6b15f58f80dab507bfe2
[ "MIT" ]
null
null
null
FrequentItems.h
JoshuaEng/FLINNG
ba660a6ea293b91c6d9d6b15f58f80dab507bfe2
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <queue> using namespace std; class FrequentItems { private: int * _values; int _k; int _size = 0; std::unordered_map<int, int> _keyToValLocMapping; std::unordered_map<int, int> _valLocToKeyMapping; std::queue<int> _emptyLocations; public: FrequentItems(int k); ~FrequentItems(); void increment(int item); unsigned int* getTopk(); void getTopk(unsigned int * outputs); };
18.958333
51
0.701099
bb651da4b2f56e342aca9b8637f29b3aef2e7cee
125,362
c
C
dmidecode/dmidecode.c
soIu/rpython
a9739d498c2812d56636d69307719082ec8cd8a2
[ "MIT" ]
11
2020-07-02T13:57:46.000Z
2022-01-23T18:04:42.000Z
dmidecode/dmidecode.c
rafi16jan/rpython-wasm
a9739d498c2812d56636d69307719082ec8cd8a2
[ "MIT" ]
1
2021-11-05T06:29:33.000Z
2021-11-06T12:33:46.000Z
dmidecode/dmidecode.c
rafi16jan/rpython-wasm
a9739d498c2812d56636d69307719082ec8cd8a2
[ "MIT" ]
2
2020-12-17T09:35:36.000Z
2021-11-24T15:34:08.000Z
/* * DMI Decode * * Copyright (C) 2000-2002 Alan Cox <alan@redhat.com> * Copyright (C) 2002-2017 Jean Delvare <jdelvare@suse.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For the avoidance of doubt the "preferred form" of this code is one which * is in an open unpatent encumbered format. Where cryptographic key signing * forms part of the process of creating an executable the information * including keys needed to generate an equivalently functional executable * are deemed to be part of the source code. * * Unless specified otherwise, all references are aimed at the "System * Management BIOS Reference Specification, Version 3.1.1" document, * available from http://www.dmtf.org/standards/smbios. * * Note to contributors: * Please reference every value you add or modify, especially if the * information does not come from the above mentioned specification. * * Additional references: * - Intel AP-485 revision 36 * "Intel Processor Identification and the CPUID Instruction" * http://www.intel.com/support/processors/sb/cs-009861.htm * - DMTF Common Information Model * CIM Schema version 2.19.1 * http://www.dmtf.org/standards/cim/ * - IPMI 2.0 revision 1.0 * "Intelligent Platform Management Interface Specification" * http://developer.intel.com/design/servers/ipmi/spec.htm * - AMD publication #25481 revision 2.28 * "CPUID Specification" * http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25481.pdf * - BIOS Integrity Services Application Programming Interface version 1.0 * http://www.intel.com/design/archives/wfm/downloads/bisspec.htm * - DMTF DSP0239 version 1.1.0 * "Management Component Transport Protocol (MCTP) IDs and Codes" * http://www.dmtf.org/standards/pmci * - "TPM Main, Part 2 TPM Structures" * Specification version 1.2, level 2, revision 116 * https://trustedcomputinggroup.org/tpm-main-specification/ * - "PC Client Platform TPM Profile (PTP) Specification" * Family "2.0", Level 00, Revision 00.43, January 26, 2015 * https://trustedcomputinggroup.org/pc-client-platform-tpm-profile-ptp-specification/ */ #if defined(__APPLE__) #include <Carbon/Carbon.h> #endif #include <stdio.h> #include <string.h> #include <strings.h> #include <stdlib.h> #include <unistd.h> #include "version.h" #include "config.h" #include "types.h" #include "util.h" #include "dmidecode.h" #include "dmiopt.h" #include "dmioem.h" #define out_of_spec "<OUT OF SPEC>" static const char *bad_index = "<BAD INDEX>"; #define SUPPORTED_SMBIOS_VER 0x030101 #define FLAG_NO_FILE_OFFSET (1 << 0) #define FLAG_STOP_AT_EOT (1 << 1) #define FLAG_FROM_API (1 << 2) #define SYS_FIRMWARE_DIR "/sys/firmware/dmi/tables" #define SYS_ENTRY_FILE SYS_FIRMWARE_DIR "/smbios_entry_point" #define SYS_TABLE_FILE SYS_FIRMWARE_DIR "/DMI" /* * Type-independant Stuff */ /* Returns 1 if the buffer contains only printable ASCII characters */ int is_printable(const u8 *data, int len) { int i; for (i = 0; i < len; i++) if (data[i] < 32 || data[i] >= 127) return 0; return 1; } const char *dmi_string(const struct dmi_header *dm, u8 s) { char *bp = (char *)dm->data; size_t i, len; if (s == 0) return "Not Specified"; bp += dm->length; while (s > 1 && *bp) { bp += strlen(bp); bp++; s--; } if (!*bp) return bad_index; if (!(opt.flags & FLAG_DUMP)) { /* ASCII filtering */ len = strlen(bp); for (i = 0; i < len; i++) if (bp[i] < 32 || bp[i] == 127) bp[i] = '.'; } return bp; } static const char *dmi_smbios_structure_type(u8 code) { static const char *type[] = { "BIOS", /* 0 */ "System", "Base Board", "Chassis", "Processor", "Memory Controller", "Memory Module", "Cache", "Port Connector", "System Slots", "On Board Devices", "OEM Strings", "System Configuration Options", "BIOS Language", "Group Associations", "System Event Log", "Physical Memory Array", "Memory Device", "32-bit Memory Error", "Memory Array Mapped Address", "Memory Device Mapped Address", "Built-in Pointing Device", "Portable Battery", "System Reset", "Hardware Security", "System Power Controls", "Voltage Probe", "Cooling Device", "Temperature Probe", "Electrical Current Probe", "Out-of-band Remote Access", "Boot Integrity Services", "System Boot", "64-bit Memory Error", "Management Device", "Management Device Component", "Management Device Threshold Data", "Memory Channel", "IPMI Device", "Power Supply", "Additional Information", "Onboard Device", "Management Controller Host Interface", "TPM Device", /* 43 */ }; if (code >= 128) return "OEM-specific"; if (code <= 43) return type[code]; return out_of_spec; } static int dmi_bcd_range(u8 value, u8 low, u8 high) { if (value > 0x99 || (value & 0x0F) > 0x09) return 0; if (value < low || value > high) return 0; return 1; } static void dmi_dump(const struct dmi_header *h, const char *prefix) { int row, i; const char *s; printf("%sHeader and Data:\n", prefix); for (row = 0; row < ((h->length - 1) >> 4) + 1; row++) { printf("%s\t", prefix); for (i = 0; i < 16 && i < h->length - (row << 4); i++) printf("%s%02X", i ? " " : "", (h->data)[(row << 4) + i]); printf("\n"); } if ((h->data)[h->length] || (h->data)[h->length + 1]) { printf("%sStrings:\n", prefix); i = 1; while ((s = dmi_string(h, i++)) != bad_index) { if (opt.flags & FLAG_DUMP) { int j, l = strlen(s) + 1; for (row = 0; row < ((l - 1) >> 4) + 1; row++) { printf("%s\t", prefix); for (j = 0; j < 16 && j < l - (row << 4); j++) printf("%s%02X", j ? " " : "", (unsigned char)s[(row << 4) + j]); printf("\n"); } /* String isn't filtered yet so do it now */ printf("%s\t\"", prefix); while (*s) { if (*s < 32 || *s == 127) fputc('.', stdout); else fputc(*s, stdout); s++; } printf("\"\n"); } else printf("%s\t%s\n", prefix, s); } } } /* shift is 0 if the value is in bytes, 1 if it is in kilobytes */ static void dmi_print_memory_size(u64 code, int shift) { unsigned long capacity; u16 split[7]; static const char *unit[8] = { "bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB" }; int i; /* * We split the overall size in powers of thousand: EB, PB, TB, GB, * MB, kB and B. In practice, it is expected that only one or two * (consecutive) of these will be non-zero. */ split[0] = code.l & 0x3FFUL; split[1] = (code.l >> 10) & 0x3FFUL; split[2] = (code.l >> 20) & 0x3FFUL; split[3] = ((code.h << 2) & 0x3FCUL) | (code.l >> 30); split[4] = (code.h >> 8) & 0x3FFUL; split[5] = (code.h >> 18) & 0x3FFUL; split[6] = code.h >> 28; /* * Now we find the highest unit with a non-zero value. If the following * is also non-zero, we use that as our base. If the following is zero, * we simply display the highest unit. */ for (i = 6; i > 0; i--) { if (split[i]) break; } if (i > 0 && split[i - 1]) { i--; capacity = split[i] + (split[i + 1] << 10); } else capacity = split[i]; printf(" %lu %s", capacity, unit[i + shift]); } /* * 7.1 BIOS Information (Type 0) */ static void dmi_bios_runtime_size(u32 code) { if (code & 0x000003FF) printf(" %u bytes", code); else printf(" %u kB", code >> 10); } static void dmi_bios_rom_size(u8 code1, u16 code2) { static const char *unit[4] = { "MB", "GB", out_of_spec, out_of_spec }; if (code1 != 0xFF) printf(" %u kB", (code1 + 1) << 6); else printf(" %u %s", code2 & 0x3FFF, unit[code2 >> 14]); } static void dmi_bios_characteristics(u64 code, const char *prefix) { /* 7.1.1 */ static const char *characteristics[] = { "BIOS characteristics not supported", /* 3 */ "ISA is supported", "MCA is supported", "EISA is supported", "PCI is supported", "PC Card (PCMCIA) is supported", "PNP is supported", "APM is supported", "BIOS is upgradeable", "BIOS shadowing is allowed", "VLB is supported", "ESCD support is available", "Boot from CD is supported", "Selectable boot is supported", "BIOS ROM is socketed", "Boot from PC Card (PCMCIA) is supported", "EDD is supported", "Japanese floppy for NEC 9800 1.2 MB is supported (int 13h)", "Japanese floppy for Toshiba 1.2 MB is supported (int 13h)", "5.25\"/360 kB floppy services are supported (int 13h)", "5.25\"/1.2 MB floppy services are supported (int 13h)", "3.5\"/720 kB floppy services are supported (int 13h)", "3.5\"/2.88 MB floppy services are supported (int 13h)", "Print screen service is supported (int 5h)", "8042 keyboard services are supported (int 9h)", "Serial services are supported (int 14h)", "Printer services are supported (int 17h)", "CGA/mono video services are supported (int 10h)", "NEC PC-98" /* 31 */ }; int i; /* * This isn't very clear what this bit is supposed to mean */ if (code.l & (1 << 3)) { printf("%s%s\n", prefix, characteristics[0]); return; } for (i = 4; i <= 31; i++) if (code.l & (1 << i)) printf("%s%s\n", prefix, characteristics[i - 3]); } static void dmi_bios_characteristics_x1(u8 code, const char *prefix) { /* 7.1.2.1 */ static const char *characteristics[] = { "ACPI is supported", /* 0 */ "USB legacy is supported", "AGP is supported", "I2O boot is supported", "LS-120 boot is supported", "ATAPI Zip drive boot is supported", "IEEE 1394 boot is supported", "Smart battery is supported" /* 7 */ }; int i; for (i = 0; i <= 7; i++) if (code & (1 << i)) printf("%s%s\n", prefix, characteristics[i]); } static void dmi_bios_characteristics_x2(u8 code, const char *prefix) { /* 37.1.2.2 */ static const char *characteristics[] = { "BIOS boot specification is supported", /* 0 */ "Function key-initiated network boot is supported", "Targeted content distribution is supported", "UEFI is supported", "System is a virtual machine" /* 4 */ }; int i; for (i = 0; i <= 4; i++) if (code & (1 << i)) printf("%s%s\n", prefix, characteristics[i]); } /* * 7.2 System Information (Type 1) */ static void dmi_system_uuid(const u8 *p, u16 ver) { int only0xFF = 1, only0x00 = 1; int i; for (i = 0; i < 16 && (only0x00 || only0xFF); i++) { if (p[i] != 0x00) only0x00 = 0; if (p[i] != 0xFF) only0xFF = 0; } if (only0xFF) { printf("Not Present"); return; } if (only0x00) { printf("Not Settable"); return; } /* * As of version 2.6 of the SMBIOS specification, the first 3 * fields of the UUID are supposed to be encoded on little-endian. * The specification says that this is the defacto standard, * however I've seen systems following RFC 4122 instead and use * network byte order, so I am reluctant to apply the byte-swapping * for older versions. */ if (ver >= 0x0206) printf("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", p[3], p[2], p[1], p[0], p[5], p[4], p[7], p[6], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); else printf("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); } static const char *dmi_system_wake_up_type(u8 code) { /* 7.2.2 */ static const char *type[] = { "Reserved", /* 0x00 */ "Other", "Unknown", "APM Timer", "Modem Ring", "LAN Remote", "Power Switch", "PCI PME#", "AC Power Restored" /* 0x08 */ }; if (code <= 0x08) return type[code]; return out_of_spec; } /* * 7.3 Base Board Information (Type 2) */ static void dmi_base_board_features(u8 code, const char *prefix) { /* 7.3.1 */ static const char *features[] = { "Board is a hosting board", /* 0 */ "Board requires at least one daughter board", "Board is removable", "Board is replaceable", "Board is hot swappable" /* 4 */ }; if ((code & 0x1F) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 0; i <= 4; i++) if (code & (1 << i)) printf("%s%s\n", prefix, features[i]); } } static const char *dmi_base_board_type(u8 code) { /* 7.3.2 */ static const char *type[] = { "Unknown", /* 0x01 */ "Other", "Server Blade", "Connectivity Switch", "System Management Module", "Processor Module", "I/O Module", "Memory Module", "Daughter Board", "Motherboard", "Processor+Memory Module", "Processor+I/O Module", "Interconnect Board" /* 0x0D */ }; if (code >= 0x01 && code <= 0x0D) return type[code - 0x01]; return out_of_spec; } static void dmi_base_board_handles(u8 count, const u8 *p, const char *prefix) { int i; printf("%sContained Object Handles: %u\n", prefix, count); for (i = 0; i < count; i++) printf("%s\t0x%04X\n", prefix, WORD(p + sizeof(u16) * i)); } /* * 7.4 Chassis Information (Type 3) */ static const char *dmi_chassis_type(u8 code) { /* 7.4.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Desktop", "Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower", "Portable", "Laptop", "Notebook", "Hand Held", "Docking Station", "All In One", "Sub Notebook", "Space-saving", "Lunch Box", "Main Server Chassis", /* CIM_Chassis.ChassisPackageType says "Main System Chassis" */ "Expansion Chassis", "Sub Chassis", "Bus Expansion Chassis", "Peripheral Chassis", "RAID Chassis", "Rack Mount Chassis", "Sealed-case PC", "Multi-system", "CompactPCI", "AdvancedTCA", "Blade", "Blade Enclosing", "Tablet", "Convertible", "Detachable", "IoT Gateway", "Embedded PC", "Mini PC", "Stick PC" /* 0x24 */ }; code &= 0x7F; /* bits 6:0 are chassis type, 7th bit is the lock bit */ if (code >= 0x01 && code <= 0x24) return type[code - 0x01]; return out_of_spec; } static const char *dmi_chassis_lock(u8 code) { static const char *lock[] = { "Not Present", /* 0x00 */ "Present" /* 0x01 */ }; return lock[code]; } static const char *dmi_chassis_state(u8 code) { /* 7.4.2 */ static const char *state[] = { "Other", /* 0x01 */ "Unknown", "Safe", "Warning", "Critical", "Non-recoverable" /* 0x06 */ }; if (code >= 0x01 && code <= 0x06) return state[code - 0x01]; return out_of_spec; } static const char *dmi_chassis_security_status(u8 code) { /* 7.4.3 */ static const char *status[] = { "Other", /* 0x01 */ "Unknown", "None", "External Interface Locked Out", "External Interface Enabled" /* 0x05 */ }; if (code >= 0x01 && code <= 0x05) return status[code - 0x01]; return out_of_spec; } static void dmi_chassis_height(u8 code) { if (code == 0x00) printf(" Unspecified"); else printf(" %u U", code); } static void dmi_chassis_power_cords(u8 code) { if (code == 0x00) printf(" Unspecified"); else printf(" %u", code); } static void dmi_chassis_elements(u8 count, u8 len, const u8 *p, const char *prefix) { int i; printf("%sContained Elements: %u\n", prefix, count); for (i = 0; i < count; i++) { if (len >= 0x03) { printf("%s\t%s (", prefix, p[i * len] & 0x80 ? dmi_smbios_structure_type(p[i * len] & 0x7F) : dmi_base_board_type(p[i * len] & 0x7F)); if (p[1 + i * len] == p[2 + i * len]) printf("%u", p[1 + i * len]); else printf("%u-%u", p[1 + i * len], p[2 + i * len]); printf(")\n"); } } } /* * 7.5 Processor Information (Type 4) */ static const char *dmi_processor_type(u8 code) { /* 7.5.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Central Processor", "Math Processor", "DSP Processor", "Video Processor" /* 0x06 */ }; if (code >= 0x01 && code <= 0x06) return type[code - 0x01]; return out_of_spec; } static const char *dmi_processor_family(const struct dmi_header *h, u16 ver) { const u8 *data = h->data; unsigned int i, low, high; u16 code; /* 7.5.2 */ static struct { int value; const char *name; } family2[] = { { 0x01, "Other" }, { 0x02, "Unknown" }, { 0x03, "8086" }, { 0x04, "80286" }, { 0x05, "80386" }, { 0x06, "80486" }, { 0x07, "8087" }, { 0x08, "80287" }, { 0x09, "80387" }, { 0x0A, "80487" }, { 0x0B, "Pentium" }, { 0x0C, "Pentium Pro" }, { 0x0D, "Pentium II" }, { 0x0E, "Pentium MMX" }, { 0x0F, "Celeron" }, { 0x10, "Pentium II Xeon" }, { 0x11, "Pentium III" }, { 0x12, "M1" }, { 0x13, "M2" }, { 0x14, "Celeron M" }, { 0x15, "Pentium 4 HT" }, { 0x18, "Duron" }, { 0x19, "K5" }, { 0x1A, "K6" }, { 0x1B, "K6-2" }, { 0x1C, "K6-3" }, { 0x1D, "Athlon" }, { 0x1E, "AMD29000" }, { 0x1F, "K6-2+" }, { 0x20, "Power PC" }, { 0x21, "Power PC 601" }, { 0x22, "Power PC 603" }, { 0x23, "Power PC 603+" }, { 0x24, "Power PC 604" }, { 0x25, "Power PC 620" }, { 0x26, "Power PC x704" }, { 0x27, "Power PC 750" }, { 0x28, "Core Duo" }, { 0x29, "Core Duo Mobile" }, { 0x2A, "Core Solo Mobile" }, { 0x2B, "Atom" }, { 0x2C, "Core M" }, { 0x2D, "Core m3" }, { 0x2E, "Core m5" }, { 0x2F, "Core m7" }, { 0x30, "Alpha" }, { 0x31, "Alpha 21064" }, { 0x32, "Alpha 21066" }, { 0x33, "Alpha 21164" }, { 0x34, "Alpha 21164PC" }, { 0x35, "Alpha 21164a" }, { 0x36, "Alpha 21264" }, { 0x37, "Alpha 21364" }, { 0x38, "Turion II Ultra Dual-Core Mobile M" }, { 0x39, "Turion II Dual-Core Mobile M" }, { 0x3A, "Athlon II Dual-Core M" }, { 0x3B, "Opteron 6100" }, { 0x3C, "Opteron 4100" }, { 0x3D, "Opteron 6200" }, { 0x3E, "Opteron 4200" }, { 0x3F, "FX" }, { 0x40, "MIPS" }, { 0x41, "MIPS R4000" }, { 0x42, "MIPS R4200" }, { 0x43, "MIPS R4400" }, { 0x44, "MIPS R4600" }, { 0x45, "MIPS R10000" }, { 0x46, "C-Series" }, { 0x47, "E-Series" }, { 0x48, "A-Series" }, { 0x49, "G-Series" }, { 0x4A, "Z-Series" }, { 0x4B, "R-Series" }, { 0x4C, "Opteron 4300" }, { 0x4D, "Opteron 6300" }, { 0x4E, "Opteron 3300" }, { 0x4F, "FirePro" }, { 0x50, "SPARC" }, { 0x51, "SuperSPARC" }, { 0x52, "MicroSPARC II" }, { 0x53, "MicroSPARC IIep" }, { 0x54, "UltraSPARC" }, { 0x55, "UltraSPARC II" }, { 0x56, "UltraSPARC IIi" }, { 0x57, "UltraSPARC III" }, { 0x58, "UltraSPARC IIIi" }, { 0x60, "68040" }, { 0x61, "68xxx" }, { 0x62, "68000" }, { 0x63, "68010" }, { 0x64, "68020" }, { 0x65, "68030" }, { 0x66, "Athlon X4" }, { 0x67, "Opteron X1000" }, { 0x68, "Opteron X2000" }, { 0x69, "Opteron A-Series" }, { 0x6A, "Opteron X3000" }, { 0x6B, "Zen" }, { 0x70, "Hobbit" }, { 0x78, "Crusoe TM5000" }, { 0x79, "Crusoe TM3000" }, { 0x7A, "Efficeon TM8000" }, { 0x80, "Weitek" }, { 0x82, "Itanium" }, { 0x83, "Athlon 64" }, { 0x84, "Opteron" }, { 0x85, "Sempron" }, { 0x86, "Turion 64" }, { 0x87, "Dual-Core Opteron" }, { 0x88, "Athlon 64 X2" }, { 0x89, "Turion 64 X2" }, { 0x8A, "Quad-Core Opteron" }, { 0x8B, "Third-Generation Opteron" }, { 0x8C, "Phenom FX" }, { 0x8D, "Phenom X4" }, { 0x8E, "Phenom X2" }, { 0x8F, "Athlon X2" }, { 0x90, "PA-RISC" }, { 0x91, "PA-RISC 8500" }, { 0x92, "PA-RISC 8000" }, { 0x93, "PA-RISC 7300LC" }, { 0x94, "PA-RISC 7200" }, { 0x95, "PA-RISC 7100LC" }, { 0x96, "PA-RISC 7100" }, { 0xA0, "V30" }, { 0xA1, "Quad-Core Xeon 3200" }, { 0xA2, "Dual-Core Xeon 3000" }, { 0xA3, "Quad-Core Xeon 5300" }, { 0xA4, "Dual-Core Xeon 5100" }, { 0xA5, "Dual-Core Xeon 5000" }, { 0xA6, "Dual-Core Xeon LV" }, { 0xA7, "Dual-Core Xeon ULV" }, { 0xA8, "Dual-Core Xeon 7100" }, { 0xA9, "Quad-Core Xeon 5400" }, { 0xAA, "Quad-Core Xeon" }, { 0xAB, "Dual-Core Xeon 5200" }, { 0xAC, "Dual-Core Xeon 7200" }, { 0xAD, "Quad-Core Xeon 7300" }, { 0xAE, "Quad-Core Xeon 7400" }, { 0xAF, "Multi-Core Xeon 7400" }, { 0xB0, "Pentium III Xeon" }, { 0xB1, "Pentium III Speedstep" }, { 0xB2, "Pentium 4" }, { 0xB3, "Xeon" }, { 0xB4, "AS400" }, { 0xB5, "Xeon MP" }, { 0xB6, "Athlon XP" }, { 0xB7, "Athlon MP" }, { 0xB8, "Itanium 2" }, { 0xB9, "Pentium M" }, { 0xBA, "Celeron D" }, { 0xBB, "Pentium D" }, { 0xBC, "Pentium EE" }, { 0xBD, "Core Solo" }, /* 0xBE handled as a special case */ { 0xBF, "Core 2 Duo" }, { 0xC0, "Core 2 Solo" }, { 0xC1, "Core 2 Extreme" }, { 0xC2, "Core 2 Quad" }, { 0xC3, "Core 2 Extreme Mobile" }, { 0xC4, "Core 2 Duo Mobile" }, { 0xC5, "Core 2 Solo Mobile" }, { 0xC6, "Core i7" }, { 0xC7, "Dual-Core Celeron" }, { 0xC8, "IBM390" }, { 0xC9, "G4" }, { 0xCA, "G5" }, { 0xCB, "ESA/390 G6" }, { 0xCC, "z/Architecture" }, { 0xCD, "Core i5" }, { 0xCE, "Core i3" }, { 0xD2, "C7-M" }, { 0xD3, "C7-D" }, { 0xD4, "C7" }, { 0xD5, "Eden" }, { 0xD6, "Multi-Core Xeon" }, { 0xD7, "Dual-Core Xeon 3xxx" }, { 0xD8, "Quad-Core Xeon 3xxx" }, { 0xD9, "Nano" }, { 0xDA, "Dual-Core Xeon 5xxx" }, { 0xDB, "Quad-Core Xeon 5xxx" }, { 0xDD, "Dual-Core Xeon 7xxx" }, { 0xDE, "Quad-Core Xeon 7xxx" }, { 0xDF, "Multi-Core Xeon 7xxx" }, { 0xE0, "Multi-Core Xeon 3400" }, { 0xE4, "Opteron 3000" }, { 0xE5, "Sempron II" }, { 0xE6, "Embedded Opteron Quad-Core" }, { 0xE7, "Phenom Triple-Core" }, { 0xE8, "Turion Ultra Dual-Core Mobile" }, { 0xE9, "Turion Dual-Core Mobile" }, { 0xEA, "Athlon Dual-Core" }, { 0xEB, "Sempron SI" }, { 0xEC, "Phenom II" }, { 0xED, "Athlon II" }, { 0xEE, "Six-Core Opteron" }, { 0xEF, "Sempron M" }, { 0xFA, "i860" }, { 0xFB, "i960" }, { 0x100, "ARMv7" }, { 0x101, "ARMv8" }, { 0x104, "SH-3" }, { 0x105, "SH-4" }, { 0x118, "ARM" }, { 0x119, "StrongARM" }, { 0x12C, "6x86" }, { 0x12D, "MediaGX" }, { 0x12E, "MII" }, { 0x140, "WinChip" }, { 0x15E, "DSP" }, { 0x1F4, "Video Processor" }, }; /* * Note to developers: when adding entries to this list, check if * function dmi_processor_id below needs updating too. */ /* Special case for ambiguous value 0x30 (SMBIOS 2.0 only) */ if (ver == 0x0200 && data[0x06] == 0x30 && h->length >= 0x08) { const char *manufacturer = dmi_string(h, data[0x07]); if (strstr(manufacturer, "Intel") != NULL || strncasecmp(manufacturer, "Intel", 5) == 0) return "Pentium Pro"; } code = (data[0x06] == 0xFE && h->length >= 0x2A) ? WORD(data + 0x28) : data[0x06]; /* Special case for ambiguous value 0xBE */ if (code == 0xBE) { if (h->length >= 0x08) { const char *manufacturer = dmi_string(h, data[0x07]); /* Best bet based on manufacturer string */ if (strstr(manufacturer, "Intel") != NULL || strncasecmp(manufacturer, "Intel", 5) == 0) return "Core 2"; if (strstr(manufacturer, "AMD") != NULL || strncasecmp(manufacturer, "AMD", 3) == 0) return "K7"; } return "Core 2 or K7"; } /* Perform a binary search */ low = 0; high = ARRAY_SIZE(family2) - 1; while (1) { i = (low + high) / 2; if (family2[i].value == code) return family2[i].name; if (low == high) /* Not found */ return out_of_spec; if (code < family2[i].value) high = i; else low = i + 1; } } static void dmi_processor_id(const struct dmi_header *h, const char *prefix) { /* Intel AP-485 revision 36, table 2-4 */ static const char *flags[32] = { "FPU (Floating-point unit on-chip)", /* 0 */ "VME (Virtual mode extension)", "DE (Debugging extension)", "PSE (Page size extension)", "TSC (Time stamp counter)", "MSR (Model specific registers)", "PAE (Physical address extension)", "MCE (Machine check exception)", "CX8 (CMPXCHG8 instruction supported)", "APIC (On-chip APIC hardware supported)", NULL, /* 10 */ "SEP (Fast system call)", "MTRR (Memory type range registers)", "PGE (Page global enable)", "MCA (Machine check architecture)", "CMOV (Conditional move instruction supported)", "PAT (Page attribute table)", "PSE-36 (36-bit page size extension)", "PSN (Processor serial number present and enabled)", "CLFSH (CLFLUSH instruction supported)", NULL, /* 20 */ "DS (Debug store)", "ACPI (ACPI supported)", "MMX (MMX technology supported)", "FXSR (FXSAVE and FXSTOR instructions supported)", "SSE (Streaming SIMD extensions)", "SSE2 (Streaming SIMD extensions 2)", "SS (Self-snoop)", "HTT (Multi-threading)", "TM (Thermal monitor supported)", NULL, /* 30 */ "PBE (Pending break enabled)" /* 31 */ }; const u8 *data = h->data; const u8 *p = data + 0x08; u32 eax, edx; int sig = 0; u16 type; type = (data[0x06] == 0xFE && h->length >= 0x2A) ? WORD(data + 0x28) : data[0x06]; /* * This might help learn about new processors supporting the * CPUID instruction or another form of identification. */ printf("%sID: %02X %02X %02X %02X %02X %02X %02X %02X\n", prefix, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); if (type == 0x05) /* 80386 */ { u16 dx = WORD(p); /* * 80386 have a different signature. */ printf("%sSignature: Type %u, Family %u, Major Stepping %u, Minor Stepping %u\n", prefix, dx >> 12, (dx >> 8) & 0xF, (dx >> 4) & 0xF, dx & 0xF); return; } if (type == 0x06) /* 80486 */ { u16 dx = WORD(p); /* * Not all 80486 CPU support the CPUID instruction, we have to find * wether the one we have here does or not. Note that this trick * works only because we know that 80486 must be little-endian. */ if ((dx & 0x0F00) == 0x0400 && ((dx & 0x00F0) == 0x0040 || (dx & 0x00F0) >= 0x0070) && ((dx & 0x000F) >= 0x0003)) sig = 1; else { printf("%sSignature: Type %u, Family %u, Model %u, Stepping %u\n", prefix, (dx >> 12) & 0x3, (dx >> 8) & 0xF, (dx >> 4) & 0xF, dx & 0xF); return; } } else if ((type >= 0x100 && type <= 0x101) /* ARM */ || (type >= 0x118 && type <= 0x119)) /* ARM */ { u32 midr = DWORD(p); /* * The format of this field was not defined for ARM processors * before version 3.1.0 of the SMBIOS specification, so we * silently skip it if it reads all zeroes. */ if (midr == 0) return; printf("%sSignature: Implementor 0x%02x, Variant 0x%x, Architecture %u, Part 0x%03x, Revision %u\n", prefix, midr >> 24, (midr >> 20) & 0xF, (midr >> 16) & 0xF, (midr >> 4) & 0xFFF, midr & 0xF); return; } else if ((type >= 0x0B && type <= 0x15) /* Intel, Cyrix */ || (type >= 0x28 && type <= 0x2F) /* Intel */ || (type >= 0xA1 && type <= 0xB3) /* Intel */ || type == 0xB5 /* Intel */ || (type >= 0xB9 && type <= 0xC7) /* Intel */ || (type >= 0xCD && type <= 0xCE) /* Intel */ || (type >= 0xD2 && type <= 0xDB) /* VIA, Intel */ || (type >= 0xDD && type <= 0xE0)) /* Intel */ sig = 1; else if ((type >= 0x18 && type <= 0x1D) /* AMD */ || type == 0x1F /* AMD */ || (type >= 0x38 && type <= 0x3F) /* AMD */ || (type >= 0x46 && type <= 0x4F) /* AMD */ || (type >= 0x66 && type <= 0x6B) /* AMD */ || (type >= 0x83 && type <= 0x8F) /* AMD */ || (type >= 0xB6 && type <= 0xB7) /* AMD */ || (type >= 0xE4 && type <= 0xEF)) /* AMD */ sig = 2; else if (type == 0x01 || type == 0x02) { const char *version = dmi_string(h, data[0x10]); /* * Some X86-class CPU have family "Other" or "Unknown". In this case, * we use the version string to determine if they are known to * support the CPUID instruction. */ if (strncmp(version, "Pentium III MMX", 15) == 0 || strncmp(version, "Intel(R) Core(TM)2", 18) == 0 || strncmp(version, "Intel(R) Pentium(R)", 19) == 0 || strcmp(version, "Genuine Intel(R) CPU U1400") == 0) sig = 1; else if (strncmp(version, "AMD Athlon(TM)", 14) == 0 || strncmp(version, "AMD Opteron(tm)", 15) == 0 || strncmp(version, "Dual-Core AMD Opteron(tm)", 25) == 0) sig = 2; else return; } else /* neither X86 nor ARM */ return; /* * Extra flags are now returned in the ECX register when one calls * the CPUID instruction. Their meaning is explained in table 3-5, but * DMI doesn't support this yet. */ eax = DWORD(p); edx = DWORD(p + 4); switch (sig) { case 1: /* Intel */ printf("%sSignature: Type %u, Family %u, Model %u, Stepping %u\n", prefix, (eax >> 12) & 0x3, ((eax >> 20) & 0xFF) + ((eax >> 8) & 0x0F), ((eax >> 12) & 0xF0) + ((eax >> 4) & 0x0F), eax & 0xF); break; case 2: /* AMD, publication #25481 revision 2.28 */ printf("%sSignature: Family %u, Model %u, Stepping %u\n", prefix, ((eax >> 8) & 0xF) + (((eax >> 8) & 0xF) == 0xF ? (eax >> 20) & 0xFF : 0), ((eax >> 4) & 0xF) | (((eax >> 8) & 0xF) == 0xF ? (eax >> 12) & 0xF0 : 0), eax & 0xF); break; } edx = DWORD(p + 4); printf("%sFlags:", prefix); if ((edx & 0xBFEFFBFF) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 0; i <= 31; i++) if (flags[i] != NULL && edx & (1 << i)) printf("%s\t%s\n", prefix, flags[i]); } } static void dmi_processor_voltage(u8 code) { /* 7.5.4 */ static const char *voltage[] = { "5.0 V", /* 0 */ "3.3 V", "2.9 V" /* 2 */ }; int i; if (code & 0x80) printf(" %.1f V", (float)(code & 0x7f) / 10); else { for (i = 0; i <= 2; i++) if (code & (1 << i)) printf(" %s", voltage[i]); if (code == 0x00) printf(" Unknown"); } } static void dmi_processor_frequency(const u8 *p) { u16 code = WORD(p); if (code) printf("%u MHz", code); else printf("Unknown"); } /* code is assumed to be a 3-bit value */ static const char *dmi_processor_status(u8 code) { static const char *status[] = { "Unknown", /* 0x00 */ "Enabled", "Disabled By User", "Disabled By BIOS", "Idle", /* 0x04 */ out_of_spec, out_of_spec, "Other" /* 0x07 */ }; return status[code]; } static const char *dmi_processor_upgrade(u8 code) { /* 7.5.5 */ static const char *upgrade[] = { "Other", /* 0x01 */ "Unknown", "Daughter Board", "ZIF Socket", "Replaceable Piggy Back", "None", "LIF Socket", "Slot 1", "Slot 2", "370-pin Socket", "Slot A", "Slot M", "Socket 423", "Socket A (Socket 462)", "Socket 478", "Socket 754", "Socket 940", "Socket 939", "Socket mPGA604", "Socket LGA771", "Socket LGA775", "Socket S1", "Socket AM2", "Socket F (1207)", "Socket LGA1366", "Socket G34", "Socket AM3", "Socket C32", "Socket LGA1156", "Socket LGA1567", "Socket PGA988A", "Socket BGA1288", "Socket rPGA988B", "Socket BGA1023", "Socket BGA1224", "Socket BGA1155", "Socket LGA1356", "Socket LGA2011", "Socket FS1", "Socket FS2", "Socket FM1", "Socket FM2", "Socket LGA2011-3", "Socket LGA1356-3", "Socket LGA1150", "Socket BGA1168", "Socket BGA1234", "Socket BGA1364", "Socket AM4", "Socket LGA1151", "Socket BGA1356", "Socket BGA1440", "Socket BGA1515", "Socket LGA3647-1", "Socket SP3", "Socket SP3r2" /* 0x38 */ }; if (code >= 0x01 && code <= 0x38) return upgrade[code - 0x01]; return out_of_spec; } static void dmi_processor_cache(u16 code, const char *level, u16 ver) { if (code == 0xFFFF) { if (ver >= 0x0203) printf(" Not Provided"); else printf(" No %s Cache", level); } else printf(" 0x%04X", code); } static void dmi_processor_characteristics(u16 code, const char *prefix) { /* 7.5.9 */ static const char *characteristics[] = { "64-bit capable", /* 2 */ "Multi-Core", "Hardware Thread", "Execute Protection", "Enhanced Virtualization", "Power/Performance Control" /* 7 */ }; if ((code & 0x00FC) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 2; i <= 7; i++) if (code & (1 << i)) printf("%s%s\n", prefix, characteristics[i - 2]); } } /* * 7.6 Memory Controller Information (Type 5) */ static const char *dmi_memory_controller_ed_method(u8 code) { /* 7.6.1 */ static const char *method[] = { "Other", /* 0x01 */ "Unknown", "None", "8-bit Parity", "32-bit ECC", "64-bit ECC", "128-bit ECC", "CRC" /* 0x08 */ }; if (code >= 0x01 && code <= 0x08) return method[code - 0x01]; return out_of_spec; } static void dmi_memory_controller_ec_capabilities(u8 code, const char *prefix) { /* 7.6.2 */ static const char *capabilities[] = { "Other", /* 0 */ "Unknown", "None", "Single-bit Error Correcting", "Double-bit Error Correcting", "Error Scrubbing" /* 5 */ }; if ((code & 0x3F) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 0; i <= 5; i++) if (code & (1 << i)) printf("%s%s\n", prefix, capabilities[i]); } } static const char *dmi_memory_controller_interleave(u8 code) { /* 7.6.3 */ static const char *interleave[] = { "Other", /* 0x01 */ "Unknown", "One-way Interleave", "Two-way Interleave", "Four-way Interleave", "Eight-way Interleave", "Sixteen-way Interleave" /* 0x07 */ }; if (code >= 0x01 && code <= 0x07) return interleave[code - 0x01]; return out_of_spec; } static void dmi_memory_controller_speeds(u16 code, const char *prefix) { /* 7.6.4 */ const char *speeds[] = { "Other", /* 0 */ "Unknown", "70 ns", "60 ns", "50 ns" /* 4 */ }; if ((code & 0x001F) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 0; i <= 4; i++) if (code & (1 << i)) printf("%s%s\n", prefix, speeds[i]); } } static void dmi_memory_controller_slots(u8 count, const u8 *p, const char *prefix) { int i; printf("%sAssociated Memory Slots: %u\n", prefix, count); for (i = 0; i < count; i++) printf("%s\t0x%04X\n", prefix, WORD(p + sizeof(u16) * i)); } /* * 7.7 Memory Module Information (Type 6) */ static void dmi_memory_module_types(u16 code, const char *sep) { /* 7.7.1 */ static const char *types[] = { "Other", /* 0 */ "Unknown", "Standard", "FPM", "EDO", "Parity", "ECC", "SIMM", "DIMM", "Burst EDO", "SDRAM" /* 10 */ }; if ((code & 0x07FF) == 0) printf(" None"); else { int i; for (i = 0; i <= 10; i++) if (code & (1 << i)) printf("%s%s", sep, types[i]); } } static void dmi_memory_module_connections(u8 code) { if (code == 0xFF) printf(" None"); else { if ((code & 0xF0) != 0xF0) printf(" %u", code >> 4); if ((code & 0x0F) != 0x0F) printf(" %u", code & 0x0F); } } static void dmi_memory_module_speed(u8 code) { if (code == 0) printf(" Unknown"); else printf(" %u ns", code); } static void dmi_memory_module_size(u8 code) { /* 7.7.2 */ switch (code & 0x7F) { case 0x7D: printf(" Not Determinable"); break; case 0x7E: printf(" Disabled"); break; case 0x7F: printf(" Not Installed"); return; default: printf(" %u MB", 1 << (code & 0x7F)); } if (code & 0x80) printf(" (Double-bank Connection)"); else printf(" (Single-bank Connection)"); } static void dmi_memory_module_error(u8 code, const char *prefix) { if (code & (1 << 2)) printf(" See Event Log\n"); else { if ((code & 0x03) == 0) printf(" OK\n"); if (code & (1 << 0)) printf("%sUncorrectable Errors\n", prefix); if (code & (1 << 1)) printf("%sCorrectable Errors\n", prefix); } } /* * 7.8 Cache Information (Type 7) */ static const char *dmi_cache_mode(u8 code) { static const char *mode[] = { "Write Through", /* 0x00 */ "Write Back", "Varies With Memory Address", "Unknown" /* 0x03 */ }; return mode[code]; } /* code is assumed to be a 2-bit value */ static const char *dmi_cache_location(u8 code) { static const char *location[4] = { "Internal", /* 0x00 */ "External", out_of_spec, /* 0x02 */ "Unknown" /* 0x03 */ }; return location[code]; } static void dmi_cache_size(u16 code) { if (code & 0x8000) printf(" %u kB", (code & 0x7FFF) << 6); else printf(" %u kB", code); } static void dmi_cache_size_2(u32 code) { if (code & 0x80000000) { code &= 0x7FFFFFFFLU; /* Use a more convenient unit for large cache size */ if (code >= 0x8000) printf(" %u MB", code >> 4); else printf(" %u kB", code << 6); } else printf(" %u kB", code); } static void dmi_cache_types(u16 code, const char *sep) { /* 7.8.2 */ static const char *types[] = { "Other", /* 0 */ "Unknown", "Non-burst", "Burst", "Pipeline Burst", "Synchronous", "Asynchronous" /* 6 */ }; if ((code & 0x007F) == 0) printf(" None"); else { int i; for (i = 0; i <= 6; i++) if (code & (1 << i)) printf("%s%s", sep, types[i]); } } static const char *dmi_cache_ec_type(u8 code) { /* 7.8.3 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "None", "Parity", "Single-bit ECC", "Multi-bit ECC" /* 0x06 */ }; if (code >= 0x01 && code <= 0x06) return type[code - 0x01]; return out_of_spec; } static const char *dmi_cache_type(u8 code) { /* 7.8.4 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Instruction", "Data", "Unified" /* 0x05 */ }; if (code >= 0x01 && code <= 0x05) return type[code - 0x01]; return out_of_spec; } static const char *dmi_cache_associativity(u8 code) { /* 7.8.5 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Direct Mapped", "2-way Set-associative", "4-way Set-associative", "Fully Associative", "8-way Set-associative", "16-way Set-associative", "12-way Set-associative", "24-way Set-associative", "32-way Set-associative", "48-way Set-associative", "64-way Set-associative", "20-way Set-associative" /* 0x0E */ }; if (code >= 0x01 && code <= 0x0E) return type[code - 0x01]; return out_of_spec; } /* * 7.9 Port Connector Information (Type 8) */ static const char *dmi_port_connector_type(u8 code) { /* 7.9.2 */ static const char *type[] = { "None", /* 0x00 */ "Centronics", "Mini Centronics", "Proprietary", "DB-25 male", "DB-25 female", "DB-15 male", "DB-15 female", "DB-9 male", "DB-9 female", "RJ-11", "RJ-45", "50 Pin MiniSCSI", "Mini DIN", "Micro DIN", "PS/2", "Infrared", "HP-HIL", "Access Bus (USB)", "SSA SCSI", "Circular DIN-8 male", "Circular DIN-8 female", "On Board IDE", "On Board Floppy", "9 Pin Dual Inline (pin 10 cut)", "25 Pin Dual Inline (pin 26 cut)", "50 Pin Dual Inline", "68 Pin Dual Inline", "On Board Sound Input From CD-ROM", "Mini Centronics Type-14", "Mini Centronics Type-26", "Mini Jack (headphones)", "BNC", "IEEE 1394", "SAS/SATA Plug Receptacle" /* 0x22 */ }; static const char *type_0xA0[] = { "PC-98", /* 0xA0 */ "PC-98 Hireso", "PC-H98", "PC-98 Note", "PC-98 Full" /* 0xA4 */ }; if (code <= 0x22) return type[code]; if (code >= 0xA0 && code <= 0xA4) return type_0xA0[code - 0xA0]; if (code == 0xFF) return "Other"; return out_of_spec; } static const char *dmi_port_type(u8 code) { /* 7.9.3 */ static const char *type[] = { "None", /* 0x00 */ "Parallel Port XT/AT Compatible", "Parallel Port PS/2", "Parallel Port ECP", "Parallel Port EPP", "Parallel Port ECP/EPP", "Serial Port XT/AT Compatible", "Serial Port 16450 Compatible", "Serial Port 16550 Compatible", "Serial Port 16550A Compatible", "SCSI Port", "MIDI Port", "Joystick Port", "Keyboard Port", "Mouse Port", "SSA SCSI", "USB", "Firewire (IEEE P1394)", "PCMCIA Type I", "PCMCIA Type II", "PCMCIA Type III", "Cardbus", "Access Bus Port", "SCSI II", "SCSI Wide", "PC-98", "PC-98 Hireso", "PC-H98", "Video Port", "Audio Port", "Modem Port", "Network Port", "SATA", "SAS" /* 0x21 */ }; static const char *type_0xA0[] = { "8251 Compatible", /* 0xA0 */ "8251 FIFO Compatible" /* 0xA1 */ }; if (code <= 0x21) return type[code]; if (code >= 0xA0 && code <= 0xA1) return type_0xA0[code - 0xA0]; if (code == 0xFF) return "Other"; return out_of_spec; } /* * 7.10 System Slots (Type 9) */ static const char *dmi_slot_type(u8 code) { /* 7.10.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "ISA", "MCA", "EISA", "PCI", "PC Card (PCMCIA)", "VLB", "Proprietary", "Processor Card", "Proprietary Memory Card", "I/O Riser Card", "NuBus", "PCI-66", "AGP", "AGP 2x", "AGP 4x", "PCI-X", "AGP 8x", "M.2 Socket 1-DP", "M.2 Socket 1-SD", "M.2 Socket 2", "M.2 Socket 3", "MXM Type I", "MXM Type II", "MXM Type III", "MXM Type III-HE", "MXM Type IV", "MXM 3.0 Type A", "MXM 3.0 Type B", "PCI Express 2 SFF-8639", "PCI Express 3 SFF-8639", "PCI Express Mini 52-pin with bottom-side keep-outs", "PCI Express Mini 52-pin without bottom-side keep-outs", "PCI Express Mini 76-pin" /* 0x23 */ }; static const char *type_0xA0[] = { "PC-98/C20", /* 0xA0 */ "PC-98/C24", "PC-98/E", "PC-98/Local Bus", "PC-98/Card", "PCI Express", "PCI Express x1", "PCI Express x2", "PCI Express x4", "PCI Express x8", "PCI Express x16", "PCI Express 2", "PCI Express 2 x1", "PCI Express 2 x2", "PCI Express 2 x4", "PCI Express 2 x8", "PCI Express 2 x16", "PCI Express 3", "PCI Express 3 x1", "PCI Express 3 x2", "PCI Express 3 x4", "PCI Express 3 x8", "PCI Express 3 x16" /* 0xB6 */ }; /* * Note to developers: when adding entries to these lists, check if * function dmi_slot_id below needs updating too. */ if (code >= 0x01 && code <= 0x23) return type[code - 0x01]; if (code >= 0xA0 && code <= 0xB6) return type_0xA0[code - 0xA0]; return out_of_spec; } static const char *dmi_slot_bus_width(u8 code) { /* 7.10.2 */ static const char *width[] = { "", /* 0x01, "Other" */ "", /* "Unknown" */ "8-bit ", "16-bit ", "32-bit ", "64-bit ", "128-bit ", "x1 ", "x2 ", "x4 ", "x8 ", "x12 ", "x16 ", "x32 " /* 0x0E */ }; if (code >= 0x01 && code <= 0x0E) return width[code - 0x01]; return out_of_spec; } static const char *dmi_slot_current_usage(u8 code) { /* 7.10.3 */ static const char *usage[] = { "Other", /* 0x01 */ "Unknown", "Available", "In Use" /* 0x04 */ }; if (code >= 0x01 && code <= 0x04) return usage[code - 0x01]; return out_of_spec; } static const char *dmi_slot_length(u8 code) { /* 7.1O.4 */ static const char *length[] = { "Other", /* 0x01 */ "Unknown", "Short", "Long" /* 0x04 */ }; if (code >= 0x01 && code <= 0x04) return length[code - 0x01]; return out_of_spec; } static void dmi_slot_id(u8 code1, u8 code2, u8 type, const char *prefix) { /* 7.10.5 */ switch (type) { case 0x04: /* MCA */ printf("%sID: %u\n", prefix, code1); break; case 0x05: /* EISA */ printf("%sID: %u\n", prefix, code1); break; case 0x06: /* PCI */ case 0x0E: /* PCI */ case 0x0F: /* AGP */ case 0x10: /* AGP */ case 0x11: /* AGP */ case 0x12: /* PCI-X */ case 0x13: /* AGP */ case 0x1F: /* PCI Express 2 */ case 0x20: /* PCI Express 3 */ case 0x21: /* PCI Express Mini */ case 0x22: /* PCI Express Mini */ case 0x23: /* PCI Express Mini */ case 0xA5: /* PCI Express */ case 0xA6: /* PCI Express */ case 0xA7: /* PCI Express */ case 0xA8: /* PCI Express */ case 0xA9: /* PCI Express */ case 0xAA: /* PCI Express */ case 0xAB: /* PCI Express 2 */ case 0xAC: /* PCI Express 2 */ case 0xAD: /* PCI Express 2 */ case 0xAE: /* PCI Express 2 */ case 0xAF: /* PCI Express 2 */ case 0xB0: /* PCI Express 2 */ case 0xB1: /* PCI Express 3 */ case 0xB2: /* PCI Express 3 */ case 0xB3: /* PCI Express 3 */ case 0xB4: /* PCI Express 3 */ case 0xB5: /* PCI Express 3 */ case 0xB6: /* PCI Express 3 */ printf("%sID: %u\n", prefix, code1); break; case 0x07: /* PCMCIA */ printf("%sID: Adapter %u, Socket %u\n", prefix, code1, code2); break; } } static void dmi_slot_characteristics(u8 code1, u8 code2, const char *prefix) { /* 7.10.6 */ static const char *characteristics1[] = { "5.0 V is provided", /* 1 */ "3.3 V is provided", "Opening is shared", "PC Card-16 is supported", "Cardbus is supported", "Zoom Video is supported", "Modem ring resume is supported" /* 7 */ }; /* 7.10.7 */ static const char *characteristics2[] = { "PME signal is supported", /* 0 */ "Hot-plug devices are supported", "SMBus signal is supported" /* 2 */ }; if (code1 & (1 << 0)) printf(" Unknown\n"); else if ((code1 & 0xFE) == 0 && (code2 & 0x07) == 0) printf(" None\n"); else { int i; printf("\n"); for (i = 1; i <= 7; i++) if (code1 & (1 << i)) printf("%s%s\n", prefix, characteristics1[i - 1]); for (i = 0; i <= 2; i++) if (code2 & (1 << i)) printf("%s%s\n", prefix, characteristics2[i]); } } static void dmi_slot_segment_bus_func(u16 code1, u8 code2, u8 code3, const char *prefix) { /* 7.10.8 */ if (!(code1 == 0xFFFF && code2 == 0xFF && code3 == 0xFF)) printf("%sBus Address: %04x:%02x:%02x.%x\n", prefix, code1, code2, code3 >> 3, code3 & 0x7); } /* * 7.11 On Board Devices Information (Type 10) */ static const char *dmi_on_board_devices_type(u8 code) { /* 7.11.1 and 7.42.2 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Video", "SCSI Controller", "Ethernet", "Token Ring", "Sound", "PATA Controller", "SATA Controller", "SAS Controller" /* 0x0A */ }; if (code >= 0x01 && code <= 0x0A) return type[code - 0x01]; return out_of_spec; } static void dmi_on_board_devices(const struct dmi_header *h, const char *prefix) { u8 *p = h->data + 4; u8 count = (h->length - 0x04) / 2; int i; for (i = 0; i < count; i++) { if (count == 1) printf("%sOn Board Device Information\n", prefix); else printf("%sOn Board Device %d Information\n", prefix, i + 1); printf("%s\tType: %s\n", prefix, dmi_on_board_devices_type(p[2 * i] & 0x7F)); printf("%s\tStatus: %s\n", prefix, p[2 * i] & 0x80 ? "Enabled" : "Disabled"); printf("%s\tDescription: %s\n", prefix, dmi_string(h, p[2 * i + 1])); } } /* * 7.12 OEM Strings (Type 11) */ static void dmi_oem_strings(const struct dmi_header *h, const char *prefix) { u8 *p = h->data + 4; u8 count = p[0x00]; int i; for (i = 1; i <= count; i++) printf("%sString %d: %s\n", prefix, i, dmi_string(h, i)); } /* * 7.13 System Configuration Options (Type 12) */ static void dmi_system_configuration_options(const struct dmi_header *h, const char *prefix) { u8 *p = h->data + 4; u8 count = p[0x00]; int i; for (i = 1; i <= count; i++) printf("%sOption %d: %s\n", prefix, i, dmi_string(h, i)); } /* * 7.14 BIOS Language Information (Type 13) */ static void dmi_bios_languages(const struct dmi_header *h, const char *prefix) { u8 *p = h->data + 4; u8 count = p[0x00]; int i; for (i = 1; i <= count; i++) printf("%s%s\n", prefix, dmi_string(h, i)); } static const char *dmi_bios_language_format(u8 code) { if (code & 0x01) return "Abbreviated"; else return "Long"; } /* * 7.15 Group Associations (Type 14) */ static void dmi_group_associations_items(u8 count, const u8 *p, const char *prefix) { int i; for (i = 0; i < count; i++) { printf("%s0x%04X (%s)\n", prefix, WORD(p + 3 * i + 1), dmi_smbios_structure_type(p[3 * i])); } } /* * 7.16 System Event Log (Type 15) */ static const char *dmi_event_log_method(u8 code) { static const char *method[] = { "Indexed I/O, one 8-bit index port, one 8-bit data port", /* 0x00 */ "Indexed I/O, two 8-bit index ports, one 8-bit data port", "Indexed I/O, one 16-bit index port, one 8-bit data port", "Memory-mapped physical 32-bit address", "General-purpose non-volatile data functions" /* 0x04 */ }; if (code <= 0x04) return method[code]; if (code >= 0x80) return "OEM-specific"; return out_of_spec; } static void dmi_event_log_status(u8 code) { static const char *valid[] = { "Invalid", /* 0 */ "Valid" /* 1 */ }; static const char *full[] = { "Not Full", /* 0 */ "Full" /* 1 */ }; printf(" %s, %s", valid[(code >> 0) & 1], full[(code >> 1) & 1]); } static void dmi_event_log_address(u8 method, const u8 *p) { /* 7.16.3 */ switch (method) { case 0x00: case 0x01: case 0x02: printf(" Index 0x%04X, Data 0x%04X", WORD(p), WORD(p + 2)); break; case 0x03: printf(" 0x%08X", DWORD(p)); break; case 0x04: printf(" 0x%04X", WORD(p)); break; default: printf(" Unknown"); } } static const char *dmi_event_log_header_type(u8 code) { static const char *type[] = { "No Header", /* 0x00 */ "Type 1" /* 0x01 */ }; if (code <= 0x01) return type[code]; if (code >= 0x80) return "OEM-specific"; return out_of_spec; } static const char *dmi_event_log_descriptor_type(u8 code) { /* 7.16.6.1 */ static const char *type[] = { NULL, /* 0x00 */ "Single-bit ECC memory error", "Multi-bit ECC memory error", "Parity memory error", "Bus timeout", "I/O channel block", "Software NMI", "POST memory resize", "POST error", "PCI parity error", "PCI system error", "CPU failure", "EISA failsafe timer timeout", "Correctable memory log disabled", "Logging disabled", NULL, /* 0x0F */ "System limit exceeded", "Asynchronous hardware timer expired", "System configuration information", "Hard disk information", "System reconfigured", "Uncorrectable CPU-complex error", "Log area reset/cleared", "System boot" /* 0x17 */ }; if (code <= 0x17 && type[code] != NULL) return type[code]; if (code >= 0x80 && code <= 0xFE) return "OEM-specific"; if (code == 0xFF) return "End of log"; return out_of_spec; } static const char *dmi_event_log_descriptor_format(u8 code) { /* 7.16.6.2 */ static const char *format[] = { "None", /* 0x00 */ "Handle", "Multiple-event", "Multiple-event handle", "POST results bitmap", "System management", "Multiple-event system management" /* 0x06 */ }; if (code <= 0x06) return format[code]; if (code >= 0x80) return "OEM-specific"; return out_of_spec; } static void dmi_event_log_descriptors(u8 count, u8 len, const u8 *p, const char *prefix) { /* 7.16.1 */ int i; for (i = 0; i < count; i++) { if (len >= 0x02) { printf("%sDescriptor %u: %s\n", prefix, i + 1, dmi_event_log_descriptor_type(p[i * len])); printf("%sData Format %u: %s\n", prefix, i + 1, dmi_event_log_descriptor_format(p[i * len + 1])); } } } /* * 7.17 Physical Memory Array (Type 16) */ static const char *dmi_memory_array_location(u8 code) { /* 7.17.1 */ static const char *location[] = { "Other", /* 0x01 */ "Unknown", "System Board Or Motherboard", "ISA Add-on Card", "EISA Add-on Card", "PCI Add-on Card", "MCA Add-on Card", "PCMCIA Add-on Card", "Proprietary Add-on Card", "NuBus" /* 0x0A */ }; static const char *location_0xA0[] = { "PC-98/C20 Add-on Card", /* 0xA0 */ "PC-98/C24 Add-on Card", "PC-98/E Add-on Card", "PC-98/Local Bus Add-on Card" /* 0xA3 */ }; if (code >= 0x01 && code <= 0x0A) return location[code - 0x01]; if (code >= 0xA0 && code <= 0xA3) return location_0xA0[code - 0xA0]; return out_of_spec; } static const char *dmi_memory_array_use(u8 code) { /* 7.17.2 */ static const char *use[] = { "Other", /* 0x01 */ "Unknown", "System Memory", "Video Memory", "Flash Memory", "Non-volatile RAM", "Cache Memory" /* 0x07 */ }; if (code >= 0x01 && code <= 0x07) return use[code - 0x01]; return out_of_spec; } static const char *dmi_memory_array_ec_type(u8 code) { /* 7.17.3 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "None", "Parity", "Single-bit ECC", "Multi-bit ECC", "CRC" /* 0x07 */ }; if (code >= 0x01 && code <= 0x07) return type[code - 0x01]; return out_of_spec; } static void dmi_memory_array_error_handle(u16 code) { if (code == 0xFFFE) printf(" Not Provided"); else if (code == 0xFFFF) printf(" No Error"); else printf(" 0x%04X", code); } /* * 7.18 Memory Device (Type 17) */ static void dmi_memory_device_width(u16 code) { /* * If no memory module is present, width may be 0 */ if (code == 0xFFFF || code == 0) printf(" Unknown"); else printf(" %u bits", code); } static void dmi_memory_device_size(u16 code) { if (code == 0) printf(" No Module Installed"); else if (code == 0xFFFF) printf(" Unknown"); else { if (code & 0x8000) printf(" %u kB", code & 0x7FFF); else printf(" %u MB", code); } } static void dmi_memory_device_extended_size(u32 code) { code &= 0x7FFFFFFFUL; /* * Use the greatest unit for which the exact value can be displayed * as an integer without rounding */ if (code & 0x3FFUL) printf(" %lu MB", (unsigned long)code); else if (code & 0xFFC00UL) printf(" %lu GB", (unsigned long)code >> 10); else printf(" %lu TB", (unsigned long)code >> 20); } static void dmi_memory_voltage_value(u16 code) { if (code == 0) printf(" Unknown"); else printf(code % 100 ? " %g V" : " %.1f V", (float)code / 1000); } static const char *dmi_memory_device_form_factor(u8 code) { /* 7.18.1 */ static const char *form_factor[] = { "Other", /* 0x01 */ "Unknown", "SIMM", "SIP", "Chip", "DIP", "ZIP", "Proprietary Card", "DIMM", "TSOP", "Row Of Chips", "RIMM", "SODIMM", "SRIMM", "FB-DIMM" /* 0x0F */ }; if (code >= 0x01 && code <= 0x0F) return form_factor[code - 0x01]; return out_of_spec; } static void dmi_memory_device_set(u8 code) { if (code == 0) printf(" None"); else if (code == 0xFF) printf(" Unknown"); else printf(" %u", code); } static const char *dmi_memory_device_type(u8 code) { /* 7.18.2 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "DRAM", "EDRAM", "VRAM", "SRAM", "RAM", "ROM", "Flash", "EEPROM", "FEPROM", "EPROM", "CDRAM", "3DRAM", "SDRAM", "SGRAM", "RDRAM", "DDR", "DDR2", "DDR2 FB-DIMM", "Reserved", "Reserved", "Reserved", "DDR3", "FBD2", "DDR4", "LPDDR", "LPDDR2", "LPDDR3", "LPDDR4" /* 0x1E */ }; if (code >= 0x01 && code <= 0x1E) return type[code - 0x01]; return out_of_spec; } static void dmi_memory_device_type_detail(u16 code) { /* 7.18.3 */ static const char *detail[] = { "Other", /* 1 */ "Unknown", "Fast-paged", "Static Column", "Pseudo-static", "RAMBus", "Synchronous", "CMOS", "EDO", "Window DRAM", "Cache DRAM", "Non-Volatile", "Registered (Buffered)", "Unbuffered (Unregistered)", "LRDIMM" /* 15 */ }; if ((code & 0xFFFE) == 0) printf(" None"); else { int i; for (i = 1; i <= 15; i++) if (code & (1 << i)) printf(" %s", detail[i - 1]); } } static void dmi_memory_device_speed(u16 code) { if (code == 0) printf(" Unknown"); else printf(" %u MT/s", code); } /* * 7.19 32-bit Memory Error Information (Type 18) */ static const char *dmi_memory_error_type(u8 code) { /* 7.19.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "OK", "Bad Read", "Parity Error", "Single-bit Error", "Double-bit Error", "Multi-bit Error", "Nibble Error", "Checksum Error", "CRC Error", "Corrected Single-bit Error", "Corrected Error", "Uncorrectable Error" /* 0x0E */ }; if (code >= 0x01 && code <= 0x0E) return type[code - 0x01]; return out_of_spec; } static const char *dmi_memory_error_granularity(u8 code) { /* 7.19.2 */ static const char *granularity[] = { "Other", /* 0x01 */ "Unknown", "Device Level", "Memory Partition Level" /* 0x04 */ }; if (code >= 0x01 && code <= 0x04) return granularity[code - 0x01]; return out_of_spec; } static const char *dmi_memory_error_operation(u8 code) { /* 7.19.3 */ static const char *operation[] = { "Other", /* 0x01 */ "Unknown", "Read", "Write", "Partial Write" /* 0x05 */ }; if (code >= 0x01 && code <= 0x05) return operation[code - 0x01]; return out_of_spec; } static void dmi_memory_error_syndrome(u32 code) { if (code == 0x00000000) printf(" Unknown"); else printf(" 0x%08X", code); } static void dmi_32bit_memory_error_address(u32 code) { if (code == 0x80000000) printf(" Unknown"); else printf(" 0x%08X", code); } /* * 7.20 Memory Array Mapped Address (Type 19) */ static void dmi_mapped_address_size(u32 code) { if (code == 0) printf(" Invalid"); else { u64 size; size.h = 0; size.l = code; dmi_print_memory_size(size, 1); } } static void dmi_mapped_address_extended_size(u64 start, u64 end) { if (start.h == end.h && start.l == end.l) printf(" Invalid"); else dmi_print_memory_size(u64_range(start, end), 0); } /* * 7.21 Memory Device Mapped Address (Type 20) */ static void dmi_mapped_address_row_position(u8 code) { if (code == 0) printf(" %s", out_of_spec); else if (code == 0xFF) printf(" Unknown"); else printf(" %u", code); } static void dmi_mapped_address_interleave_position(u8 code, const char *prefix) { if (code != 0) { printf("%sInterleave Position:", prefix); if (code == 0xFF) printf(" Unknown"); else printf(" %u", code); printf("\n"); } } static void dmi_mapped_address_interleaved_data_depth(u8 code, const char *prefix) { if (code != 0) { printf("%sInterleaved Data Depth:", prefix); if (code == 0xFF) printf(" Unknown"); else printf(" %u", code); printf("\n"); } } /* * 7.22 Built-in Pointing Device (Type 21) */ static const char *dmi_pointing_device_type(u8 code) { /* 7.22.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Mouse", "Track Ball", "Track Point", "Glide Point", "Touch Pad", "Touch Screen", "Optical Sensor" /* 0x09 */ }; if (code >= 0x01 && code <= 0x09) return type[code - 0x01]; return out_of_spec; } static const char *dmi_pointing_device_interface(u8 code) { /* 7.22.2 */ static const char *interface[] = { "Other", /* 0x01 */ "Unknown", "Serial", "PS/2", "Infrared", "HIP-HIL", "Bus Mouse", "ADB (Apple Desktop Bus)" /* 0x08 */ }; static const char *interface_0xA0[] = { "Bus Mouse DB-9", /* 0xA0 */ "Bus Mouse Micro DIN", "USB" /* 0xA2 */ }; if (code >= 0x01 && code <= 0x08) return interface[code - 0x01]; if (code >= 0xA0 && code <= 0xA2) return interface_0xA0[code - 0xA0]; return out_of_spec; } /* * 7.23 Portable Battery (Type 22) */ static const char *dmi_battery_chemistry(u8 code) { /* 7.23.1 */ static const char *chemistry[] = { "Other", /* 0x01 */ "Unknown", "Lead Acid", "Nickel Cadmium", "Nickel Metal Hydride", "Lithium Ion", "Zinc Air", "Lithium Polymer" /* 0x08 */ }; if (code >= 0x01 && code <= 0x08) return chemistry[code - 0x01]; return out_of_spec; } static void dmi_battery_capacity(u16 code, u8 multiplier) { if (code == 0) printf(" Unknown"); else printf(" %u mWh", code * multiplier); } static void dmi_battery_voltage(u16 code) { if (code == 0) printf(" Unknown"); else printf(" %u mV", code); } static void dmi_battery_maximum_error(u8 code) { if (code == 0xFF) printf(" Unknown"); else printf(" %u%%", code); } /* * 7.24 System Reset (Type 23) */ /* code is assumed to be a 2-bit value */ static const char *dmi_system_reset_boot_option(u8 code) { static const char *option[] = { out_of_spec, /* 0x0 */ "Operating System", /* 0x1 */ "System Utilities", "Do Not Reboot" /* 0x3 */ }; return option[code]; } static void dmi_system_reset_count(u16 code) { if (code == 0xFFFF) printf(" Unknown"); else printf(" %u", code); } static void dmi_system_reset_timer(u16 code) { if (code == 0xFFFF) printf(" Unknown"); else printf(" %u min", code); } /* * 7.25 Hardware Security (Type 24) */ static const char *dmi_hardware_security_status(u8 code) { static const char *status[] = { "Disabled", /* 0x00 */ "Enabled", "Not Implemented", "Unknown" /* 0x03 */ }; return status[code]; } /* * 7.26 System Power Controls (Type 25) */ static void dmi_power_controls_power_on(const u8 *p) { /* 7.26.1 */ if (dmi_bcd_range(p[0], 0x01, 0x12)) printf(" %02X", p[0]); else printf(" *"); if (dmi_bcd_range(p[1], 0x01, 0x31)) printf("-%02X", p[1]); else printf("-*"); if (dmi_bcd_range(p[2], 0x00, 0x23)) printf(" %02X", p[2]); else printf(" *"); if (dmi_bcd_range(p[3], 0x00, 0x59)) printf(":%02X", p[3]); else printf(":*"); if (dmi_bcd_range(p[4], 0x00, 0x59)) printf(":%02X", p[4]); else printf(":*"); } /* * 7.27 Voltage Probe (Type 26) */ static const char *dmi_voltage_probe_location(u8 code) { /* 7.27.1 */ static const char *location[] = { "Other", /* 0x01 */ "Unknown", "Processor", "Disk", "Peripheral Bay", "System Management Module", "Motherboard", "Memory Module", "Processor Module", "Power Unit", "Add-in Card" /* 0x0B */ }; if (code >= 0x01 && code <= 0x0B) return location[code - 0x01]; return out_of_spec; } static const char *dmi_probe_status(u8 code) { /* 7.27.1 */ static const char *status[] = { "Other", /* 0x01 */ "Unknown", "OK", "Non-critical", "Critical", "Non-recoverable" /* 0x06 */ }; if (code >= 0x01 && code <= 0x06) return status[code - 0x01]; return out_of_spec; } static void dmi_voltage_probe_value(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.3f V", (float)(i16)code / 1000); } static void dmi_voltage_probe_resolution(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.1f mV", (float)code / 10); } static void dmi_probe_accuracy(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.2f%%", (float)code / 100); } /* * 7.28 Cooling Device (Type 27) */ static const char *dmi_cooling_device_type(u8 code) { /* 7.28.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Fan", "Centrifugal Blower", "Chip Fan", "Cabinet Fan", "Power Supply Fan", "Heat Pipe", "Integrated Refrigeration" /* 0x09 */ }; static const char *type_0x10[] = { "Active Cooling", /* 0x10 */ "Passive Cooling" /* 0x11 */ }; if (code >= 0x01 && code <= 0x09) return type[code - 0x01]; if (code >= 0x10 && code <= 0x11) return type_0x10[code - 0x10]; return out_of_spec; } static void dmi_cooling_device_speed(u16 code) { if (code == 0x8000) printf(" Unknown Or Non-rotating"); else printf(" %u rpm", code); } /* * 7.29 Temperature Probe (Type 28) */ static const char *dmi_temperature_probe_location(u8 code) { /* 7.29.1 */ static const char *location[] = { "Other", /* 0x01 */ "Unknown", "Processor", "Disk", "Peripheral Bay", "System Management Module", "Motherboard", "Memory Module", "Processor Module", "Power Unit", "Add-in Card", "Front Panel Board", "Back Panel Board", "Power System Board", "Drive Back Plane" /* 0x0F */ }; if (code >= 0x01 && code <= 0x0F) return location[code - 0x01]; return out_of_spec; } static void dmi_temperature_probe_value(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.1f deg C", (float)(i16)code / 10); } static void dmi_temperature_probe_resolution(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.3f deg C", (float)code / 1000); } /* * 7.30 Electrical Current Probe (Type 29) */ static void dmi_current_probe_value(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.3f A", (float)(i16)code / 1000); } static void dmi_current_probe_resolution(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %.1f mA", (float)code / 10); } /* * 7.33 System Boot Information (Type 32) */ static const char *dmi_system_boot_status(u8 code) { static const char *status[] = { "No errors detected", /* 0 */ "No bootable media", "Operating system failed to load", "Firmware-detected hardware failure", "Operating system-detected hardware failure", "User-requested boot", "System security violation", "Previously-requested image", "System watchdog timer expired" /* 8 */ }; if (code <= 8) return status[code]; if (code >= 128 && code <= 191) return "OEM-specific"; if (code >= 192) return "Product-specific"; return out_of_spec; } /* * 7.34 64-bit Memory Error Information (Type 33) */ static void dmi_64bit_memory_error_address(u64 code) { if (code.h == 0x80000000 && code.l == 0x00000000) printf(" Unknown"); else printf(" 0x%08X%08X", code.h, code.l); } /* * 7.35 Management Device (Type 34) */ /* * Several boards have a bug where some type 34 structures have their * length incorrectly set to 0x10 instead of 0x0B. This causes the * first 5 characters of the device name to be trimmed. It's easy to * check and fix, so do it, but warn. */ static void dmi_fixup_type_34(struct dmi_header *h, int display) { u8 *p = h->data; /* Make sure the hidden data is ASCII only */ if (h->length == 0x10 && is_printable(p + 0x0B, 0x10 - 0x0B)) { if (!(opt.flags & FLAG_QUIET) && display) fprintf(stderr, "Invalid entry length (%u). Fixed up to %u.\n", 0x10, 0x0B); h->length = 0x0B; } } static const char *dmi_management_device_type(u8 code) { /* 7.35.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "LM75", "LM78", "LM79", "LM80", "LM81", "ADM9240", "DS1780", "MAX1617", "GL518SM", "W83781D", "HT82H791" /* 0x0D */ }; if (code >= 0x01 && code <= 0x0D) return type[code - 0x01]; return out_of_spec; } static const char *dmi_management_device_address_type(u8 code) { /* 7.35.2 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "I/O Port", "Memory", "SMBus" /* 0x05 */ }; if (code >= 0x01 && code <= 0x05) return type[code - 0x01]; return out_of_spec; } /* * 7.38 Memory Channel (Type 37) */ static const char *dmi_memory_channel_type(u8 code) { /* 7.38.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "RamBus", "SyncLink" /* 0x04 */ }; if (code >= 0x01 && code <= 0x04) return type[code - 0x01]; return out_of_spec; } static void dmi_memory_channel_devices(u8 count, const u8 *p, const char *prefix) { int i; for (i = 1; i <= count; i++) { printf("%sDevice %u Load: %u\n", prefix, i, p[3 * i]); if (!(opt.flags & FLAG_QUIET)) printf("%sDevice %u Handle: 0x%04X\n", prefix, i, WORD(p + 3 * i + 1)); } } /* * 7.39 IPMI Device Information (Type 38) */ static const char *dmi_ipmi_interface_type(u8 code) { /* 7.39.1 and IPMI 2.0, appendix C1, table C1-2 */ static const char *type[] = { "Unknown", /* 0x00 */ "KCS (Keyboard Control Style)", "SMIC (Server Management Interface Chip)", "BT (Block Transfer)", "SSIF (SMBus System Interface)" /* 0x04 */ }; if (code <= 0x04) return type[code]; return out_of_spec; } static void dmi_ipmi_base_address(u8 type, const u8 *p, u8 lsb) { if (type == 0x04) /* SSIF */ { printf("0x%02X (SMBus)", (*p) >> 1); } else { u64 address = QWORD(p); printf("0x%08X%08X (%s)", address.h, (address.l & ~1) | lsb, address.l & 1 ? "I/O" : "Memory-mapped"); } } /* code is assumed to be a 2-bit value */ static const char *dmi_ipmi_register_spacing(u8 code) { /* IPMI 2.0, appendix C1, table C1-1 */ static const char *spacing[] = { "Successive Byte Boundaries", /* 0x00 */ "32-bit Boundaries", "16-byte Boundaries", /* 0x02 */ out_of_spec /* 0x03 */ }; return spacing[code]; } /* * 7.40 System Power Supply (Type 39) */ static void dmi_power_supply_power(u16 code) { if (code == 0x8000) printf(" Unknown"); else printf(" %u W", (unsigned int)code); } static const char *dmi_power_supply_type(u8 code) { /* 7.40.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Linear", "Switching", "Battery", "UPS", "Converter", "Regulator" /* 0x08 */ }; if (code >= 0x01 && code <= 0x08) return type[code - 0x01]; return out_of_spec; } static const char *dmi_power_supply_status(u8 code) { /* 7.40.1 */ static const char *status[] = { "Other", /* 0x01 */ "Unknown", "OK", "Non-critical", "Critical" /* 0x05 */ }; if (code >= 0x01 && code <= 0x05) return status[code - 0x01]; return out_of_spec; } static const char *dmi_power_supply_range_switching(u8 code) { /* 7.40.1 */ static const char *switching[] = { "Other", /* 0x01 */ "Unknown", "Manual", "Auto-switch", "Wide Range", "N/A" /* 0x06 */ }; if (code >= 0x01 && code <= 0x06) return switching[code - 0x01]; return out_of_spec; } /* * 7.41 Additional Information (Type 40) * * Proper support of this entry type would require redesigning a large part of * the code, so I am waiting to see actual implementations of it to decide * whether it's worth the effort. */ static void dmi_additional_info(const struct dmi_header *h, const char *prefix) { u8 *p = h->data + 4; u8 count = *p++; u8 length; int i, offset = 5; for (i = 0; i < count; i++) { printf("%sAdditional Information %d\n", prefix, i + 1); /* Check for short entries */ if (h->length < offset + 1) break; length = p[0x00]; if (length < 0x05 || h->length < offset + length) break; printf("%s\tReferenced Handle: 0x%04x\n", prefix, WORD(p + 0x01)); printf("%s\tReferenced Offset: 0x%02x\n", prefix, p[0x03]); printf("%s\tString: %s\n", prefix, dmi_string(h, p[0x04])); printf("%s\tValue: ", prefix); switch (length - 0x05) { case 1: printf("0x%02x", p[0x05]); break; case 2: printf("0x%04x", WORD(p + 0x05)); break; case 4: printf("0x%08x", DWORD(p + 0x05)); break; default: printf("Unexpected size"); break; } printf("\n"); p += length; offset += length; } } /* * 7.43 Management Controller Host Interface (Type 42) */ static const char *dmi_management_controller_host_type(u8 code) { /* DMTF DSP0239 (MCTP) version 1.1.0 */ static const char *type[] = { "KCS: Keyboard Controller Style", /* 0x02 */ "8250 UART Register Compatible", "16450 UART Register Compatible", "16550/16550A UART Register Compatible", "16650/16650A UART Register Compatible", "16750/16750A UART Register Compatible", "16850/16850A UART Register Compatible" /* 0x08 */ }; if (code >= 0x02 && code <= 0x08) return type[code - 0x02]; if (code == 0xF0) return "OEM"; return out_of_spec; } /* * 7.44 TPM Device (Type 43) */ static void dmi_tpm_vendor_id(const u8 *p) { char vendor_id[5]; int i; /* ASCII filtering */ for (i = 0; i < 4 && p[i] != 0; i++) { if (p[i] < 32 || p[i] >= 127) vendor_id[i] = '.'; else vendor_id[i] = p[i]; } /* Terminate the string */ vendor_id[i] = '\0'; printf(" %s", vendor_id); } static void dmi_tpm_characteristics(u64 code, const char *prefix) { /* 7.1.1 */ static const char *characteristics[] = { "TPM Device characteristics not supported", /* 2 */ "Family configurable via firmware update", "Family configurable via platform software support", "Family configurable via OEM proprietary mechanism" /* 5 */ }; int i; /* * This isn't very clear what this bit is supposed to mean */ if (code.l & (1 << 2)) { printf("%s%s\n", prefix, characteristics[0]); return; } for (i = 3; i <= 5; i++) if (code.l & (1 << i)) printf("%s%s\n", prefix, characteristics[i - 2]); } /* * Main */ static void dmi_decode(const struct dmi_header *h, u16 ver) { const u8 *data = h->data; /* * Note: DMI types 37 and 42 are untested */ switch (h->type) { case 0: /* 7.1 BIOS Information */ printf("BIOS Information\n"); if (h->length < 0x12) break; printf("\tVendor: %s\n", dmi_string(h, data[0x04])); printf("\tVersion: %s\n", dmi_string(h, data[0x05])); printf("\tRelease Date: %s\n", dmi_string(h, data[0x08])); /* * On IA-64, the BIOS base address will read 0 because * there is no BIOS. Skip the base address and the * runtime size in this case. */ if (WORD(data + 0x06) != 0) { printf("\tAddress: 0x%04X0\n", WORD(data + 0x06)); printf("\tRuntime Size:"); dmi_bios_runtime_size((0x10000 - WORD(data + 0x06)) << 4); printf("\n"); } printf("\tROM Size:"); dmi_bios_rom_size(data[0x09], h->length < 0x1A ? 16 : WORD(data + 0x18)); printf("\n"); printf("\tCharacteristics:\n"); dmi_bios_characteristics(QWORD(data + 0x0A), "\t\t"); if (h->length < 0x13) break; dmi_bios_characteristics_x1(data[0x12], "\t\t"); if (h->length < 0x14) break; dmi_bios_characteristics_x2(data[0x13], "\t\t"); if (h->length < 0x18) break; if (data[0x14] != 0xFF && data[0x15] != 0xFF) printf("\tBIOS Revision: %u.%u\n", data[0x14], data[0x15]); if (data[0x16] != 0xFF && data[0x17] != 0xFF) printf("\tFirmware Revision: %u.%u\n", data[0x16], data[0x17]); break; case 1: /* 7.2 System Information */ printf("System Information\n"); if (h->length < 0x08) break; printf("\tManufacturer: %s\n", dmi_string(h, data[0x04])); printf("\tProduct Name: %s\n", dmi_string(h, data[0x05])); printf("\tVersion: %s\n", dmi_string(h, data[0x06])); printf("\tSerial Number: %s\n", dmi_string(h, data[0x07])); if (h->length < 0x19) break; printf("\tUUID: "); dmi_system_uuid(data + 0x08, ver); printf("\n"); printf("\tWake-up Type: %s\n", dmi_system_wake_up_type(data[0x18])); if (h->length < 0x1B) break; printf("\tSKU Number: %s\n", dmi_string(h, data[0x19])); printf("\tFamily: %s\n", dmi_string(h, data[0x1A])); break; case 2: /* 7.3 Base Board Information */ printf("Base Board Information\n"); if (h->length < 0x08) break; printf("\tManufacturer: %s\n", dmi_string(h, data[0x04])); printf("\tProduct Name: %s\n", dmi_string(h, data[0x05])); printf("\tVersion: %s\n", dmi_string(h, data[0x06])); printf("\tSerial Number: %s\n", dmi_string(h, data[0x07])); if (h->length < 0x09) break; printf("\tAsset Tag: %s\n", dmi_string(h, data[0x08])); if (h->length < 0x0A) break; printf("\tFeatures:"); dmi_base_board_features(data[0x09], "\t\t"); if (h->length < 0x0E) break; printf("\tLocation In Chassis: %s\n", dmi_string(h, data[0x0A])); if (!(opt.flags & FLAG_QUIET)) printf("\tChassis Handle: 0x%04X\n", WORD(data + 0x0B)); printf("\tType: %s\n", dmi_base_board_type(data[0x0D])); if (h->length < 0x0F) break; if (h->length < 0x0F + data[0x0E] * sizeof(u16)) break; if (!(opt.flags & FLAG_QUIET)) dmi_base_board_handles(data[0x0E], data + 0x0F, "\t"); break; case 3: /* 7.4 Chassis Information */ printf("Chassis Information\n"); if (h->length < 0x09) break; printf("\tManufacturer: %s\n", dmi_string(h, data[0x04])); printf("\tType: %s\n", dmi_chassis_type(data[0x05])); printf("\tLock: %s\n", dmi_chassis_lock(data[0x05] >> 7)); printf("\tVersion: %s\n", dmi_string(h, data[0x06])); printf("\tSerial Number: %s\n", dmi_string(h, data[0x07])); printf("\tAsset Tag: %s\n", dmi_string(h, data[0x08])); if (h->length < 0x0D) break; printf("\tBoot-up State: %s\n", dmi_chassis_state(data[0x09])); printf("\tPower Supply State: %s\n", dmi_chassis_state(data[0x0A])); printf("\tThermal State: %s\n", dmi_chassis_state(data[0x0B])); printf("\tSecurity Status: %s\n", dmi_chassis_security_status(data[0x0C])); if (h->length < 0x11) break; printf("\tOEM Information: 0x%08X\n", DWORD(data + 0x0D)); if (h->length < 0x13) break; printf("\tHeight:"); dmi_chassis_height(data[0x11]); printf("\n"); printf("\tNumber Of Power Cords:"); dmi_chassis_power_cords(data[0x12]); printf("\n"); if (h->length < 0x15) break; if (h->length < 0x15 + data[0x13] * data[0x14]) break; dmi_chassis_elements(data[0x13], data[0x14], data + 0x15, "\t"); if (h->length < 0x16 + data[0x13] * data[0x14]) break; printf("\tSKU Number: %s\n", dmi_string(h, data[0x15 + data[0x13] * data[0x14]])); break; case 4: /* 7.5 Processor Information */ printf("Processor Information\n"); if (h->length < 0x1A) break; printf("\tSocket Designation: %s\n", dmi_string(h, data[0x04])); printf("\tType: %s\n", dmi_processor_type(data[0x05])); printf("\tFamily: %s\n", dmi_processor_family(h, ver)); printf("\tManufacturer: %s\n", dmi_string(h, data[0x07])); dmi_processor_id(h, "\t"); printf("\tVersion: %s\n", dmi_string(h, data[0x10])); printf("\tVoltage:"); dmi_processor_voltage(data[0x11]); printf("\n"); printf("\tExternal Clock: "); dmi_processor_frequency(data + 0x12); printf("\n"); printf("\tMax Speed: "); dmi_processor_frequency(data + 0x14); printf("\n"); printf("\tCurrent Speed: "); dmi_processor_frequency(data + 0x16); printf("\n"); if (data[0x18] & (1 << 6)) printf("\tStatus: Populated, %s\n", dmi_processor_status(data[0x18] & 0x07)); else printf("\tStatus: Unpopulated\n"); printf("\tUpgrade: %s\n", dmi_processor_upgrade(data[0x19])); if (h->length < 0x20) break; if (!(opt.flags & FLAG_QUIET)) { printf("\tL1 Cache Handle:"); dmi_processor_cache(WORD(data + 0x1A), "L1", ver); printf("\n"); printf("\tL2 Cache Handle:"); dmi_processor_cache(WORD(data + 0x1C), "L2", ver); printf("\n"); printf("\tL3 Cache Handle:"); dmi_processor_cache(WORD(data + 0x1E), "L3", ver); printf("\n"); } if (h->length < 0x23) break; printf("\tSerial Number: %s\n", dmi_string(h, data[0x20])); printf("\tAsset Tag: %s\n", dmi_string(h, data[0x21])); printf("\tPart Number: %s\n", dmi_string(h, data[0x22])); if (h->length < 0x28) break; if (data[0x23] != 0) printf("\tCore Count: %u\n", h->length >= 0x2C && data[0x23] == 0xFF ? WORD(data + 0x2A) : data[0x23]); if (data[0x24] != 0) printf("\tCore Enabled: %u\n", h->length >= 0x2E && data[0x24] == 0xFF ? WORD(data + 0x2C) : data[0x24]); if (data[0x25] != 0) printf("\tThread Count: %u\n", h->length >= 0x30 && data[0x25] == 0xFF ? WORD(data + 0x2E) : data[0x25]); printf("\tCharacteristics:"); dmi_processor_characteristics(WORD(data + 0x26), "\t\t"); break; case 5: /* 7.6 Memory Controller Information */ printf("Memory Controller Information\n"); if (h->length < 0x0F) break; printf("\tError Detecting Method: %s\n", dmi_memory_controller_ed_method(data[0x04])); printf("\tError Correcting Capabilities:"); dmi_memory_controller_ec_capabilities(data[0x05], "\t\t"); printf("\tSupported Interleave: %s\n", dmi_memory_controller_interleave(data[0x06])); printf("\tCurrent Interleave: %s\n", dmi_memory_controller_interleave(data[0x07])); printf("\tMaximum Memory Module Size: %u MB\n", 1 << data[0x08]); printf("\tMaximum Total Memory Size: %u MB\n", data[0x0E] * (1 << data[0x08])); printf("\tSupported Speeds:"); dmi_memory_controller_speeds(WORD(data + 0x09), "\t\t"); printf("\tSupported Memory Types:"); dmi_memory_module_types(WORD(data + 0x0B), "\n\t\t"); printf("\n"); printf("\tMemory Module Voltage:"); dmi_processor_voltage(data[0x0D]); printf("\n"); if (h->length < 0x0F + data[0x0E] * sizeof(u16)) break; dmi_memory_controller_slots(data[0x0E], data + 0x0F, "\t"); if (h->length < 0x10 + data[0x0E] * sizeof(u16)) break; printf("\tEnabled Error Correcting Capabilities:"); dmi_memory_controller_ec_capabilities(data[0x0F + data[0x0E] * sizeof(u16)], "\t\t"); break; case 6: /* 7.7 Memory Module Information */ printf("Memory Module Information\n"); if (h->length < 0x0C) break; printf("\tSocket Designation: %s\n", dmi_string(h, data[0x04])); printf("\tBank Connections:"); dmi_memory_module_connections(data[0x05]); printf("\n"); printf("\tCurrent Speed:"); dmi_memory_module_speed(data[0x06]); printf("\n"); printf("\tType:"); dmi_memory_module_types(WORD(data + 0x07), " "); printf("\n"); printf("\tInstalled Size:"); dmi_memory_module_size(data[0x09]); printf("\n"); printf("\tEnabled Size:"); dmi_memory_module_size(data[0x0A]); printf("\n"); printf("\tError Status:"); dmi_memory_module_error(data[0x0B], "\t\t"); break; case 7: /* 7.8 Cache Information */ printf("Cache Information\n"); if (h->length < 0x0F) break; printf("\tSocket Designation: %s\n", dmi_string(h, data[0x04])); printf("\tConfiguration: %s, %s, Level %u\n", WORD(data + 0x05) & 0x0080 ? "Enabled" : "Disabled", WORD(data + 0x05) & 0x0008 ? "Socketed" : "Not Socketed", (WORD(data + 0x05) & 0x0007) + 1); printf("\tOperational Mode: %s\n", dmi_cache_mode((WORD(data + 0x05) >> 8) & 0x0003)); printf("\tLocation: %s\n", dmi_cache_location((WORD(data + 0x05) >> 5) & 0x0003)); printf("\tInstalled Size:"); if (h->length >= 0x1B) dmi_cache_size_2(DWORD(data + 0x17)); else dmi_cache_size(WORD(data + 0x09)); printf("\n"); printf("\tMaximum Size:"); if (h->length >= 0x17) dmi_cache_size_2(DWORD(data + 0x13)); else dmi_cache_size(WORD(data + 0x07)); printf("\n"); printf("\tSupported SRAM Types:"); dmi_cache_types(WORD(data + 0x0B), "\n\t\t"); printf("\n"); printf("\tInstalled SRAM Type:"); dmi_cache_types(WORD(data + 0x0D), " "); printf("\n"); if (h->length < 0x13) break; printf("\tSpeed:"); dmi_memory_module_speed(data[0x0F]); printf("\n"); printf("\tError Correction Type: %s\n", dmi_cache_ec_type(data[0x10])); printf("\tSystem Type: %s\n", dmi_cache_type(data[0x11])); printf("\tAssociativity: %s\n", dmi_cache_associativity(data[0x12])); break; case 8: /* 7.9 Port Connector Information */ printf("Port Connector Information\n"); if (h->length < 0x09) break; printf("\tInternal Reference Designator: %s\n", dmi_string(h, data[0x04])); printf("\tInternal Connector Type: %s\n", dmi_port_connector_type(data[0x05])); printf("\tExternal Reference Designator: %s\n", dmi_string(h, data[0x06])); printf("\tExternal Connector Type: %s\n", dmi_port_connector_type(data[0x07])); printf("\tPort Type: %s\n", dmi_port_type(data[0x08])); break; case 9: /* 7.10 System Slots */ printf("System Slot Information\n"); if (h->length < 0x0C) break; printf("\tDesignation: %s\n", dmi_string(h, data[0x04])); printf("\tType: %s%s\n", dmi_slot_bus_width(data[0x06]), dmi_slot_type(data[0x05])); printf("\tCurrent Usage: %s\n", dmi_slot_current_usage(data[0x07])); printf("\tLength: %s\n", dmi_slot_length(data[0x08])); dmi_slot_id(data[0x09], data[0x0A], data[0x05], "\t"); printf("\tCharacteristics:"); if (h->length < 0x0D) dmi_slot_characteristics(data[0x0B], 0x00, "\t\t"); else dmi_slot_characteristics(data[0x0B], data[0x0C], "\t\t"); if (h->length < 0x11) break; dmi_slot_segment_bus_func(WORD(data + 0x0D), data[0x0F], data[0x10], "\t"); break; case 10: /* 7.11 On Board Devices Information */ dmi_on_board_devices(h, ""); break; case 11: /* 7.12 OEM Strings */ printf("OEM Strings\n"); if (h->length < 0x05) break; dmi_oem_strings(h, "\t"); break; case 12: /* 7.13 System Configuration Options */ printf("System Configuration Options\n"); if (h->length < 0x05) break; dmi_system_configuration_options(h, "\t"); break; case 13: /* 7.14 BIOS Language Information */ printf("BIOS Language Information\n"); if (h->length < 0x16) break; if (ver >= 0x0201) { printf("\tLanguage Description Format: %s\n", dmi_bios_language_format(data[0x05])); } printf("\tInstallable Languages: %u\n", data[0x04]); dmi_bios_languages(h, "\t\t"); printf("\tCurrently Installed Language: %s\n", dmi_string(h, data[0x15])); break; case 14: /* 7.15 Group Associations */ printf("Group Associations\n"); if (h->length < 0x05) break; printf("\tName: %s\n", dmi_string(h, data[0x04])); printf("\tItems: %u\n", (h->length - 0x05) / 3); dmi_group_associations_items((h->length - 0x05) / 3, data + 0x05, "\t\t"); break; case 15: /* 7.16 System Event Log */ printf("System Event Log\n"); if (h->length < 0x14) break; printf("\tArea Length: %u bytes\n", WORD(data + 0x04)); printf("\tHeader Start Offset: 0x%04X\n", WORD(data + 0x06)); if (WORD(data + 0x08) - WORD(data + 0x06)) printf("\tHeader Length: %u byte%s\n", WORD(data + 0x08) - WORD(data + 0x06), WORD(data + 0x08) - WORD(data + 0x06) > 1 ? "s" : ""); printf("\tData Start Offset: 0x%04X\n", WORD(data + 0x08)); printf("\tAccess Method: %s\n", dmi_event_log_method(data[0x0A])); printf("\tAccess Address:"); dmi_event_log_address(data[0x0A], data + 0x10); printf("\n"); printf("\tStatus:"); dmi_event_log_status(data[0x0B]); printf("\n"); printf("\tChange Token: 0x%08X\n", DWORD(data + 0x0C)); if (h->length < 0x17) break; printf("\tHeader Format: %s\n", dmi_event_log_header_type(data[0x14])); printf("\tSupported Log Type Descriptors: %u\n", data[0x15]); if (h->length < 0x17 + data[0x15] * data[0x16]) break; dmi_event_log_descriptors(data[0x15], data[0x16], data + 0x17, "\t"); break; case 16: /* 7.17 Physical Memory Array */ printf("Physical Memory Array\n"); if (h->length < 0x0F) break; printf("\tLocation: %s\n", dmi_memory_array_location(data[0x04])); printf("\tUse: %s\n", dmi_memory_array_use(data[0x05])); printf("\tError Correction Type: %s\n", dmi_memory_array_ec_type(data[0x06])); printf("\tMaximum Capacity:"); if (DWORD(data + 0x07) == 0x80000000) { if (h->length < 0x17) printf(" Unknown"); else dmi_print_memory_size(QWORD(data + 0x0F), 0); } else { u64 capacity; capacity.h = 0; capacity.l = DWORD(data + 0x07); dmi_print_memory_size(capacity, 1); } printf("\n"); if (!(opt.flags & FLAG_QUIET)) { printf("\tError Information Handle:"); dmi_memory_array_error_handle(WORD(data + 0x0B)); printf("\n"); } printf("\tNumber Of Devices: %u\n", WORD(data + 0x0D)); break; case 17: /* 7.18 Memory Device */ printf("Memory Device\n"); if (h->length < 0x15) break; if (!(opt.flags & FLAG_QUIET)) { printf("\tArray Handle: 0x%04X\n", WORD(data + 0x04)); printf("\tError Information Handle:"); dmi_memory_array_error_handle(WORD(data + 0x06)); printf("\n"); } printf("\tTotal Width:"); dmi_memory_device_width(WORD(data + 0x08)); printf("\n"); printf("\tData Width:"); dmi_memory_device_width(WORD(data + 0x0A)); printf("\n"); printf("\tSize:"); if (h->length >= 0x20 && WORD(data + 0x0C) == 0x7FFF) dmi_memory_device_extended_size(DWORD(data + 0x1C)); else dmi_memory_device_size(WORD(data + 0x0C)); printf("\n"); printf("\tForm Factor: %s\n", dmi_memory_device_form_factor(data[0x0E])); printf("\tSet:"); dmi_memory_device_set(data[0x0F]); printf("\n"); printf("\tLocator: %s\n", dmi_string(h, data[0x10])); printf("\tBank Locator: %s\n", dmi_string(h, data[0x11])); printf("\tType: %s\n", dmi_memory_device_type(data[0x12])); printf("\tType Detail:"); dmi_memory_device_type_detail(WORD(data + 0x13)); printf("\n"); if (h->length < 0x17) break; printf("\tSpeed:"); dmi_memory_device_speed(WORD(data + 0x15)); printf("\n"); if (h->length < 0x1B) break; printf("\tManufacturer: %s\n", dmi_string(h, data[0x17])); printf("\tSerial Number: %s\n", dmi_string(h, data[0x18])); printf("\tAsset Tag: %s\n", dmi_string(h, data[0x19])); printf("\tPart Number: %s\n", dmi_string(h, data[0x1A])); if (h->length < 0x1C) break; printf("\tRank: "); if ((data[0x1B] & 0x0F) == 0) printf("Unknown"); else printf("%u", data[0x1B] & 0x0F); printf("\n"); if (h->length < 0x22) break; printf("\tConfigured Clock Speed:"); dmi_memory_device_speed(WORD(data + 0x20)); printf("\n"); if (h->length < 0x28) break; printf("\tMinimum Voltage:"); dmi_memory_voltage_value(WORD(data + 0x22)); printf("\n"); printf("\tMaximum Voltage:"); dmi_memory_voltage_value(WORD(data + 0x24)); printf("\n"); printf("\tConfigured Voltage:"); dmi_memory_voltage_value(WORD(data + 0x26)); printf("\n"); break; case 18: /* 7.19 32-bit Memory Error Information */ printf("32-bit Memory Error Information\n"); if (h->length < 0x17) break; printf("\tType: %s\n", dmi_memory_error_type(data[0x04])); printf("\tGranularity: %s\n", dmi_memory_error_granularity(data[0x05])); printf("\tOperation: %s\n", dmi_memory_error_operation(data[0x06])); printf("\tVendor Syndrome:"); dmi_memory_error_syndrome(DWORD(data + 0x07)); printf("\n"); printf("\tMemory Array Address:"); dmi_32bit_memory_error_address(DWORD(data + 0x0B)); printf("\n"); printf("\tDevice Address:"); dmi_32bit_memory_error_address(DWORD(data + 0x0F)); printf("\n"); printf("\tResolution:"); dmi_32bit_memory_error_address(DWORD(data + 0x13)); printf("\n"); break; case 19: /* 7.20 Memory Array Mapped Address */ printf("Memory Array Mapped Address\n"); if (h->length < 0x0F) break; if (h->length >= 0x1F && DWORD(data + 0x04) == 0xFFFFFFFF) { u64 start, end; start = QWORD(data + 0x0F); end = QWORD(data + 0x17); printf("\tStarting Address: 0x%08X%08Xk\n", start.h, start.l); printf("\tEnding Address: 0x%08X%08Xk\n", end.h, end.l); printf("\tRange Size:"); dmi_mapped_address_extended_size(start, end); } else { printf("\tStarting Address: 0x%08X%03X\n", DWORD(data + 0x04) >> 2, (DWORD(data + 0x04) & 0x3) << 10); printf("\tEnding Address: 0x%08X%03X\n", DWORD(data + 0x08) >> 2, ((DWORD(data + 0x08) & 0x3) << 10) + 0x3FF); printf("\tRange Size:"); dmi_mapped_address_size(DWORD(data + 0x08) - DWORD(data + 0x04) + 1); } printf("\n"); if (!(opt.flags & FLAG_QUIET)) printf("\tPhysical Array Handle: 0x%04X\n", WORD(data + 0x0C)); printf("\tPartition Width: %u\n", data[0x0E]); break; case 20: /* 7.21 Memory Device Mapped Address */ printf("Memory Device Mapped Address\n"); if (h->length < 0x13) break; if (h->length >= 0x23 && DWORD(data + 0x04) == 0xFFFFFFFF) { u64 start, end; start = QWORD(data + 0x13); end = QWORD(data + 0x1B); printf("\tStarting Address: 0x%08X%08Xk\n", start.h, start.l); printf("\tEnding Address: 0x%08X%08Xk\n", end.h, end.l); printf("\tRange Size:"); dmi_mapped_address_extended_size(start, end); } else { printf("\tStarting Address: 0x%08X%03X\n", DWORD(data + 0x04) >> 2, (DWORD(data + 0x04) & 0x3) << 10); printf("\tEnding Address: 0x%08X%03X\n", DWORD(data + 0x08) >> 2, ((DWORD(data + 0x08) & 0x3) << 10) + 0x3FF); printf("\tRange Size:"); dmi_mapped_address_size(DWORD(data + 0x08) - DWORD(data + 0x04) + 1); } printf("\n"); if (!(opt.flags & FLAG_QUIET)) { printf("\tPhysical Device Handle: 0x%04X\n", WORD(data + 0x0C)); printf("\tMemory Array Mapped Address Handle: 0x%04X\n", WORD(data + 0x0E)); } printf("\tPartition Row Position:"); dmi_mapped_address_row_position(data[0x10]); printf("\n"); dmi_mapped_address_interleave_position(data[0x11], "\t"); dmi_mapped_address_interleaved_data_depth(data[0x12], "\t"); break; case 21: /* 7.22 Built-in Pointing Device */ printf("Built-in Pointing Device\n"); if (h->length < 0x07) break; printf("\tType: %s\n", dmi_pointing_device_type(data[0x04])); printf("\tInterface: %s\n", dmi_pointing_device_interface(data[0x05])); printf("\tButtons: %u\n", data[0x06]); break; case 22: /* 7.23 Portable Battery */ printf("Portable Battery\n"); if (h->length < 0x10) break; printf("\tLocation: %s\n", dmi_string(h, data[0x04])); printf("\tManufacturer: %s\n", dmi_string(h, data[0x05])); if (data[0x06] || h->length < 0x1A) printf("\tManufacture Date: %s\n", dmi_string(h, data[0x06])); if (data[0x07] || h->length < 0x1A) printf("\tSerial Number: %s\n", dmi_string(h, data[0x07])); printf("\tName: %s\n", dmi_string(h, data[0x08])); if (data[0x09] != 0x02 || h->length < 0x1A) printf("\tChemistry: %s\n", dmi_battery_chemistry(data[0x09])); printf("\tDesign Capacity:"); if (h->length < 0x16) dmi_battery_capacity(WORD(data + 0x0A), 1); else dmi_battery_capacity(WORD(data + 0x0A), data[0x15]); printf("\n"); printf("\tDesign Voltage:"); dmi_battery_voltage(WORD(data + 0x0C)); printf("\n"); printf("\tSBDS Version: %s\n", dmi_string(h, data[0x0E])); printf("\tMaximum Error:"); dmi_battery_maximum_error(data[0x0F]); printf("\n"); if (h->length < 0x1A) break; if (data[0x07] == 0) printf("\tSBDS Serial Number: %04X\n", WORD(data + 0x10)); if (data[0x06] == 0) printf("\tSBDS Manufacture Date: %u-%02u-%02u\n", 1980 + (WORD(data + 0x12) >> 9), (WORD(data + 0x12) >> 5) & 0x0F, WORD(data + 0x12) & 0x1F); if (data[0x09] == 0x02) printf("\tSBDS Chemistry: %s\n", dmi_string(h, data[0x14])); printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x16)); break; case 23: /* 7.24 System Reset */ printf("System Reset\n"); if (h->length < 0x0D) break; printf("\tStatus: %s\n", data[0x04] & (1 << 0) ? "Enabled" : "Disabled"); printf("\tWatchdog Timer: %s\n", data[0x04] & (1 << 5) ? "Present" : "Not Present"); if (!(data[0x04] & (1 << 5))) break; printf("\tBoot Option: %s\n", dmi_system_reset_boot_option((data[0x04] >> 1) & 0x3)); printf("\tBoot Option On Limit: %s\n", dmi_system_reset_boot_option((data[0x04] >> 3) & 0x3)); printf("\tReset Count:"); dmi_system_reset_count(WORD(data + 0x05)); printf("\n"); printf("\tReset Limit:"); dmi_system_reset_count(WORD(data + 0x07)); printf("\n"); printf("\tTimer Interval:"); dmi_system_reset_timer(WORD(data + 0x09)); printf("\n"); printf("\tTimeout:"); dmi_system_reset_timer(WORD(data + 0x0B)); printf("\n"); break; case 24: /* 7.25 Hardware Security */ printf("Hardware Security\n"); if (h->length < 0x05) break; printf("\tPower-On Password Status: %s\n", dmi_hardware_security_status(data[0x04] >> 6)); printf("\tKeyboard Password Status: %s\n", dmi_hardware_security_status((data[0x04] >> 4) & 0x3)); printf("\tAdministrator Password Status: %s\n", dmi_hardware_security_status((data[0x04] >> 2) & 0x3)); printf("\tFront Panel Reset Status: %s\n", dmi_hardware_security_status(data[0x04] & 0x3)); break; case 25: /* 7.26 System Power Controls */ printf("\tSystem Power Controls\n"); if (h->length < 0x09) break; printf("\tNext Scheduled Power-on:"); dmi_power_controls_power_on(data + 0x04); printf("\n"); break; case 26: /* 7.27 Voltage Probe */ printf("Voltage Probe\n"); if (h->length < 0x14) break; printf("\tDescription: %s\n", dmi_string(h, data[0x04])); printf("\tLocation: %s\n", dmi_voltage_probe_location(data[0x05] & 0x1f)); printf("\tStatus: %s\n", dmi_probe_status(data[0x05] >> 5)); printf("\tMaximum Value:"); dmi_voltage_probe_value(WORD(data + 0x06)); printf("\n"); printf("\tMinimum Value:"); dmi_voltage_probe_value(WORD(data + 0x08)); printf("\n"); printf("\tResolution:"); dmi_voltage_probe_resolution(WORD(data + 0x0A)); printf("\n"); printf("\tTolerance:"); dmi_voltage_probe_value(WORD(data + 0x0C)); printf("\n"); printf("\tAccuracy:"); dmi_probe_accuracy(WORD(data + 0x0E)); printf("\n"); printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x10)); if (h->length < 0x16) break; printf("\tNominal Value:"); dmi_voltage_probe_value(WORD(data + 0x14)); printf("\n"); break; case 27: /* 7.28 Cooling Device */ printf("Cooling Device\n"); if (h->length < 0x0C) break; if (!(opt.flags & FLAG_QUIET) && WORD(data + 0x04) != 0xFFFF) printf("\tTemperature Probe Handle: 0x%04X\n", WORD(data + 0x04)); printf("\tType: %s\n", dmi_cooling_device_type(data[0x06] & 0x1f)); printf("\tStatus: %s\n", dmi_probe_status(data[0x06] >> 5)); if (data[0x07] != 0x00) printf("\tCooling Unit Group: %u\n", data[0x07]); printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x08)); if (h->length < 0x0E) break; printf("\tNominal Speed:"); dmi_cooling_device_speed(WORD(data + 0x0C)); printf("\n"); if (h->length < 0x0F) break; printf("\tDescription: %s\n", dmi_string(h, data[0x0E])); break; case 28: /* 7.29 Temperature Probe */ printf("Temperature Probe\n"); if (h->length < 0x14) break; printf("\tDescription: %s\n", dmi_string(h, data[0x04])); printf("\tLocation: %s\n", dmi_temperature_probe_location(data[0x05] & 0x1F)); printf("\tStatus: %s\n", dmi_probe_status(data[0x05] >> 5)); printf("\tMaximum Value:"); dmi_temperature_probe_value(WORD(data + 0x06)); printf("\n"); printf("\tMinimum Value:"); dmi_temperature_probe_value(WORD(data + 0x08)); printf("\n"); printf("\tResolution:"); dmi_temperature_probe_resolution(WORD(data + 0x0A)); printf("\n"); printf("\tTolerance:"); dmi_temperature_probe_value(WORD(data + 0x0C)); printf("\n"); printf("\tAccuracy:"); dmi_probe_accuracy(WORD(data + 0x0E)); printf("\n"); printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x10)); if (h->length < 0x16) break; printf("\tNominal Value:"); dmi_temperature_probe_value(WORD(data + 0x14)); printf("\n"); break; case 29: /* 7.30 Electrical Current Probe */ printf("Electrical Current Probe\n"); if (h->length < 0x14) break; printf("\tDescription: %s\n", dmi_string(h, data[0x04])); printf("\tLocation: %s\n", dmi_voltage_probe_location(data[5] & 0x1F)); printf("\tStatus: %s\n", dmi_probe_status(data[0x05] >> 5)); printf("\tMaximum Value:"); dmi_current_probe_value(WORD(data + 0x06)); printf("\n"); printf("\tMinimum Value:"); dmi_current_probe_value(WORD(data + 0x08)); printf("\n"); printf("\tResolution:"); dmi_current_probe_resolution(WORD(data + 0x0A)); printf("\n"); printf("\tTolerance:"); dmi_current_probe_value(WORD(data + 0x0C)); printf("\n"); printf("\tAccuracy:"); dmi_probe_accuracy(WORD(data + 0x0E)); printf("\n"); printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x10)); if (h->length < 0x16) break; printf("\tNominal Value:"); dmi_current_probe_value(WORD(data + 0x14)); printf("\n"); break; case 30: /* 7.31 Out-of-band Remote Access */ printf("Out-of-band Remote Access\n"); if (h->length < 0x06) break; printf("\tManufacturer Name: %s\n", dmi_string(h, data[0x04])); printf("\tInbound Connection: %s\n", data[0x05] & (1 << 0) ? "Enabled" : "Disabled"); printf("\tOutbound Connection: %s\n", data[0x05] & (1 << 1) ? "Enabled" : "Disabled"); break; case 31: /* 7.32 Boot Integrity Services Entry Point */ printf("Boot Integrity Services Entry Point\n"); if (h->length < 0x1C) break; printf("\tChecksum: %s\n", checksum(data, h->length) ? "OK" : "Invalid"); printf("\t16-bit Entry Point Address: %04X:%04X\n", DWORD(data + 0x08) >> 16, DWORD(data + 0x08) & 0xFFFF); printf("\t32-bit Entry Point Address: 0x%08X\n", DWORD(data + 0x0C)); break; case 32: /* 7.33 System Boot Information */ printf("System Boot Information\n"); if (h->length < 0x0B) break; printf("\tStatus: %s\n", dmi_system_boot_status(data[0x0A])); break; case 33: /* 7.34 64-bit Memory Error Information */ if (h->length < 0x1F) break; printf("64-bit Memory Error Information\n"); printf("\tType: %s\n", dmi_memory_error_type(data[0x04])); printf("\tGranularity: %s\n", dmi_memory_error_granularity(data[0x05])); printf("\tOperation: %s\n", dmi_memory_error_operation(data[0x06])); printf("\tVendor Syndrome:"); dmi_memory_error_syndrome(DWORD(data + 0x07)); printf("\n"); printf("\tMemory Array Address:"); dmi_64bit_memory_error_address(QWORD(data + 0x0B)); printf("\n"); printf("\tDevice Address:"); dmi_64bit_memory_error_address(QWORD(data + 0x13)); printf("\n"); printf("\tResolution:"); dmi_32bit_memory_error_address(DWORD(data + 0x1B)); printf("\n"); break; case 34: /* 7.35 Management Device */ printf("Management Device\n"); if (h->length < 0x0B) break; printf("\tDescription: %s\n", dmi_string(h, data[0x04])); printf("\tType: %s\n", dmi_management_device_type(data[0x05])); printf("\tAddress: 0x%08X\n", DWORD(data + 0x06)); printf("\tAddress Type: %s\n", dmi_management_device_address_type(data[0x0A])); break; case 35: /* 7.36 Management Device Component */ printf("Management Device Component\n"); if (h->length < 0x0B) break; printf("\tDescription: %s\n", dmi_string(h, data[0x04])); if (!(opt.flags & FLAG_QUIET)) { printf("\tManagement Device Handle: 0x%04X\n", WORD(data + 0x05)); printf("\tComponent Handle: 0x%04X\n", WORD(data + 0x07)); if (WORD(data + 0x09) != 0xFFFF) printf("\tThreshold Handle: 0x%04X\n", WORD(data + 0x09)); } break; case 36: /* 7.37 Management Device Threshold Data */ printf("Management Device Threshold Data\n"); if (h->length < 0x10) break; if (WORD(data + 0x04) != 0x8000) printf("\tLower Non-critical Threshold: %d\n", (i16)WORD(data + 0x04)); if (WORD(data + 0x06) != 0x8000) printf("\tUpper Non-critical Threshold: %d\n", (i16)WORD(data + 0x06)); if (WORD(data + 0x08) != 0x8000) printf("\tLower Critical Threshold: %d\n", (i16)WORD(data + 0x08)); if (WORD(data + 0x0A) != 0x8000) printf("\tUpper Critical Threshold: %d\n", (i16)WORD(data + 0x0A)); if (WORD(data + 0x0C) != 0x8000) printf("\tLower Non-recoverable Threshold: %d\n", (i16)WORD(data + 0x0C)); if (WORD(data + 0x0E) != 0x8000) printf("\tUpper Non-recoverable Threshold: %d\n", (i16)WORD(data + 0x0E)); break; case 37: /* 7.38 Memory Channel */ printf("Memory Channel\n"); if (h->length < 0x07) break; printf("\tType: %s\n", dmi_memory_channel_type(data[0x04])); printf("\tMaximal Load: %u\n", data[0x05]); printf("\tDevices: %u\n", data[0x06]); if (h->length < 0x07 + 3 * data[0x06]) break; dmi_memory_channel_devices(data[0x06], data + 0x07, "\t"); break; case 38: /* 7.39 IPMI Device Information */ /* * We use the word "Version" instead of "Revision", conforming to * the IPMI specification. */ printf("IPMI Device Information\n"); if (h->length < 0x10) break; printf("\tInterface Type: %s\n", dmi_ipmi_interface_type(data[0x04])); printf("\tSpecification Version: %u.%u\n", data[0x05] >> 4, data[0x05] & 0x0F); printf("\tI2C Slave Address: 0x%02x\n", data[0x06] >> 1); if (data[0x07] != 0xFF) printf("\tNV Storage Device Address: %u\n", data[0x07]); else printf("\tNV Storage Device: Not Present\n"); printf("\tBase Address: "); dmi_ipmi_base_address(data[0x04], data + 0x08, h->length < 0x11 ? 0 : (data[0x10] >> 4) & 1); printf("\n"); if (h->length < 0x12) break; if (data[0x04] != 0x04) { printf("\tRegister Spacing: %s\n", dmi_ipmi_register_spacing(data[0x10] >> 6)); if (data[0x10] & (1 << 3)) { printf("\tInterrupt Polarity: %s\n", data[0x10] & (1 << 1) ? "Active High" : "Active Low"); printf("\tInterrupt Trigger Mode: %s\n", data[0x10] & (1 << 0) ? "Level" : "Edge"); } } if (data[0x11] != 0x00) { printf("\tInterrupt Number: %u\n", data[0x11]); } break; case 39: /* 7.40 System Power Supply */ printf("System Power Supply\n"); if (h->length < 0x10) break; if (data[0x04] != 0x00) printf("\tPower Unit Group: %u\n", data[0x04]); printf("\tLocation: %s\n", dmi_string(h, data[0x05])); printf("\tName: %s\n", dmi_string(h, data[0x06])); printf("\tManufacturer: %s\n", dmi_string(h, data[0x07])); printf("\tSerial Number: %s\n", dmi_string(h, data[0x08])); printf("\tAsset Tag: %s\n", dmi_string(h, data[0x09])); printf("\tModel Part Number: %s\n", dmi_string(h, data[0x0A])); printf("\tRevision: %s\n", dmi_string(h, data[0x0B])); printf("\tMax Power Capacity:"); dmi_power_supply_power(WORD(data + 0x0C)); printf("\n"); printf("\tStatus:"); if (WORD(data + 0x0E) & (1 << 1)) printf(" Present, %s", dmi_power_supply_status((WORD(data + 0x0E) >> 7) & 0x07)); else printf(" Not Present"); printf("\n"); printf("\tType: %s\n", dmi_power_supply_type((WORD(data + 0x0E) >> 10) & 0x0F)); printf("\tInput Voltage Range Switching: %s\n", dmi_power_supply_range_switching((WORD(data + 0x0E) >> 3) & 0x0F)); printf("\tPlugged: %s\n", WORD(data + 0x0E) & (1 << 2) ? "No" : "Yes"); printf("\tHot Replaceable: %s\n", WORD(data + 0x0E) & (1 << 0) ? "Yes" : "No"); if (h->length < 0x16) break; if (!(opt.flags & FLAG_QUIET)) { if (WORD(data + 0x10) != 0xFFFF) printf("\tInput Voltage Probe Handle: 0x%04X\n", WORD(data + 0x10)); if (WORD(data + 0x12) != 0xFFFF) printf("\tCooling Device Handle: 0x%04X\n", WORD(data + 0x12)); if (WORD(data + 0x14) != 0xFFFF) printf("\tInput Current Probe Handle: 0x%04X\n", WORD(data + 0x14)); } break; case 40: /* 7.41 Additional Information */ if (h->length < 0x0B) break; if (opt.flags & FLAG_QUIET) return; dmi_additional_info(h, ""); break; case 41: /* 7.42 Onboard Device Extended Information */ printf("Onboard Device\n"); if (h->length < 0x0B) break; printf("\tReference Designation: %s\n", dmi_string(h, data[0x04])); printf("\tType: %s\n", dmi_on_board_devices_type(data[0x05] & 0x7F)); printf("\tStatus: %s\n", data[0x05] & 0x80 ? "Enabled" : "Disabled"); printf("\tType Instance: %u\n", data[0x06]); dmi_slot_segment_bus_func(WORD(data + 0x07), data[0x09], data[0x0A], "\t"); break; case 42: /* 7.43 Management Controller Host Interface */ printf("Management Controller Host Interface\n"); if (h->length < 0x05) break; printf("\tInterface Type: %s\n", dmi_management_controller_host_type(data[0x04])); /* * There you have a type-dependent, variable-length * part in the middle of the structure, with no * length specifier, so no easy way to decode the * common, final part of the structure. What a pity. */ if (h->length < 0x09) break; if (data[0x04] == 0xF0) /* OEM */ { printf("\tVendor ID: 0x%02X%02X%02X%02X\n", data[0x05], data[0x06], data[0x07], data[0x08]); } break; case 43: /* 7.44 TPM Device */ printf("TPM Device\n"); if (h->length < 0x1B) break; printf("\tVendor ID:"); dmi_tpm_vendor_id(data + 0x04); printf("\n"); printf("\tSpecification Version: %d.%d", data[0x08], data[0x09]); switch (data[0x08]) { case 0x01: /* * We skip the first 2 bytes, which are * redundant with the above, and uncoded * in a silly way. */ printf("\tFirmware Revision: %u.%u\n", data[0x0C], data[0x0D]); break; case 0x02: printf("\tFirmware Revision: %u.%u\n", DWORD(data + 0x0A) >> 16, DWORD(data + 0x0A) && 0xFF); /* * We skip the next 4 bytes, as their * format is not standardized and their * usefulness seems limited anyway. */ break; } printf("\tDescription: %s", dmi_string(h, data[0x12])); printf("\tCharacteristics:\n"); dmi_tpm_characteristics(QWORD(data + 0x13), "\t\t"); if (h->length < 0x1F) break; printf("\tOEM-specific Information: 0x%08X\n", DWORD(data + 0x1B)); break; case 126: /* 7.44 Inactive */ printf("Inactive\n"); break; case 127: /* 7.45 End Of Table */ printf("End Of Table\n"); break; default: if (dmi_decode_oem(h)) break; if (opt.flags & FLAG_QUIET) return; printf("%s Type\n", h->type >= 128 ? "OEM-specific" : "Unknown"); dmi_dump(h, "\t"); } printf("\n"); } static void to_dmi_header(struct dmi_header *h, u8 *data) { h->type = data[0]; h->length = data[1]; h->handle = WORD(data + 2); h->data = data; } static void dmi_table_string(const struct dmi_header *h, const u8 *data, u16 ver) { int key; u8 offset = opt.string->offset; if (opt.string->type == 11) /* OEM strings */ { if (h->length < 5 || offset > data[4]) { fprintf(stderr, "No OEM string number %u\n", offset); return; } if (offset) printf("%s\n", dmi_string(h, offset)); else printf("%u\n", data[4]); /* count */ return; } if (offset >= h->length) return; key = (opt.string->type << 8) | offset; switch (key) { case 0x108: dmi_system_uuid(data + offset, ver); printf("\n"); break; case 0x305: printf("%s\n", dmi_chassis_type(data[offset])); break; case 0x406: printf("%s\n", dmi_processor_family(h, ver)); break; case 0x416: dmi_processor_frequency(data + offset); printf("\n"); break; default: printf("%s\n", dmi_string(h, data[offset])); } } static void dmi_table_dump(const u8 *buf, u32 len) { if (!(opt.flags & FLAG_QUIET)) printf("# Writing %d bytes to %s.\n", len, opt.dumpfile); write_dump(32, len, buf, opt.dumpfile, 0); } static void dmi_table_decode(u8 *buf, u32 len, u16 num, u16 ver, u32 flags) { u8 *data; int i = 0; data = buf; while ((i < num || !num) && data + 4 <= buf + len) /* 4 is the length of an SMBIOS structure header */ { u8 *next; struct dmi_header h; int display; to_dmi_header(&h, data); display = ((opt.type == NULL || opt.type[h.type]) && !((opt.flags & FLAG_QUIET) && (h.type == 126 || h.type == 127)) && !opt.string); /* * If a short entry is found (less than 4 bytes), not only it * is invalid, but we cannot reliably locate the next entry. * Better stop at this point, and let the user know his/her * table is broken. */ if (h.length < 4) { if (!(opt.flags & FLAG_QUIET)) { fprintf(stderr, "Invalid entry length (%u). DMI table " "is broken! Stop.\n\n", (unsigned int)h.length); opt.flags |= FLAG_QUIET; } break; } /* In quiet mode, stop decoding at end of table marker */ if ((opt.flags & FLAG_QUIET) && h.type == 127) break; if (display && (!(opt.flags & FLAG_QUIET) || (opt.flags & FLAG_DUMP))) printf("Handle 0x%04X, DMI type %d, %d bytes\n", h.handle, h.type, h.length); /* assign vendor for vendor-specific decodes later */ if (h.type == 1 && h.length >= 5) dmi_set_vendor(dmi_string(&h, data[0x04])); /* Fixup a common mistake */ if (h.type == 34) dmi_fixup_type_34(&h, display); /* look for the next handle */ next = data + h.length; while ((unsigned long)(next - buf + 1) < len && (next[0] != 0 || next[1] != 0)) next++; next += 2; if (display) { if ((unsigned long)(next - buf) <= len) { if (opt.flags & FLAG_DUMP) { dmi_dump(&h, "\t"); printf("\n"); } else dmi_decode(&h, ver); } else if (!(opt.flags & FLAG_QUIET)) printf("\t<TRUNCATED>\n\n"); } else if (opt.string != NULL && opt.string->type == h.type) dmi_table_string(&h, data, ver); data = next; i++; /* SMBIOS v3 requires stopping at this marker */ if (h.type == 127 && (flags & FLAG_STOP_AT_EOT)) break; } /* * SMBIOS v3 64-bit entry points do not announce a structures count, * and only indicate a maximum size for the table. */ if (!(opt.flags & FLAG_QUIET)) { if (num && i != num) fprintf(stderr, "Wrong DMI structures count: %d announced, " "only %d decoded.\n", num, i); if ((unsigned long)(data - buf) > len || (num && (unsigned long)(data - buf) < len)) fprintf(stderr, "Wrong DMI structures length: %u bytes " "announced, structures occupy %lu bytes.\n", len, (unsigned long)(data - buf)); } } static void dmi_table(off_t base, u32 len, u16 num, u32 ver, const char *devmem, u32 flags) { u8 *buf; if (ver > SUPPORTED_SMBIOS_VER && !(opt.flags & FLAG_QUIET)) { printf("# SMBIOS implementations newer than version %u.%u.%u are not\n" "# fully supported by this version of dmidecode.\n", SUPPORTED_SMBIOS_VER >> 16, (SUPPORTED_SMBIOS_VER >> 8) & 0xFF, SUPPORTED_SMBIOS_VER & 0xFF); } if (!(opt.flags & FLAG_QUIET)) { if (opt.type == NULL) { if (num) printf("%u structures occupying %u bytes.\n", num, len); if (!(flags & FLAG_FROM_API) && !(opt.flags & FLAG_FROM_DUMP)) printf("Table at 0x%08llX.\n", (unsigned long long)base); } printf("\n"); } if ((flags & FLAG_NO_FILE_OFFSET) || (opt.flags & FLAG_FROM_DUMP)) { /* * When reading from sysfs or from a dump file, the file may be * shorter than announced. For SMBIOS v3 this is expcted, as we * only know the maximum table size, not the actual table size. * For older implementations (and for SMBIOS v3 too), this * would be the result of the kernel truncating the table on * parse error. */ size_t size = len; buf = read_file(flags & FLAG_NO_FILE_OFFSET ? 0 : base, &size, devmem); if (!(opt.flags & FLAG_QUIET) && num && size != (size_t)len) { fprintf(stderr, "Wrong DMI structures length: %u bytes " "announced, only %lu bytes available.\n", len, (unsigned long)size); } len = size; } else buf = mem_chunk(base, len, devmem); #ifdef __APPLE__ // read tables returned by API call if (flags & FLAG_FROM_API) { mach_port_t masterPort; CFMutableDictionaryRef properties = NULL; io_service_t service = MACH_PORT_NULL; CFDataRef dataRef; IOMasterPort(MACH_PORT_NULL, &masterPort); service = IOServiceGetMatchingService(masterPort, IOServiceMatching("AppleSMBIOS")); if (service == MACH_PORT_NULL) { fprintf(stderr, "AppleSMBIOS service is unreachable, sorry.\n"); return; } if (kIOReturnSuccess != IORegistryEntryCreateCFProperties(service, &properties, kCFAllocatorDefault, kNilOptions)) { fprintf(stderr, "No data in AppleSMBIOS IOService, sorry.\n"); return; } if (!CFDictionaryGetValueIfPresent(properties, CFSTR( "SMBIOS"), (const void **)&dataRef)) { fprintf(stderr, "SMBIOS property data is unreachable, sorry.\n"); return; } len = CFDataGetLength(dataRef); if((buf = malloc(sizeof(u8) * len)) == NULL) { perror("malloc"); return; } CFDataGetBytes(dataRef, CFRangeMake(0, len), (UInt8*)buf); if (NULL != dataRef) CFRelease(dataRef); /* * This CFRelease throws 'Segmentation fault: 11' since macOS 10.12, if * the compiled binary is not signed with an Apple developer profile. */ if (NULL != properties) CFRelease(properties); IOObjectRelease(service); } #endif // __APPLE__ if (buf == NULL) { fprintf(stderr, "Failed to read table, sorry.\n"); #ifndef USE_MMAP if (!(flags & FLAG_NO_FILE_OFFSET)) fprintf(stderr, "Try compiling dmidecode with -DUSE_MMAP.\n"); #endif return; } if (opt.flags & FLAG_DUMP_BIN) dmi_table_dump(buf, len); else dmi_table_decode(buf, len, num, ver >> 8, flags); free(buf); } /* * Build a crafted entry point with table address hard-coded to 32, * as this is where we will put it in the output file. We adjust the * DMI checksum appropriately. The SMBIOS checksum needs no adjustment. */ static void overwrite_dmi_address(u8 *buf) { buf[0x05] += buf[0x08] + buf[0x09] + buf[0x0A] + buf[0x0B] - 32; buf[0x08] = 32; buf[0x09] = 0; buf[0x0A] = 0; buf[0x0B] = 0; } /* Same thing for SMBIOS3 entry points */ static void overwrite_smbios3_address(u8 *buf) { buf[0x05] += buf[0x10] + buf[0x11] + buf[0x12] + buf[0x13] + buf[0x14] + buf[0x15] + buf[0x16] + buf[0x17] - 32; buf[0x10] = 32; buf[0x11] = 0; buf[0x12] = 0; buf[0x13] = 0; buf[0x14] = 0; buf[0x15] = 0; buf[0x16] = 0; buf[0x17] = 0; } static int smbios3_decode(u8 *buf, const char *devmem, u32 flags) { u32 ver; u64 offset; if (!checksum(buf, buf[0x06])) return 0; ver = (buf[0x07] << 16) + (buf[0x08] << 8) + buf[0x09]; if (!(opt.flags & FLAG_QUIET)) printf("SMBIOS %u.%u.%u present.\n", buf[0x07], buf[0x08], buf[0x09]); offset = QWORD(buf + 0x10); if (!(flags & FLAG_NO_FILE_OFFSET) && offset.h && sizeof(off_t) < 8) { fprintf(stderr, "64-bit addresses not supported, sorry.\n"); return 0; } dmi_table(((off_t)offset.h << 32) | offset.l, DWORD(buf + 0x0C), 0, ver, devmem, flags | FLAG_STOP_AT_EOT); if (opt.flags & FLAG_DUMP_BIN) { u8 crafted[32]; memcpy(crafted, buf, 32); overwrite_smbios3_address(crafted); if (!(opt.flags & FLAG_QUIET)) printf("# Writing %d bytes to %s.\n", crafted[0x06], opt.dumpfile); write_dump(0, crafted[0x06], crafted, opt.dumpfile, 1); } return 1; } static int smbios_decode(u8 *buf, const char *devmem, u32 flags) { u16 ver; if (!checksum(buf, buf[0x05]) || memcmp(buf + 0x10, "_DMI_", 5) != 0 || !checksum(buf + 0x10, 0x0F)) return 0; ver = (buf[0x06] << 8) + buf[0x07]; /* Some BIOS report weird SMBIOS version, fix that up */ switch (ver) { case 0x021F: case 0x0221: if (!(opt.flags & FLAG_QUIET)) fprintf(stderr, "SMBIOS version fixup (2.%d -> 2.%d).\n", ver & 0xFF, 3); ver = 0x0203; break; case 0x0233: if (!(opt.flags & FLAG_QUIET)) fprintf(stderr, "SMBIOS version fixup (2.%d -> 2.%d).\n", 51, 6); ver = 0x0206; break; } if (!(opt.flags & FLAG_QUIET)) printf("SMBIOS %u.%u present.\n", ver >> 8, ver & 0xFF); dmi_table(DWORD(buf + 0x18), WORD(buf + 0x16), WORD(buf + 0x1C), ver << 8, devmem, flags); if (opt.flags & FLAG_DUMP_BIN) { u8 crafted[32]; memcpy(crafted, buf, 32); overwrite_dmi_address(crafted + 0x10); if (!(opt.flags & FLAG_QUIET)) printf("# Writing %d bytes to %s.\n", crafted[0x05], opt.dumpfile); write_dump(0, crafted[0x05], crafted, opt.dumpfile, 1); } return 1; } static int legacy_decode(u8 *buf, const char *devmem, u32 flags) { if (!checksum(buf, 0x0F)) return 0; if (!(opt.flags & FLAG_QUIET)) printf("Legacy DMI %u.%u present.\n", buf[0x0E] >> 4, buf[0x0E] & 0x0F); dmi_table(DWORD(buf + 0x08), WORD(buf + 0x06), WORD(buf + 0x0C), ((buf[0x0E] & 0xF0) << 12) + ((buf[0x0E] & 0x0F) << 8), devmem, flags); if (opt.flags & FLAG_DUMP_BIN) { u8 crafted[16]; memcpy(crafted, buf, 16); overwrite_dmi_address(crafted); if (!(opt.flags & FLAG_QUIET)) printf("# Writing %d bytes to %s.\n", 0x0F, opt.dumpfile); write_dump(0, 0x0F, crafted, opt.dumpfile, 1); } return 1; } /* * Probe for EFI interface */ #define EFI_NOT_FOUND (-1) #define EFI_NO_SMBIOS (-2) static int address_from_efi(off_t *address) { FILE *efi_systab; const char *filename; char linebuf[64]; int ret; *address = 0; /* Prevent compiler warning */ /* * Linux up to 2.6.6: /proc/efi/systab * Linux 2.6.7 and up: /sys/firmware/efi/systab */ if ((efi_systab = fopen(filename = "/sys/firmware/efi/systab", "r")) == NULL && (efi_systab = fopen(filename = "/proc/efi/systab", "r")) == NULL) { /* No EFI interface, fallback to memory scan */ return EFI_NOT_FOUND; } ret = EFI_NO_SMBIOS; while ((fgets(linebuf, sizeof(linebuf) - 1, efi_systab)) != NULL) { char *addrp = strchr(linebuf, '='); *(addrp++) = '\0'; if (strcmp(linebuf, "SMBIOS3") == 0 || strcmp(linebuf, "SMBIOS") == 0) { *address = strtoull(addrp, NULL, 0); if (!(opt.flags & FLAG_QUIET)) printf("# %s entry point at 0x%08llx\n", linebuf, (unsigned long long)*address); ret = 0; break; } } if (fclose(efi_systab) != 0) perror(filename); if (ret == EFI_NO_SMBIOS) fprintf(stderr, "%s: SMBIOS entry point missing\n", filename); return ret; } int main(int argc, char * const argv[]) { int ret = 0; /* Returned value */ int found = 0; off_t fp; size_t size; int efi; u8 *buf; /* * We don't want stdout and stderr to be mixed up if both are * redirected to the same file. */ setlinebuf(stdout); setlinebuf(stderr); if (sizeof(u8) != 1 || sizeof(u16) != 2 || sizeof(u32) != 4 || '\0' != 0) { fprintf(stderr, "%s: compiler incompatibility\n", argv[0]); exit(255); } /* Set default option values */ opt.devmem = DEFAULT_MEM_DEV; opt.flags = 0; if (parse_command_line(argc, argv)<0) { ret = 2; goto exit_free; } if (opt.flags & FLAG_HELP) { print_help(); goto exit_free; } if (opt.flags & FLAG_VERSION) { printf("%s\n", VERSION); goto exit_free; } if (!(opt.flags & FLAG_QUIET)) printf("# dmidecode %s\n", VERSION); /* Read from dump if so instructed */ if (opt.flags & FLAG_FROM_DUMP) { if (!(opt.flags & FLAG_QUIET)) printf("Reading SMBIOS/DMI data from file %s.\n", opt.dumpfile); if ((buf = mem_chunk(0, 0x20, opt.dumpfile)) == NULL) { ret = 1; goto exit_free; } if (memcmp(buf, "_SM3_", 5) == 0) { if (smbios3_decode(buf, opt.dumpfile, 0)) found++; } else if (memcmp(buf, "_SM_", 4) == 0) { if (smbios_decode(buf, opt.dumpfile, 0)) found++; } else if (memcmp(buf, "_DMI_", 5) == 0) { if (legacy_decode(buf, opt.dumpfile, 0)) found++; } goto done; } #if defined(__APPLE__) mach_port_t masterPort; io_service_t service = MACH_PORT_NULL; CFDataRef dataRef; if (!(opt.flags & FLAG_QUIET)) printf("Getting SMBIOS data from Apple SMBIOS service.\n"); IOMasterPort(MACH_PORT_NULL, &masterPort); service = IOServiceGetMatchingService(masterPort, IOServiceMatching("AppleSMBIOS")); if (service == MACH_PORT_NULL) { fprintf(stderr, "AppleSMBIOS service is unreachable, sorry."); ret = 1; goto exit_free; } dataRef = (CFDataRef) IORegistryEntryCreateCFProperty(service, CFSTR("SMBIOS-EPS"), kCFAllocatorDefault, kNilOptions); if (dataRef == NULL) { fprintf(stderr, "SMBIOS entry point is unreachable, sorry.\n"); ret = 1; goto exit_free; } if((buf = malloc(0x20)) == NULL) { perror("malloc"); ret = 1; goto exit_free; } CFDataGetBytes(dataRef, CFRangeMake(0, 0x20), (UInt8*)buf); if (NULL != dataRef) CFRelease(dataRef); IOObjectRelease(service); if (smbios_decode(buf, NULL, FLAG_FROM_API)) { found++; goto done; } #endif // __APPLE__ /* * First try reading from sysfs tables. The entry point file could * contain one of several types of entry points, so read enough for * the largest one, then determine what type it contains. */ size = 0x20; if (!(opt.flags & FLAG_NO_SYSFS) && (buf = read_file(0, &size, SYS_ENTRY_FILE)) != NULL) { if (!(opt.flags & FLAG_QUIET)) printf("Getting SMBIOS data from sysfs.\n"); if (size >= 24 && memcmp(buf, "_SM3_", 5) == 0) { if (smbios3_decode(buf, SYS_TABLE_FILE, FLAG_NO_FILE_OFFSET)) found++; } else if (size >= 31 && memcmp(buf, "_SM_", 4) == 0) { if (smbios_decode(buf, SYS_TABLE_FILE, FLAG_NO_FILE_OFFSET)) found++; } else if (size >= 15 && memcmp(buf, "_DMI_", 5) == 0) { if (legacy_decode(buf, SYS_TABLE_FILE, FLAG_NO_FILE_OFFSET)) found++; } if (found) goto done; if (!(opt.flags & FLAG_QUIET)) printf("Failed to get SMBIOS data from sysfs.\n"); } /* Next try EFI (ia64, Intel-based Mac) */ efi = address_from_efi(&fp); switch (efi) { case EFI_NOT_FOUND: goto memory_scan; case EFI_NO_SMBIOS: ret = 1; goto exit_free; } if (!(opt.flags & FLAG_QUIET)) printf("Found SMBIOS entry point in EFI, reading table from %s.\n", opt.devmem); if ((buf = mem_chunk(fp, 0x20, opt.devmem)) == NULL) { ret = 1; goto exit_free; } if (memcmp(buf, "_SM3_", 5) == 0) { if (smbios3_decode(buf, opt.devmem, 0)) found++; } else if (memcmp(buf, "_SM_", 4) == 0) { if (smbios_decode(buf, opt.devmem, 0)) found++; } goto done; memory_scan: if (!(opt.flags & FLAG_QUIET)) printf("Scanning %s for entry point.\n", opt.devmem); /* Fallback to memory scan (x86, x86_64) */ if ((buf = mem_chunk(0xF0000, 0x10000, opt.devmem)) == NULL) { ret = 1; goto exit_free; } /* Look for a 64-bit entry point first */ for (fp = 0; fp <= 0xFFE0; fp += 16) { if (memcmp(buf + fp, "_SM3_", 5) == 0) { if (smbios3_decode(buf + fp, opt.devmem, 0)) { found++; goto done; } } } /* If none found, look for a 32-bit entry point */ for (fp = 0; fp <= 0xFFF0; fp += 16) { if (memcmp(buf + fp, "_SM_", 4) == 0 && fp <= 0xFFE0) { if (smbios_decode(buf + fp, opt.devmem, 0)) { found++; goto done; } } else if (memcmp(buf + fp, "_DMI_", 5) == 0) { if (legacy_decode(buf + fp, opt.devmem, 0)) { found++; goto done; } } } done: if (!found && !(opt.flags & FLAG_QUIET)) printf("# No SMBIOS nor DMI entry point found, sorry.\n"); free(buf); exit_free: free(opt.type); return ret; }
23.72932
102
0.601729
af5825963a0c42cc6c6c31ec5b5e7f64db214cef
116
h
C
include/dialogs/window.h
ThomasAdam/rofi
27f5c7413e75d2f381ea4d2d7affcc27704d769f
[ "MIT" ]
null
null
null
include/dialogs/window.h
ThomasAdam/rofi
27f5c7413e75d2f381ea4d2d7affcc27704d769f
[ "MIT" ]
null
null
null
include/dialogs/window.h
ThomasAdam/rofi
27f5c7413e75d2f381ea4d2d7affcc27704d769f
[ "MIT" ]
null
null
null
#ifndef __WINDOW_DIALOG_H__ #define __WINDOW_DIALOG_H__ extern Switcher window_mode; #endif // __WINDOW_DIALOG_H__
19.333333
29
0.853448
c63351473686262a9436aff8a0f2f93357414f91
2,923
h
C
Modules/_sre/sre_constants.h
dignissimus/cpython
17357108732c731d6ed4f2bd123ee6ba1ff6891b
[ "0BSD" ]
null
null
null
Modules/_sre/sre_constants.h
dignissimus/cpython
17357108732c731d6ed4f2bd123ee6ba1ff6891b
[ "0BSD" ]
2
2022-01-01T11:08:44.000Z
2022-03-01T19:01:02.000Z
Modules/_sre/sre_constants.h
dignissimus/cpython
17357108732c731d6ed4f2bd123ee6ba1ff6891b
[ "0BSD" ]
null
null
null
/* * Secret Labs' Regular Expression Engine * * regular expression matching engine * * Auto-generated by Tools/scripts/generate_sre_constants.py from * Lib/re/_constants.py. * * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. * * See the sre.c file for information on usage and redistribution. */ #define SRE_MAGIC 20220615 #define SRE_OP_FAILURE 0 #define SRE_OP_SUCCESS 1 #define SRE_OP_ANY 2 #define SRE_OP_ANY_ALL 3 #define SRE_OP_ASSERT 4 #define SRE_OP_ASSERT_NOT 5 #define SRE_OP_AT 6 #define SRE_OP_BRANCH 7 #define SRE_OP_CATEGORY 8 #define SRE_OP_CHARSET 9 #define SRE_OP_BIGCHARSET 10 #define SRE_OP_GROUPREF 11 #define SRE_OP_GROUPREF_EXISTS 12 #define SRE_OP_IN 13 #define SRE_OP_INFO 14 #define SRE_OP_JUMP 15 #define SRE_OP_LITERAL 16 #define SRE_OP_MARK 17 #define SRE_OP_MAX_UNTIL 18 #define SRE_OP_MIN_UNTIL 19 #define SRE_OP_NOT_LITERAL 20 #define SRE_OP_NEGATE 21 #define SRE_OP_RANGE 22 #define SRE_OP_REPEAT 23 #define SRE_OP_REPEAT_ONE 24 #define SRE_OP_SUBPATTERN 25 #define SRE_OP_MIN_REPEAT_ONE 26 #define SRE_OP_ATOMIC_GROUP 27 #define SRE_OP_POSSESSIVE_REPEAT 28 #define SRE_OP_POSSESSIVE_REPEAT_ONE 29 #define SRE_OP_GROUPREF_IGNORE 30 #define SRE_OP_IN_IGNORE 31 #define SRE_OP_LITERAL_IGNORE 32 #define SRE_OP_NOT_LITERAL_IGNORE 33 #define SRE_OP_GROUPREF_LOC_IGNORE 34 #define SRE_OP_IN_LOC_IGNORE 35 #define SRE_OP_LITERAL_LOC_IGNORE 36 #define SRE_OP_NOT_LITERAL_LOC_IGNORE 37 #define SRE_OP_GROUPREF_UNI_IGNORE 38 #define SRE_OP_IN_UNI_IGNORE 39 #define SRE_OP_LITERAL_UNI_IGNORE 40 #define SRE_OP_NOT_LITERAL_UNI_IGNORE 41 #define SRE_OP_RANGE_UNI_IGNORE 42 #define SRE_AT_BEGINNING 0 #define SRE_AT_BEGINNING_LINE 1 #define SRE_AT_BEGINNING_STRING 2 #define SRE_AT_BOUNDARY 3 #define SRE_AT_NON_BOUNDARY 4 #define SRE_AT_END 5 #define SRE_AT_END_LINE 6 #define SRE_AT_END_STRING 7 #define SRE_AT_LOC_BOUNDARY 8 #define SRE_AT_LOC_NON_BOUNDARY 9 #define SRE_AT_UNI_BOUNDARY 10 #define SRE_AT_UNI_NON_BOUNDARY 11 #define SRE_CATEGORY_DIGIT 0 #define SRE_CATEGORY_NOT_DIGIT 1 #define SRE_CATEGORY_SPACE 2 #define SRE_CATEGORY_NOT_SPACE 3 #define SRE_CATEGORY_WORD 4 #define SRE_CATEGORY_NOT_WORD 5 #define SRE_CATEGORY_LINEBREAK 6 #define SRE_CATEGORY_NOT_LINEBREAK 7 #define SRE_CATEGORY_LOC_WORD 8 #define SRE_CATEGORY_LOC_NOT_WORD 9 #define SRE_CATEGORY_UNI_DIGIT 10 #define SRE_CATEGORY_UNI_NOT_DIGIT 11 #define SRE_CATEGORY_UNI_SPACE 12 #define SRE_CATEGORY_UNI_NOT_SPACE 13 #define SRE_CATEGORY_UNI_WORD 14 #define SRE_CATEGORY_UNI_NOT_WORD 15 #define SRE_CATEGORY_UNI_LINEBREAK 16 #define SRE_CATEGORY_UNI_NOT_LINEBREAK 17 #define SRE_FLAG_TEMPLATE 1 #define SRE_FLAG_IGNORECASE 2 #define SRE_FLAG_LOCALE 4 #define SRE_FLAG_MULTILINE 8 #define SRE_FLAG_DOTALL 16 #define SRE_FLAG_UNICODE 32 #define SRE_FLAG_VERBOSE 64 #define SRE_FLAG_DEBUG 128 #define SRE_FLAG_ASCII 256 #define SRE_INFO_PREFIX 1 #define SRE_INFO_LITERAL 2 #define SRE_INFO_CHARSET 4
29.23
67
0.851865
7662bc8a7960eb961696ddf7d3b396b0aff80754
571
h
C
include/spectrum.h
alexwenym/NEWS-G-SNOLAB-Simulation
4f936d5dd5ed4c43e0b470ae7b0d52e29385f3d4
[ "MIT" ]
null
null
null
include/spectrum.h
alexwenym/NEWS-G-SNOLAB-Simulation
4f936d5dd5ed4c43e0b470ae7b0d52e29385f3d4
[ "MIT" ]
null
null
null
include/spectrum.h
alexwenym/NEWS-G-SNOLAB-Simulation
4f936d5dd5ed4c43e0b470ae7b0d52e29385f3d4
[ "MIT" ]
null
null
null
#ifndef __SHIELD_SPECTRUM_H_ #define __SHIELD_SPECTRUM_H_ #include <initializer_list> #include <string> #include <vector> #include <G4Types.hh> namespace shield { struct EnergyFrequencyPair { G4double energy; G4double frequency; }; class Spectrum { public: Spectrum(std::initializer_list<EnergyFrequencyPair> spectrum); Spectrum(std::string fileName); virtual ~Spectrum() { } // Given a number between 0 and 1, returns an value from the spectrum. G4double Draw(G4double x); private: std::vector<EnergyFrequencyPair> m_spectrum; }; } #endif
14.275
71
0.744308
bbdfa2e814a1e1ee8eb5c7de741eadf871bd1bd5
1,586
h
C
YubiKit/YubiKit/SharedModel/YKFOTPTextParserProtocol.h
boxatom/yubikit-ios
b0b1b0a39c8c06512e87555e679d7c71b7b46da3
[ "Apache-2.0" ]
136
2019-08-19T11:37:08.000Z
2022-03-22T14:28:03.000Z
YubiKit/YubiKit/SharedModel/YKFOTPTextParserProtocol.h
boxatom/yubikit-ios
b0b1b0a39c8c06512e87555e679d7c71b7b46da3
[ "Apache-2.0" ]
54
2019-09-02T20:07:32.000Z
2022-03-25T07:42:58.000Z
YubiKit/YubiKit/SharedModel/YKFOTPTextParserProtocol.h
boxatom/yubikit-ios
b0b1b0a39c8c06512e87555e679d7c71b7b46da3
[ "Apache-2.0" ]
37
2019-09-10T15:59:26.000Z
2022-03-07T12:49:55.000Z
// Copyright 2018-2019 Yubico AB // // 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. NS_ASSUME_NONNULL_BEGIN /*! @protocol YKFOTPTextParserProtocol @abstract Interface for a NFC OTP custom text parser. If the used YubiKeys use a custom way of formatting the text received from the YubiKey a custom parser can be provided by the host application by implementing this interface and setting it on YubiKitConfiguration. */ @protocol YKFOTPTextParserProtocol<NSObject> /*! @method tokenFromPayload: @abstract Implements the extraction of the token from the payload. This method should always return a token, since the token is the minimal information all payloads should have. In case the token is not valid it should return a empty string. */ - (NSString *)tokenFromPayload:(NSString *)payload; /*! @method textFromPayload: @abstract Implements the extraction of the text from the payload. This method can return nil if no text is available in the payload. */ - (nullable NSString *)textFromPayload:(NSString *)payload; @end NS_ASSUME_NONNULL_END
34.478261
134
0.764187
6380ff2d8e1328874c1f9056c4c66e3e00c14ad6
2,884
h
C
mlir/include/mlir/Dialect/LLVMIR/FunctionCallUtils.h
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
mlir/include/mlir/Dialect/LLVMIR/FunctionCallUtils.h
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
mlir/include/mlir/Dialect/LLVMIR/FunctionCallUtils.h
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===- FunctionCallUtils.h - Utilities for C function calls -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file declares helper functions to call common simple C functions in // LLVMIR (e.g. among others to support printing and debugging). // //===----------------------------------------------------------------------===// #ifndef MLIR_DIALECT_LLVMIR_FUNCTIONCALLUTILS_H_ #define MLIR_DIALECT_LLVMIR_FUNCTIONCALLUTILS_H_ #include "mlir/IR/Operation.h" #include "mlir/Support/LLVM.h" namespace mlir { class Location; class ModuleOp; class OpBuilder; class Operation; class Type; class ValueRange; namespace LLVM { class LLVMFuncOp; /// Helper functions to lookup or create the declaration for commonly used /// external C function calls. Such ops can then be invoked by creating a CallOp /// with the proper arguments via `createLLVMCall`. /// The list of functions provided here must be implemented separately (e.g. as /// part of a support runtime library or as part of the libc). LLVM::LLVMFuncOp lookupOrCreatePrintI64Fn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintU64Fn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintF32Fn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintF64Fn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintOpenFn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintCloseFn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintCommaFn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreatePrintNewlineFn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreateMallocFn(ModuleOp moduleOp, Type indexType); LLVM::LLVMFuncOp lookupOrCreateAlignedAllocFn(ModuleOp moduleOp, Type indexType); LLVM::LLVMFuncOp lookupOrCreateFreeFn(ModuleOp moduleOp); LLVM::LLVMFuncOp lookupOrCreateMemRefCopyFn(ModuleOp moduleOp, Type indexType, Type unrankedDescriptorType); /// Create a FuncOp with signature `resultType`(`paramTypes`)` and name `name`. LLVM::LLVMFuncOp lookupOrCreateFn(ModuleOp moduleOp, StringRef name, ArrayRef<Type> paramTypes = {}, Type resultType = {}); /// Helper wrapper to create a call to `fn` with `args` and `resultTypes`. Operation::result_range createLLVMCall(OpBuilder &b, Location loc, LLVM::LLVMFuncOp fn, ValueRange args = {}, ArrayRef<Type> resultTypes = {}); } // namespace LLVM } // namespace mlir #endif // MLIR_DIALECT_LLVMIR_FUNCTIONCALLUTILS_H_
43.69697
80
0.671983
49ccc017034bfc79f1ecd0a53ffd349c120a85c5
2,205
c
C
turbine/code/src/tcl/julia/tcl-julia.c
hsphcdm/swift-t
4e3131f38c0985bd0995574848ad79f0b626ceb5
[ "Apache-2.0" ]
51
2015-06-09T00:37:48.000Z
2021-09-07T20:36:01.000Z
turbine/code/src/tcl/julia/tcl-julia.c
hsphcdm/swift-t
4e3131f38c0985bd0995574848ad79f0b626ceb5
[ "Apache-2.0" ]
175
2015-04-22T20:34:41.000Z
2021-07-09T16:52:09.000Z
turbine/code/src/tcl/julia/tcl-julia.c
hsphcdm/swift-t
4e3131f38c0985bd0995574848ad79f0b626ceb5
[ "Apache-2.0" ]
25
2015-06-08T18:53:44.000Z
2020-12-01T16:42:27.000Z
/* * tcl-julia.c * * Created on: Jun 2, 2014 * Author: wozniak */ #include "config.h" #include <stdio.h> #include <tcl.h> #ifdef INLINE // Julia also defines INLINE #undef INLINE #endif #include <exm-string.h> #include "src/util/debug.h" #include "src/tcl/util.h" #include "src/tcl/julia/tcl-julia.h" #if HAVE_JULIA == 1 #include <julia.h> static bool initialized = false; static void inline julia_initialize(void) { jl_init(NULL); JL_SET_STACK_BASE; initialized = true; } static int julia_eval(const char* code, Tcl_Obj** result) { if (!initialized) julia_initialize(); int length = strlen(code); char assignment[length + 32]; DEBUG_TCL_TURBINE("julia evaluation:\n%s", code); sprintf(assignment, "_t = %s", code); // sprintf(assignment, "_t = sqrt(2.0)"); jl_eval_string(assignment); jl_value_t* value = jl_eval_string("\"$_t\n\""); char* s = jl_string_data(value); chomp(s); DEBUG_TCL_TURBINE("julia result: %s", s); *result = Tcl_NewStringObj(s, -1); return TCL_OK; } static int Julia_Eval_Cmd(ClientData cdata, Tcl_Interp* interp, int objc, Tcl_Obj* const objv[]) { TCL_ARGS(2); char* code = Tcl_GetString(objv[1]); Tcl_Obj* result = NULL; int rc = julia_eval(code, &result); TCL_CHECK(rc); Tcl_SetObjResult(interp, result); return TCL_OK; } #else // Julia disabled static int Julia_Eval_Cmd(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { TCL_ARGS(2); // TODO: Throw TURBINE ERROR for cleaner handling (#601) turbine_tcl_condition_failed(interp, objv[0], "Turbine not compiled with Julia support"); return TCL_ERROR; } #endif /** Called when Tcl loads this extension */ int DLLEXPORT Tcljulia_Init(Tcl_Interp* interp) { if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) return TCL_ERROR; if (Tcl_PkgProvide(interp, "python", "0.1") == TCL_ERROR) return TCL_ERROR; return TCL_OK; } #define COMMAND(tcl_function, c_function) \ Tcl_CreateObjCommand(interp, "julia::" tcl_function, c_function, \ NULL, NULL); void tcl_julia_init(Tcl_Interp* interp) { COMMAND("eval", Julia_Eval_Cmd); }
19.864865
70
0.671655
e49241195665be684821154094a33d4804f0113a
1,190
h
C
include/RE/A/ActorKnowledge.h
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
118
2019-02-07T22:34:11.000Z
2022-03-29T10:40:40.000Z
include/RE/A/ActorKnowledge.h
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
63
2019-07-30T13:50:11.000Z
2022-02-19T02:14:33.000Z
include/RE/A/ActorKnowledge.h
colinswrath/CommonLibSSE
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
[ "MIT" ]
71
2019-05-21T00:15:51.000Z
2022-03-03T15:14:19.000Z
#pragma once #include "RE/A/AITimeStamp.h" #include "RE/B/BSPointerHandle.h" #include "RE/F/FightReactions.h" #include "RE/N/NiRefObject.h" #include "RE/N/NiSmartPointer.h" namespace RE { class DetectionListener; class DetectionState; class ActorKnowledge : public NiRefObject { public: inline static constexpr auto RTTI = RTTI_ActorKnowledge; enum class FLAGS { kNone = 0 }; ~ActorKnowledge() override; // 00 // members ActorHandle owner; // 10 ActorHandle target; // 14 stl::enumeration<FIGHT_REACTION, std::uint32_t> factionFightReaction; // 18 AITimeStamp shouldAttackTargetTimeStamp; // 1C NiPointer<DetectionState> detectionState; // 20 BSTArray<NiPointer<DetectionListener>> listeners; // 28 stl::enumeration<FLAGS, std::uint32_t> flags; // 40 AITimeStamp detectionQueuedTimeStamp; // 44 }; static_assert(sizeof(ActorKnowledge) == 0x48); }
31.315789
85
0.551261
0221504586848336087f6f84ee815d3b67f22b53
249
h
C
Example/Pellicola/PhotoStarStyle.h
Subito-it/Pellicola
d4c9d7dbbef7f9fffaf873c6d406e4e53f699759
[ "Apache-2.0" ]
9
2017-11-14T10:55:23.000Z
2019-09-02T11:18:37.000Z
Example/Pellicola/PhotoStarStyle.h
Subito-it/Pellicola
d4c9d7dbbef7f9fffaf873c6d406e4e53f699759
[ "Apache-2.0" ]
2
2018-05-31T08:54:55.000Z
2018-09-12T15:10:13.000Z
Example/Pellicola/PhotoStarStyle.h
Subito-it/Pellicola
d4c9d7dbbef7f9fffaf873c6d406e4e53f699759
[ "Apache-2.0" ]
null
null
null
// // PhotoStarStyle.h // Pellicola_Example // // Created by Andrea Antonioni on 01/02/2018. // Copyright © 2018 CocoaPods. All rights reserved. // #import "Pellicola-Swift.h" @interface PhotoStarStyle: NSObject <PellicolaStyleProtocol> @end
17.785714
60
0.730924
f2068ea2f98b8acf360700605b90453f4c4bf0a4
5,185
c
C
fft/filter.c
ouluz/Labview_fft
b4b32a37878364001bf7d41010345954bac1fa42
[ "MIT" ]
null
null
null
fft/filter.c
ouluz/Labview_fft
b4b32a37878364001bf7d41010345954bac1fa42
[ "MIT" ]
null
null
null
fft/filter.c
ouluz/Labview_fft
b4b32a37878364001bf7d41010345954bac1fa42
[ "MIT" ]
1
2022-03-30T02:15:58.000Z
2022-03-30T02:15:58.000Z
/* ==================================================================== * Title: filter.c * * Purpose: * Implement a Fixed-Point filter. * * Comments: * * Structure type: IIR Cascaded Second Order Sections Form II Transposed * * Fixed-Point Models: * * CoefficientB Quantizer: * Word Length: 16 * Integer Word Length: -5 * Overflow Mode: Saturation * Round-off Mode: Nearest * * CoefficientA Quantizer: * Word Length: 16 * Integer Word Length: 1 * Overflow Mode: Saturation * Round-off Mode: Nearest * * Input Quantizer: * Word Length: 16 * Integer Word Length: 1 * Overflow Mode: Saturation * Round-off Mode: Nearest * * Output Quantizer: * Word Length: 16 * Integer Word Length: 2 * Overflow Mode: Wrap * Round-off Mode: Truncation * * Multiplicand Quantizer: * Word Length: 32 * Integer Word Length: 2 * Overflow Mode: Wrap * Round-off Mode: Truncation * * Product Quantizer: * Word Length: 32 * Integer Word Length: 2 * Overflow Mode: Wrap * Round-off Mode: Truncation * * Sum Quantizer: * Word Length: 32 * Integer Word Length: 2 * Overflow Mode: Wrap * Round-off Mode: Truncation * * Delay Quantizer: * Word Length: 32 * Integer Word Length: 2 * Overflow Mode: Wrap * Round-off Mode: Truncation * * * Copyright 2008 National Instruments Corporation. All rights reserved. * ==================================================================== */ #include "filter.h" /* ---- Constants ----*/ #define FILTER_N_SECTIONS 1 #define FILTER_N_STATES (2*FILTER_N_SECTIONS) #define FILTER_N_COEFA (2*FILTER_N_SECTIONS) #define FILTER_N_COEFB (3*FILTER_N_SECTIONS) /* ---- Global Variables Declaration ----*/ static I16 filter_CoefA[FILTER_N_COEFA]; static I16 filter_CoefB[FILTER_N_COEFB]; static I32 filter_MultB(I32 x, I16 coef); static I32 filter_MultA(I32 x, I16 coef); /* ---- SHFT Define ---- */ #define IN2SUM 15 /* IN2SUM LeftShift 15 */ #define SUM2OUT 16 /* SUM2OUT RightShift 16 */ /* ---- Create State of filter ---- */ filter_State filter_CreateState ( ) { filter_State state = NULL; state = (filter_State)malloc(sizeof(I32) * FILTER_N_STATES); return state; } /* ---- Dispose State of filter ---- */ void filter_DisposeState (filter_State state) { free(state); return; } /* ---- Initialize the State of filter ---- */ void filter_InitState(filter_State state) { int i; for (i=0; i < FILTER_N_STATES; i++) state[i] = 0; return; } /* ---- Implement the Fixed-Point Filter ---- */ I16 filter_Filtering (I16 sampleIn, filter_State state) { I32 accA, accB; I32 mult_a, mult_b; int i; int iA, iB; accA = ((I32)sampleIn << IN2SUM); iA = iB = 0; for (i=0; i < FILTER_N_SECTIONS; i++) { mult_b = accA; /* Filtering */ accA = filter_MultB(mult_b, filter_CoefB[iB++]); accA += state[iA]; mult_a = accA; /* Update the internal states */ accB = state[iA+1]; accB += filter_MultB(mult_b, filter_CoefB[iB++]); accB -= filter_MultA(mult_a, filter_CoefA[iA]); state[iA++] = accB; accB = filter_MultB(mult_b, filter_CoefB[iB++]); accB -= filter_MultA(mult_a, filter_CoefA[iA]); state[iA++] = accB; } accA = (accA >> SUM2OUT); return (I16)accA; } /* ---- Internal Functions ---- */ /* ==================================================================== * Fixed-Point Multiplication: * x * coef => prod * Q2.30 * Q-5.21 => Q2.30 * ==================================================================== */ static I32 filter_MultB(I32 x, I16 coef) { I32 prod; prod = (x >> 16) * coef; prod = (prod + (((x & 0xffff) * coef) >> 16)) >> 5; return prod; } /* ==================================================================== * Fixed-Point Multiplication: * x * coef => prod * Q2.30 * Q1.15 => Q2.30 * ==================================================================== */ static I32 filter_MultA(I32 x, I16 coef) { I32 prod; prod = ((x >> 16) * coef) << 1; prod += ((x & 0xffff) * coef) >> 15; return prod; } /* ---- Filter Coefficients ---- */ static I16 filter_CoefA [] = { -32197, 0 }; static I16 filter_CoefB [] = { 18287, 18287, 0 };
25.79602
80
0.460559