blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
d20d1b7d64e6531fa8c3d85a7da6ed8475b3ede5
3ecb1e2ec69baa9f8b3f02b606d06d92cd05bf33
/include/psp2kern/kernel/systimer.h
9cb2d08d49a931d05e58decf6155fc09bee21100
[ "MIT" ]
permissive
vitasdk/vita-headers
f66f3b06443ce1c4f7857e5d15fa8d40cd048374
8ea6dc183be93f4d7848a6f452a6b4759dfedfbc
refs/heads/master
2023-09-03T08:56:23.567294
2023-09-02T20:16:21
2023-09-03T01:42:19
40,744,530
247
451
MIT
2023-09-13T07:05:10
2015-08-15T02:57:40
C
UTF-8
C
false
false
3,715
h
systimer.h
/** * \kernelgroup{SceSystimer} * \usage{psp2kern/kernel/systimer.h,SceSystimerForDriver_stub} */ #ifndef _PSP2KERN_SYSTIMER_H_ #define _PSP2KERN_SYSTIMER_H_ #include <vitasdk/build_utils.h> #include <psp2kern/types.h> #ifdef __cplusplus extern "C" { #endif typedef SceInt32 SceSysTimerId; VITASDK_BUILD_ASSERT_EQ(4, SceSysTimerId); typedef void (*SceSysTimerCallback)(SceSysTimerId timer, void* pUserData); typedef enum SceSysTimerType { SCE_SYSTIMER_TYPE_LONG = 1, //!< 64-bit timer SCE_SYSTIMER_TYPE_WORD = 2 //!< 32-bit timer } SceSysTimerType; typedef enum SceSysTimerClockSource { SCE_SYSTIMER_CLOCK_SOURCE_SYS = 0, //!< 190/222MHz Frequency. Controlled by kscePower[Get|Set]SysClockFrequency SCE_SYSTIMER_CLOCK_SOURCE_48MHZ = 3, //!< 48MHz Frequency. Used by GpuEs4 and Threadmgr timers } SceSysTimerClockSource; /** * @brief Allocate one of the system's timers. * * @param timerType - One of ::SceSysTimerType. * * @return The id of the new timer on success, < 0 on error. */ SceSysTimerId ksceKernelSysTimerAlloc(SceSysTimerType timerType); /** * @brief Free an allocated system timer * * @param timerId - The timer to free. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerFree(SceSysTimerId timerId); /** * @brief Start a timer. * * @param timerId - The target timer. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerStartCount(SceSysTimerId timerId); /** * @brief Stop a timer. * * @param timerId - The target timer. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerStopCount(SceSysTimerId timerId); /** * @brief Configure the source clock signal for a timer. * * @par The final input clock is determined as such: * @code * inputClock = sourceClock / (prescaleFactor + 1) * @endcode * * @param timerId - The target timer. * @param clockSource - The source of the clock signal. * @param prescaleFactor - The prescale factor applied to the clock signal. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerSetClockSource(SceSysTimerId timerId, SceSysTimerClockSource clockSource, SceUInt8 prescaleFactor); /** * @brief Set the timer interval. * * The interval determines the count at which the timer will overflow to 0, and an interrupt will be fired. * * @param timerId - The target timer. * @param interval - The timer interval. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerSetInterval(SceSysTimerId timerId, SceKernelSysClock interval); /** * @brief Set the interrupt callback handler for the timer. * * @param timerId - The target timer. * @param callback - The callback function. * @param targetCPU - The CPU cores the interrupt can be handled from. * @param pUserData - User data to be passed to the callback. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerSetHandler(SceSysTimerId timerId, SceSysTimerCallback callback, SceUInt32 targetCPU, void *pUserData); /** * @brief Get the timer count value. * * @param timerId - The target timer. * @param pCount - The variable to store the count to. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerGetCount(SceSysTimerId timerId, SceKernelSysClock *pCount); /** * @brief Set the timer count value. * * @param timerId - The target timer. * @param count - The count to set. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerSetCount(SceSysTimerId timerId, SceKernelSysClock count); /** * @brief Reset the timer count. * * @param timerId - The target timer. * * @return 0 on success, < 0 on error. */ int ksceKernelSysTimerResetCount(SceSysTimerId timerId); #ifdef __cplusplus } #endif #endif
d6cf3161daf381283bd2a798ca3e26f311d6e902
1efb2283837c9b70bc6449cec877799e4efa3268
/test/mpi/coll/allgather_struct.c
4929b34276bf106504c4f8170c4bf77546ae9b47
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
1,928
c
allgather_struct.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include <stdlib.h> #include "mpi.h" #include "mpitest.h" /* Allgather a two-field struct datatype. This test may trigger bugs such as when the implementation does not handle well misaligned types.*/ typedef struct { int first; long second; } int_long_t; int main(int argc, char **argv) { MPI_Comm comm; int minsize = 2; int i, errs = 0; int rank, size; int_long_t object; MPI_Datatype type; MPI_Aint begin; MPI_Aint displacements[2]; MPI_Datatype types[] = { MPI_INT, MPI_LONG }; int blocklength[2] = { 1, 1 }; int_long_t *gathered_objects; MTest_Init(&argc, &argv); while (MTestGetIntracommGeneral(&comm, minsize, 1)) { if (comm == MPI_COMM_NULL) continue; /* Determine the sender and receiver */ MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); gathered_objects = (int_long_t *) malloc(size * sizeof(int_long_t)); /* Local object */ object.first = rank; object.second = rank * 10; /* Datatype creation */ MPI_Get_address(&object, &begin); MPI_Get_address(&object.first, &displacements[0]); MPI_Get_address(&object.second, &displacements[1]); for (i = 0; i != 2; ++i) displacements[i] -= begin; MPI_Type_create_struct(2, &blocklength[0], &displacements[0], &types[0], &type); MPI_Type_commit(&type); MPI_Allgather(&object, 1, type, gathered_objects, 1, type, comm); for (i = 0; i < size; i++) { if (gathered_objects[i].first != i || gathered_objects[i].second != i * 10) errs++; } MPI_Type_free(&type); MTestFreeComm(&comm); free(gathered_objects); } MTest_Finalize(errs); return MTestReturnValue(errs); }
a6f6a1b872b6021224644165a41eb58e256841fc
b9dc55919b29da24c24f8ee367c5618c9532f56f
/Code_source/Compiled/signal/sfz~/sfizz/library/external/st_audiofile/thirdparty/dr_libs/tests/external/miniaudio/tests/test_common/ma_test_common.c
c6b8d7cf437c349005246d8a8fc04a2d18638699
[ "BSD-3-Clause", "MIT-0", "ISC", "BSL-1.0", "Apache-2.0", "LGPL-2.0-or-later", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LGPL-2.1-only", "WTFPL", "MIT", "Unlicense", "LicenseRef-scancode-unknown-license-reference" ]
permissive
porres/pd-else
075e8b7ac7a78f442055fbd30d6602cae49c887e
b30e8c13c88bb9752c08f78514d64c6206d6678b
refs/heads/master
2023-08-18T22:26:31.120893
2023-08-18T00:46:59
2023-08-18T00:46:59
56,870,805
238
42
WTFPL
2023-09-12T15:55:56
2016-04-22T16:45:29
C
UTF-8
C
false
false
1,789
c
ma_test_common.c
#define DR_FLAC_IMPLEMENTATION #include "../../extras/dr_flac.h" #define DR_MP3_IMPLEMENTATION #include "../../extras/dr_mp3.h" #define DR_WAV_IMPLEMENTATION #include "../../extras/dr_wav.h" /* Make sure we include the Speex resampler so we can test it. */ #define MINIAUDIO_SPEEX_RESAMPLER_IMPLEMENTATION #include "../../extras/speex_resampler/ma_speex_resampler.h" #define MINIAUDIO_IMPLEMENTATION #include "../../miniaudio.h" #include <stdio.h> #define MAX_TESTS 64 #define TEST_OUTPUT_DIR "res/output" typedef int (* ma_test_entry_proc)(int argc, char** argv); typedef struct { const char* pName; ma_test_entry_proc onEntry; } ma_test; static struct { ma_test pTests[MAX_TESTS]; size_t count; } g_Tests; ma_result ma_register_test(const char* pName, ma_test_entry_proc onEntry) { MA_ASSERT(pName != NULL); MA_ASSERT(onEntry != NULL); if (g_Tests.count >= MAX_TESTS) { printf("Failed to register test %s because there are too many tests already registered. Increase the value of MAX_TESTS\n", pName); return MA_INVALID_OPERATION; } g_Tests.pTests[g_Tests.count].pName = pName; g_Tests.pTests[g_Tests.count].onEntry = onEntry; g_Tests.count += 1; return MA_SUCCESS; } drwav_data_format drwav_data_format_from_minaudio_format(ma_format format, ma_uint32 channels, ma_uint32 sampleRate) { drwav_data_format wavFormat; wavFormat.container = drwav_container_riff; wavFormat.channels = channels; wavFormat.sampleRate = sampleRate; wavFormat.bitsPerSample = ma_get_bytes_per_sample(format) * 8; if (format == ma_format_f32) { wavFormat.format = DR_WAVE_FORMAT_IEEE_FLOAT; } else { wavFormat.format = DR_WAVE_FORMAT_PCM; } return wavFormat; }
759d19ef088cd5eb695c16ce212ca821b93a3ee5
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGHF/vertexingHF/charmFlow/DmesonsFlowYieldSyst.C
332df9a173712e29358a4289048f600a2264752b
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
66,953
c
DmesonsFlowYieldSyst.C
#if !defined(__CINT__) || defined(__MAKECINT__) #include <Riostream.h> #include <TFile.h> #include <TString.h> #include <TH2F.h> #include <TH1F.h> #include <TF1.h> #include <TGraph.h> #include <TGraphErrors.h> #include <TGraphAsymmErrors.h> #include <TMultiGraph.h> #include <TDirectoryFile.h> #include <TList.h> #include <TCanvas.h> #include <TLegend.h> #include <TLegendEntry.h> #include <TPaveText.h> #include <TPaveStats.h> #include <TStyle.h> #include <TASImage.h> #include <TPad.h> #include <TROOT.h> #include <TDatabasePDG.h> #include <TParameter.h> #include <TLatex.h> #include <TLine.h> #include <TSystem.h> #include "AliHFMassFitter.h" #include "AliHFMassFitterVAR.h" #include "AliRDHFCutsD0toKpi.h" #include "AliRDHFCutsDstoKKpi.h" #include "AliVertexingHFUtils.h" #include "AliRDHFCutsDplustoKpipi.h" #include "AliRDHFCutsDStartoKpipi.h" #include "AliEventPlaneResolutionHandler.h" #include "AliVertexingHFUtils.h" #endif //methods for the extraction yield systematics for the v2 computed with the Event Plane method //Author: Fabrizio Grosa, INFN Turin grosa@to.infn.it //*************************************************// // // // Main Function: DmesonsFlowYieldSyst() // // // //*************************************************// //_________________________________________________________________ //GLOBAL VARIABLES TO BE SET //input file const TString filename="$HOME/cernbox/ALICE_WORK/Files/Trains/Run2/LHC15o/AnalysisResults_v2_3050_step2_EP_VZERO.root"; const TString suffix="_Topod0Cut_VZERO_EP"; const TString partname="Dplus"; const Int_t minCent=30; const Int_t maxCent=50; const TString outputdir = "Cent3050/v2"; //EP resolution //kTPCFullEta, kTPCPosEta,kVZERO,kVZEROA,kVZEROC const Int_t evPlane=AliEventPlaneResolutionHandler::kVZERO; //resolution flag fromAliEventPlaneResolutionHandler: //kTwoRandSub,kTwoChargeSub,kTwoEtaSub,kThreeSub,kThreeSubTPCGap const Bool_t useAliHandlerForRes=kFALSE; Int_t evPlaneRes=AliEventPlaneResolutionHandler::kThreeSub; const Bool_t useNcollWeight=kFALSE; // pt and phi binning const Int_t nptbinsnew=10; const Double_t ptbinsnew[nptbinsnew+1]={2.,3.,4.,5.,6.,7.,8.,10.,12.,16.,24.}; //const Int_t nptbinsnew=16; //const Double_t ptbinsnew[nptbinsnew+1]={2.,2.5,3.,3.5,4.,4.5,5.,5.5,6.,6.5,7.,7.5,8.,10.,12.,16.,24.}; const Int_t nphibins=4; const Double_t phibinslim[nphibins+1]={0,TMath::Pi()/4,TMath::Pi()/2,3*TMath::Pi()/4,TMath::Pi()}; // mass fit configuration const Int_t nReb=5; const Int_t rebin[nptbinsnew]={2,3,4,5,6}; enum {kGaus=0, kDoubleGaus, kReflTempl}; const Int_t types=kGaus; const Int_t nBkgFcn=3; const Int_t typeb[nBkgFcn]={AliHFMassFitter::kExpo,AliHFMassFitter::kPol2,AliHFMassFitter::kLin}; const Int_t nMins=5; const Double_t minMassForFit[nMins]={1.66,1.68,1.70,1.72,1.76}; const Int_t nMaxs=5; const Double_t maxMassForFit[nMaxs]={2.08,2.06,2.04,2.02,2.00}; const Double_t nSigmaForCounting=3.5; const Bool_t fixAlsoMass=kFALSE; const Double_t maxchi=2.0; Bool_t useTemplD0Refl=kFALSE; TString rflFitType="DoubleGaus"; TString fileNameMCD0refl="../reflections/reflections_fitted_DoubleGaus.root"; //not to be set Int_t minPtBin[nptbinsnew]={-1,-1,-1,-1}; Int_t maxPtBin[nptbinsnew]={-1,-1,-1,-1}; const Double_t effInOverEffOut=1.03; Double_t massD; const Int_t colors[] = {kRed+1,kBlack,kBlue+1,kGreen+2,kOrange+7,kBlue-7}; const Int_t markers[] = {kFullSquare,kFullCircle,kFullTriangleUp,kFullDiamond,kOpenSquare,kOpenCircle,kOpenTriangleUp,kOpenDiamond}; //_________________________________________________________________ //METHODS PROTOTYPES Int_t DmesonsFlowYieldSyst(Bool_t inoutanis=kTRUE); TList *LoadMassHistos(TList *inputlist,Bool_t inoutanis); TList* LoadResolutionHistos(TList *inputlist); Int_t FindPtBin(Int_t nbins, Double_t* array,Double_t value); void FillSignalGraph(TList *histlist,TGraphAsymmErrors **gSignal,TGraphAsymmErrors **gSignalfs, TGraphAsymmErrors **gSignalBC1, TGraphAsymmErrors **gSignalBC2,TGraphAsymmErrors **gSigmaFree,TGraphAsymmErrors **gSigmaFixed, TGraphAsymmErrors **gChiSquareFree, TGraphAsymmErrors **gChiSquareFixed, Bool_t inoutanis, Int_t bkgfunc, Double_t minfit, Double_t maxfit, Int_t rebin); TGraphAsymmErrors* Computev2(TGraphAsymmErrors **gSignal, Double_t resol, Float_t *averagePt, Bool_t inoutanis, TGraphAsymmErrors *gRelSystEff); Double_t GetEventPlaneResolution(Double_t& error, TH1F* hsubev1, TH1F* hsubev2, TH1F* hsubev3); Bool_t DefinePtBins(AliRDHFCuts *cutobj); Int_t LoadRefGraphs(TString reffilename, TH1F **hRawYieldRef, TH1F **hRawYieldfsRef, TH1F **hRawYieldBC1Ref, TH1F **hRawYieldBC2Ref, TGraphAsymmErrors *&gv2Ref, TGraphAsymmErrors *&gv2fsRef, TGraphAsymmErrors *&gv2BC1Ref, TGraphAsymmErrors *&gv2BC2Ref, Bool_t inoutanis); void GetMinMaxHisto(TH1F* histo, Double_t &xmin, Double_t &xmax); void DivideCanvas(TCanvas* c, Int_t nPtBins); void SetStyle(Int_t optfit=0); Bool_t LoadD0toKpiMCHistos(TList *outlist); //_________________________________________________________________ //METHODS IMPLEMENTATION Int_t DmesonsFlowYieldSyst(Bool_t inoutanis){ TString workdir=gSystem->pwd(); if(!gSystem->cd(outputdir.Data())) {gSystem->mkdir(outputdir.Data());} else {gSystem->cd(workdir.Data());} TString dirname=Form("PWGHF_D2H_HFv2_%s%s",partname.Data(),suffix.Data()); TString listname=Form("coutputv2%s%s",partname.Data(),suffix.Data()); AliRDHFCuts *cutsobj=0x0; //Load input data from AliAnalysisTaskSEHFv2 TFile *f = TFile::Open(filename.Data()); if(!f){ printf("file %s not found, please check file name\n",filename.Data());return 1; } TDirectoryFile* dir=(TDirectoryFile*)f->Get(dirname.Data()); if(!dir){ printf("Directory %s not found, please check dir name\n",dirname.Data());return 2; } if(partname.Contains("Dzero")) { cutsobj=((AliRDHFCutsD0toKpi*)dir->Get(dir->GetListOfKeys()->At(2)->GetName())); massD=TDatabasePDG::Instance()->GetParticle(421)->Mass(); } if(partname.Contains("Dplus")){ cutsobj=((AliRDHFCutsDplustoKpipi*)dir->Get(dir->GetListOfKeys()->At(2)->GetName())); massD=TDatabasePDG::Instance()->GetParticle(411)->Mass(); } if(partname.Contains("Dstar")) { cutsobj=((AliRDHFCutsDStartoKpipi*)dir->Get(dir->GetListOfKeys()->At(2)->GetName())); massD=(TDatabasePDG::Instance()->GetParticle(413)->Mass() - TDatabasePDG::Instance()->GetParticle(421)->Mass()); } if(partname.Contains("Ds")) { cutsobj=((AliRDHFCutsDstoKKpi*)dir->Get(dir->GetListOfKeys()->At(2)->GetName())); massD=(TDatabasePDG::Instance()->GetParticle(431)->Mass()); } TList *list =(TList*)dir->Get(listname.Data()); if(!list){ printf("list %s not found in file, please check list name\n",listname.Data());return 3; } if(!cutsobj){ printf("cut object not found in file, please check keylist number\n");return 4; } //Define new pt bins if(!DefinePtBins(cutsobj)){ printf("cut not define pt bins\n");return 5; } //Load mass histograms corresponding to the required centrality, pt range and phi binning printf("Load mass histos \n"); TList *histlist=LoadMassHistos(list,inoutanis); Int_t nphi=nphibins; if(inoutanis)nphi=2; printf("average pt for pt bin \n"); //average pt for pt bin AliVertexingHFUtils *utils=new AliVertexingHFUtils(); Int_t minCentTimesTen=minCent*10; Int_t maxCentTimesTen=maxCent*10; TH2F* hmasspt=(TH2F*)list->FindObject(Form("hMPtCandcentr%d_%d",minCentTimesTen,minCentTimesTen+25)); for(Int_t icent=minCentTimesTen+25;icent<maxCentTimesTen;icent=icent+25)hmasspt->Add((TH2F*)list->FindObject(Form("hMPtCandcentr%d_%d",icent,icent+25))); Float_t averagePt[nptbinsnew]; Float_t errorPt[nptbinsnew]; for(Int_t ipt=0;ipt<nptbinsnew;ipt++){ Int_t binMin=hmasspt->FindBin(ptbinsnew[ipt]); Int_t binMax=hmasspt->FindBin(ptbinsnew[ipt+1]-0.001); if(TMath::Abs(hmasspt->GetXaxis()->GetBinLowEdge(binMin)-ptbinsnew[ipt])>0.001 || TMath::Abs(hmasspt->GetXaxis()->GetBinUpEdge(binMax)-ptbinsnew[ipt+1])>0.001){ printf("Error in pt bin limits for projection!\n"); return 6; } TH1F *histtofit = (TH1F*)hmasspt->ProjectionY("_py",binMin,binMax); Int_t nMassBins=histtofit->GetNbinsX(); Double_t hmin=histtofit->GetBinLowEdge(2); // need wide range for <pt> Double_t hmax=histtofit->GetBinLowEdge(nMassBins-2); // need wide range for <pt> //AliHFMassFitter fitter(histtofit,hmin,hmax,1); AliHFMassFitterVAR *fitter=new AliHFMassFitterVAR(histtofit,hmin,hmax,1,typeb[0],types); if(useTemplD0Refl){ Printf("USE TEMPLATE FOR AVERAGE Pt"); TH1F *hrflTempl=(TH1F*)(histlist->FindObject(Form("histRfl_%d",ipt)))->Clone(Form("histrfl_%d",ipt)); if(!hrflTempl) {Printf("histRfl_%d not found",ipt); return 7;} TH1F *hsigMC=(TH1F*)(histlist->FindObject(Form("histSgn_%d",ipt)))->Clone(Form("histsgn_%d",ipt)); if(!hsigMC) {Printf("histSgn_%d not found",ipt); return 8;} fitter->SetTemplateReflections(hrflTempl); Float_t sOverRef=(hrflTempl->Integral(hrflTempl->FindBin(hmin*1.0001),hrflTempl->FindBin(hmax*0.999)))/(hsigMC->Integral(hsigMC->FindBin(hmin*1.0001),hsigMC->FindBin(hmax*0.999))); Printf("R OVER S = %f",sOverRef); fitter->SetFixReflOverS(sOverRef,kTRUE); } fitter->MassFitter(kFALSE); Double_t massFromFit=fitter->GetMean(); Double_t sigmaFromFit=fitter->GetSigma(); TF1* funcB2=fitter->GetBackgroundRecalcFunc(); utils->AveragePt(averagePt[ipt],errorPt[ipt],ptbinsnew[ipt],ptbinsnew[ipt+1],hmasspt,massFromFit,sigmaFromFit,funcB2,2.5,4.5,0.,3.,1); } printf("Average pt\n"); for(Int_t ipt=0;ipt<nptbinsnew;ipt++) printf("%f +- %f\n",averagePt[ipt],errorPt[ipt]); printf("Fill TGraphs for signal \n"); //Fill TGraphs for signal TGraphAsymmErrors *gSignal[nptbinsnew]; TGraphAsymmErrors *gSignalfs[nptbinsnew]; TGraphAsymmErrors *gSignalBC1[nptbinsnew]; TGraphAsymmErrors *gSignalBC2[nptbinsnew]; TGraphAsymmErrors *gSigmaFree[nptbinsnew]; TGraphAsymmErrors *gSigmaFixed[nptbinsnew]; TGraphAsymmErrors *gChiSquareFree[nptbinsnew]; TGraphAsymmErrors *gChiSquareFixed[nptbinsnew]; for(Int_t i=0;i<nptbinsnew;i++){ gSignal[i]=new TGraphAsymmErrors(nphi); gSignal[i]->SetName(Form("gasigpt%d",i)); gSignal[i]->SetTitle(Form("Signal %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gSignal[i]->SetMarkerStyle(25); gSignalfs[i]=new TGraphAsymmErrors(nphi); gSignalfs[i]->SetName(Form("gasigfspt%d",i)); gSignalfs[i]->SetTitle(Form("Signal (fixed sigma) %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gSignalfs[i]->SetMarkerStyle(21); gSignalBC1[i]=new TGraphAsymmErrors(nphi); gSignalBC1[i]->SetName(Form("gasigBC1pt%d",i)); gSignalBC1[i]->SetTitle(Form("Signal (BC1) %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gSignalBC2[i]=new TGraphAsymmErrors(nphi); gSignalBC2[i]->SetName(Form("gasigBC2pt%d",i)); gSignalBC2[i]->SetTitle(Form("Signal (BC2) %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gSigmaFree[i]=new TGraphAsymmErrors(nphi); gSigmaFree[i]->SetName(Form("gasigmafree%d",i)); gSigmaFree[i]->SetTitle(Form("Sigma free %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gSigmaFixed[i]=new TGraphAsymmErrors(nphi); gSigmaFixed[i]->SetName(Form("gasigmafixed%d",i)); gSigmaFixed[i]->SetTitle(Form("Sigma fixed %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gChiSquareFree[i]=new TGraphAsymmErrors(nphi); gChiSquareFree[i]->SetName(Form("gachifree%d",i)); gChiSquareFree[i]->SetTitle(Form("ChiSquare free %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); gChiSquareFixed[i]=new TGraphAsymmErrors(nphi); gChiSquareFixed[i]->SetName(Form("gachifixed%d",i)); gChiSquareFixed[i]->SetTitle(Form("ChiSquare fixed %.1f < #it{p}_{T} < %.1f GeV/c;#Delta#phi bin;Counts",ptbinsnew[i],ptbinsnew[i+1])); } //EP resolution Double_t resol=-1.; Double_t errorres=-1.; if(useAliHandlerForRes) { AliEventPlaneResolutionHandler* epres=new AliEventPlaneResolutionHandler(); epres->SetEventPlane(evPlane); epres->SetResolutionOption(evPlaneRes); if(useNcollWeight) epres->SetUseNcollWeights(); resol=epres->GetEventPlaneResolution(minCent,maxCent); delete epres; } else { TList* resolhist=LoadResolutionHistos(list); TString suffixcentr=Form("centr%d_%d",minCent,maxCent); TH1F* hevplresos[3]; TString namereso[3]={"Reso","Reso2","Reso3"}; Int_t nSubRes=1; TH1F* htestversion=(TH1F*)resolhist->FindObject(Form("hEvPlane%s%s",namereso[0].Data(),suffixcentr.Data())); if(htestversion){ printf("Old version of the task\n"); }else{ printf("New version of the task\n"); namereso[0]="Reso1"; } if(evPlaneRes==AliEventPlaneResolutionHandler::kThreeSub|| evPlaneRes==AliEventPlaneResolutionHandler::kThreeSubTPCGap)nSubRes=3; for(Int_t ires=0;ires<nSubRes;ires++){ hevplresos[ires]=(TH1F*)resolhist->FindObject(Form("hEvPlane%s%s",namereso[ires].Data(),suffixcentr.Data())); } resol=GetEventPlaneResolution(errorres,hevplresos[0],hevplresos[1],hevplresos[2]); } SetStyle(); printf("Event plane resolution %f\n",resol); printf("Compute v2 \n"); //compute v2 TString fine=""; if(nptbinsnew>=15) fine="_fineptbin"; TString aniss=""; if(nphi==2) aniss+="anis"; //load reference graphs TGraphAsymmErrors* gv2Ref=0x0; TGraphAsymmErrors* gv2fsRef=0x0; TGraphAsymmErrors* gv2BC1Ref=0x0; TGraphAsymmErrors* gv2BC2Ref=0x0; TH1F** hRawYieldRef = new TH1F*[nphi]; TH1F** hRawYieldfsRef = new TH1F*[nphi]; TH1F** hRawYieldBC1Ref = new TH1F*[nphi]; TH1F** hRawYieldBC2Ref = new TH1F*[nphi]; TString reffilename = Form("%s/v2Output_%d_%d_%s%s%s.root",outputdir.Data(),minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data()); Int_t loadref=LoadRefGraphs(reffilename, hRawYieldRef, hRawYieldfsRef, hRawYieldBC1Ref, hRawYieldBC2Ref, gv2Ref, gv2fsRef, gv2BC1Ref, gv2BC2Ref, inoutanis); if(loadref>0) {return 7;} TCanvas *cv2 =new TCanvas("cv2","v2 - systematic on yield extraction",1920,1080); DivideCanvas(cv2,nptbinsnew); TCanvas *cv2VsTrial =new TCanvas("cv2VsTrial","v2 vs. Trial - systematic on yield extraction",1920,1080); DivideCanvas(cv2VsTrial,nptbinsnew); TH1F** hv2 = new TH1F*[nptbinsnew]; TH1F** hv2fs = new TH1F*[nptbinsnew]; TH1F** hv2BC1 = new TH1F*[nptbinsnew]; TH1F** hv2BC2 = new TH1F*[nptbinsnew]; TH1F** hv2VsTrial = new TH1F*[nptbinsnew]; TH1F** hv2fsVsTrial = new TH1F*[nptbinsnew]; TH1F** hv2BC1VsTrial = new TH1F*[nptbinsnew]; TH1F** hv2BC2VsTrial = new TH1F*[nptbinsnew]; TCanvas** cRawYield=new TCanvas*[nphi]; TCanvas** cSigma=new TCanvas*[nphi]; TCanvas** cChiSquare=new TCanvas*[nphi]; TH1F*** hRawYield=new TH1F**[nphi]; TH1F*** hRawYieldfs=new TH1F**[nphi]; TH1F*** hRawYieldBC1=new TH1F**[nphi]; TH1F*** hRawYieldBC2=new TH1F**[nphi]; TH1F*** hSigmaFixed=new TH1F**[nphi]; TH1F*** hSigmaFree=new TH1F**[nphi]; TH1F*** hChiSquareFixed=new TH1F**[nphi]; TH1F*** hChiSquareFree=new TH1F**[nphi]; for(Int_t iPhi=0; iPhi<nphi; iPhi++) { hRawYield[iPhi]=new TH1F*[nptbinsnew]; hRawYieldfs[iPhi]=new TH1F*[nptbinsnew]; hRawYieldBC1[iPhi]=new TH1F*[nptbinsnew]; hRawYieldBC2[iPhi]=new TH1F*[nptbinsnew]; hSigmaFree[iPhi]=new TH1F*[nptbinsnew]; hSigmaFixed[iPhi]=new TH1F*[nptbinsnew]; hChiSquareFree[iPhi]=new TH1F*[nptbinsnew]; hChiSquareFixed[iPhi]=new TH1F*[nptbinsnew]; cRawYield[iPhi]=new TCanvas(Form("cRawYield_phi%d",iPhi),"Y - systematic on yield extraction",1920,1080); cSigma[iPhi]=new TCanvas(Form("cSigma_phi%d",iPhi),"Y - systematic on yield extraction",1920,1080); cChiSquare[iPhi]=new TCanvas(Form("cChiSquare_phi%d",iPhi),"Y - systematic on yield extraction",1920,1080); DivideCanvas(cRawYield[iPhi],nptbinsnew); DivideCanvas(cSigma[iPhi],nptbinsnew); DivideCanvas(cChiSquare[iPhi],nptbinsnew); } TH1F** hv2Syst = new TH1F*[nptbinsnew]; TH1F** hv2fsSyst = new TH1F*[nptbinsnew]; TH1F** hv2BC1Syst = new TH1F*[nptbinsnew]; TH1F** hv2BC2Syst = new TH1F*[nptbinsnew]; TH1F** hv2Syst2 = new TH1F*[nptbinsnew]; TH1F** hv2fsSyst2 = new TH1F*[nptbinsnew]; TH1F** hv2BC1Syst2 = new TH1F*[nptbinsnew]; TH1F** hv2BC2Syst2 = new TH1F*[nptbinsnew]; TH1F* hSyst1 = new TH1F("hSyst1","",nptbinsnew,ptbinsnew); hSyst1->SetLineWidth(2); hSyst1->SetStats(kFALSE); hSyst1->SetLineColor(colors[1]); hSyst1->GetYaxis()->SetTitle("#sqrt{RMS^{2} + shift^{2}} (fixed sigma)"); hSyst1->GetYaxis()->SetTitleOffset(1.4); hSyst1->GetXaxis()->SetTitle("#it{p}_{T} (GeV/c)"); const Int_t nbins=50; const Int_t nTrials=nReb*nMins*nMaxs*nBkgFcn; for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { Double_t v2staterr = gv2fsRef->GetErrorY(iPt); hv2[iPt] = new TH1F(Form("hv2_%d",iPt),"",nbins,-3*v2staterr,3*v2staterr); hv2fs[iPt] = new TH1F(Form("hv2fs_%d",iPt),"",nbins,-3*v2staterr,3*v2staterr); hv2BC1[iPt] = new TH1F(Form("hv2BC1_%d",iPt),"",nbins,-3*v2staterr,3*v2staterr); hv2BC2[iPt] = new TH1F(Form("hv2BC2_%d",iPt),"",nbins,-3*v2staterr,3*v2staterr); hv2VsTrial[iPt] = new TH1F(Form("hv2VsTrial_%d",iPt),"",nTrials,-0.5,nTrials-0.5); hv2fsVsTrial[iPt] = new TH1F(Form("hv2fsVsTrial_%d",iPt),"",nTrials,-0.5,nTrials-0.5); hv2BC1VsTrial[iPt] = new TH1F(Form("hv2BC1VsTrial_%d",iPt),"",nTrials,-0.5,nTrials-0.5); hv2BC2VsTrial[iPt] = new TH1F(Form("hv2BC2VsTrial_%d",iPt),"",nTrials,-0.5,nTrials-0.5); hv2VsTrial[iPt]->SetStats(kFALSE); hv2fsVsTrial[iPt]->SetStats(kFALSE); hv2BC1VsTrial[iPt]->SetStats(kFALSE); hv2BC2VsTrial[iPt]->SetStats(kFALSE); hv2Syst[iPt] = new TH1F(Form("hv2Syst_%d",iPt),"",4,-0.5,3.5); hv2fsSyst[iPt] = new TH1F(Form("hv2fsSyst_%d",iPt),"",4,-0.5,3.5); hv2BC1Syst[iPt] = new TH1F(Form("hv2BC1Syst_%d",iPt),"",4,-0.5,3.5); hv2BC2Syst[iPt] = new TH1F(Form("hv2BC2Syst_%d",iPt),"",4,-0.5,3.5); hv2Syst[iPt]->SetStats(kFALSE); hv2fsSyst[iPt]->SetStats(kFALSE); hv2BC1Syst[iPt]->SetStats(kFALSE); hv2BC2Syst[iPt]->SetStats(kFALSE); hv2Syst2[iPt] = new TH1F(Form("hv2Syst2_%d",iPt),"",4,-0.4,3.6); hv2fsSyst2[iPt] = new TH1F(Form("hv2fsSyst2_%d",iPt),"",4,-0.4,3.6); hv2BC1Syst2[iPt] = new TH1F(Form("hv2BC1Syst2_%d",iPt),"",4,-0.4,3.6); hv2BC2Syst2[iPt] = new TH1F(Form("hv2BC2Syst2_%d",iPt),"",4,-0.4,3.6); hv2Syst2[iPt]->SetStats(kFALSE); hv2fsSyst2[iPt]->SetStats(kFALSE); hv2BC1Syst2[iPt]->SetStats(kFALSE); hv2BC2Syst2[iPt]->SetStats(kFALSE); hv2[iPt]->GetXaxis()->SetTitle("v_{2}-v_{2}^{ref} {EP}"); hv2[iPt]->GetYaxis()->SetTitle("Entries"); hv2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2fs[iPt]->GetXaxis()->SetTitle("v_{2}-v_{2}^{ref} {EP}"); hv2fs[iPt]->GetYaxis()->SetTitle("Entries"); hv2fs[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC1[iPt]->GetXaxis()->SetTitle("v_{2}-v_{2}^{ref} {EP}"); hv2BC1[iPt]->GetYaxis()->SetTitle("Entries"); hv2BC1[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC2[iPt]->GetXaxis()->SetTitle("v_{2}-v_{2}^{ref} {EP}"); hv2BC2[iPt]->GetYaxis()->SetTitle("Entries"); hv2BC2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2[iPt]->SetLineColor(colors[0]); hv2fs[iPt]->SetLineColor(colors[1]); hv2BC1[iPt]->SetLineColor(colors[2]); hv2BC2[iPt]->SetLineColor(colors[3]); hv2VsTrial[iPt]->GetYaxis()->SetTitle("v_{2} {EP}"); hv2VsTrial[iPt]->GetXaxis()->SetTitle("Trial #"); hv2VsTrial[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2fsVsTrial[iPt]->GetYaxis()->SetTitle("v_{2} {EP}"); hv2fsVsTrial[iPt]->GetXaxis()->SetTitle("Trial #"); hv2fsVsTrial[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC1VsTrial[iPt]->GetYaxis()->SetTitle("v_{2} {EP}"); hv2BC1VsTrial[iPt]->GetXaxis()->SetTitle("Trial #"); hv2BC1VsTrial[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC2VsTrial[iPt]->GetYaxis()->SetTitle("v_{2} {EP}"); hv2BC2VsTrial[iPt]->GetXaxis()->SetTitle("Trial #"); hv2BC2VsTrial[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2VsTrial[iPt]->SetLineColor(colors[0]); hv2fsVsTrial[iPt]->SetLineColor(colors[1]); hv2BC1VsTrial[iPt]->SetLineColor(colors[2]); hv2BC2VsTrial[iPt]->SetLineColor(colors[3]); hv2VsTrial[iPt]->SetMarkerColor(colors[0]); hv2fsVsTrial[iPt]->SetMarkerColor(colors[1]); hv2BC1VsTrial[iPt]->SetMarkerColor(colors[2]); hv2BC2VsTrial[iPt]->SetMarkerColor(colors[3]); hv2VsTrial[iPt]->SetMarkerSize(0.5); hv2fsVsTrial[iPt]->SetMarkerSize(0.5); hv2BC1VsTrial[iPt]->SetMarkerSize(0.5); hv2BC2VsTrial[iPt]->SetMarkerSize(0.5); hv2Syst[iPt]->GetYaxis()->SetTitle("MEAN v_{2}-v_{2}^{ref}"); hv2Syst[iPt]->GetYaxis()->SetTitleOffset(1.5); hv2Syst[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2fsSyst[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2fsSyst[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC1Syst[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2BC1Syst[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC2Syst[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2BC2Syst[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2Syst[iPt]->SetLineColor(colors[0]); hv2fsSyst[iPt]->SetLineColor(colors[1]); hv2BC1Syst[iPt]->SetLineColor(colors[2]); hv2BC2Syst[iPt]->SetLineColor(colors[3]); hv2Syst[iPt]->SetMarkerColor(colors[0]); hv2fsSyst[iPt]->SetMarkerColor(colors[1]); hv2BC1Syst[iPt]->SetMarkerColor(colors[2]); hv2BC2Syst[iPt]->SetMarkerColor(colors[3]); hv2Syst[iPt]->SetMarkerStyle(markers[0]); hv2fsSyst[iPt]->SetMarkerStyle(markers[1]); hv2BC1Syst[iPt]->SetMarkerStyle(markers[2]); hv2BC2Syst[iPt]->SetMarkerStyle(markers[3]); hv2Syst[iPt]->GetXaxis()->SetBinLabel(1,"free sigma"); hv2Syst[iPt]->GetXaxis()->SetBinLabel(2,"fixed sigma"); hv2Syst[iPt]->GetXaxis()->SetBinLabel(3,"BC1"); hv2Syst[iPt]->GetXaxis()->SetBinLabel(4,"BC2"); hv2Syst2[iPt]->GetYaxis()->SetTitle("MEAN v_{2}-v_{2}^{ref}"); hv2Syst2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2fsSyst2[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2fsSyst2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC1Syst2[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2BC1Syst2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2BC2Syst2[iPt]->GetYaxis()->SetTitle("v_{2} syst. uncertainty"); hv2BC2Syst2[iPt]->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[iPt],ptbinsnew[iPt+1])); hv2Syst2[iPt]->SetLineColor(colors[0]); hv2fsSyst2[iPt]->SetLineColor(colors[1]); hv2BC1Syst2[iPt]->SetLineColor(colors[2]); hv2BC2Syst2[iPt]->SetLineColor(colors[3]); hv2Syst2[iPt]->SetMarkerColor(colors[0]); hv2fsSyst2[iPt]->SetMarkerColor(colors[1]); hv2BC1Syst2[iPt]->SetMarkerColor(colors[2]); hv2BC2Syst2[iPt]->SetMarkerColor(colors[3]); hv2Syst2[iPt]->SetMarkerStyle(markers[4]); hv2fsSyst2[iPt]->SetMarkerStyle(markers[5]); hv2BC1Syst2[iPt]->SetMarkerStyle(markers[6]); hv2BC2Syst2[iPt]->SetMarkerStyle(markers[7]); for(Int_t iPhi=0; iPhi<nphi; iPhi++) { Double_t minraw=hRawYieldRef[iPhi]->GetBinContent(iPt+1)*(1-0.5); Double_t maxraw=hRawYieldRef[iPhi]->GetBinContent(iPt+1)*(1+0.5); hRawYield[iPhi][iPt] = new TH1F(Form("hRawYield_%d_%d",iPhi,iPt),"",nbins,minraw,maxraw); hRawYieldfs[iPhi][iPt] = new TH1F(Form("hRawYieldfs_%d_%d",iPhi,iPt),"",nbins,minraw,maxraw); hRawYieldBC1[iPhi][iPt] = new TH1F(Form("hRawYieldBC1_%d_%d",iPhi,iPt),"",nbins,minraw,maxraw); hRawYieldBC2[iPhi][iPt] = new TH1F(Form("hRawYieldBC2_%d_%d",iPhi,iPt),"",nbins,minraw,maxraw); hRawYield[iPhi][iPt]->GetXaxis()->SetTitle("raw yield"); hRawYield[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hRawYield[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hRawYieldfs[iPhi][iPt]->GetXaxis()->SetTitle("raw yield"); hRawYieldfs[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hRawYieldfs[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hRawYieldBC1[iPhi][iPt]->GetXaxis()->SetTitle("raw yield"); hRawYieldBC1[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hRawYieldBC1[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hRawYieldBC2[iPhi][iPt]->GetXaxis()->SetTitle("raw yield"); hRawYieldBC2[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hRawYieldBC2[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hRawYield[iPhi][iPt]->SetLineColor(colors[0]); hRawYieldfs[iPhi][iPt]->SetLineColor(colors[1]); hRawYieldBC1[iPhi][iPt]->SetLineColor(colors[2]); hRawYieldBC2[iPhi][iPt]->SetLineColor(colors[3]); hSigmaFree[iPhi][iPt] = new TH1F(Form("hSigmaFree_%d_%d",iPhi,iPt),"",nbins,0,0.025); hSigmaFree[iPhi][iPt]->GetXaxis()->SetTitle("width (GeV/c^{2})"); hSigmaFree[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hSigmaFree[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hSigmaFree[iPhi][iPt]->SetLineColor(colors[0]); hSigmaFixed[iPhi][iPt] = new TH1F(Form("hSigmaFixed_%d_%d",iPhi,iPt),"",nbins,0,0.025); hSigmaFixed[iPhi][iPt]->GetXaxis()->SetTitle("width (GeV/c^{2})"); hSigmaFixed[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hSigmaFixed[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hSigmaFixed[iPhi][iPt]->SetLineColor(colors[1]); hChiSquareFree[iPhi][iPt] = new TH1F(Form("hChiSquareFree_%d_%d",iPhi,iPt),"",30,0,3.); hChiSquareFree[iPhi][iPt]->GetXaxis()->SetTitle("#chi^{2}"); hChiSquareFree[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hChiSquareFree[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hChiSquareFree[iPhi][iPt]->SetLineColor(colors[0]); hChiSquareFixed[iPhi][iPt] = new TH1F(Form("hChiSquareFixed_%d_%d",iPhi,iPt),"",30,0,3.); hChiSquareFixed[iPhi][iPt]->GetXaxis()->SetTitle("#chi^{2}"); hChiSquareFixed[iPhi][iPt]->GetYaxis()->SetTitle("Entries"); hChiSquareFixed[iPhi][iPt]->SetTitle(Form("#phi%d, %.1f < #it{p}_{T} < %.1f GeV/c",iPhi,ptbinsnew[iPt],ptbinsnew[iPt+1])); hChiSquareFixed[iPhi][iPt]->SetLineColor(colors[1]); } } Int_t iTrial=0; for(Int_t iReb=0; iReb<nReb; iReb++) { for(Int_t iMin=0; iMin<nMins; iMin++) { for(Int_t iMax=0; iMax<nMaxs; iMax++) { for(Int_t iBkgFcn=0; iBkgFcn<nBkgFcn; iBkgFcn++) { Double_t chisquare[nptbinsnew][4]; for(Int_t ipt=0; ipt<nptbinsnew; ipt++) { for(Int_t ichi=0; ichi<4; ichi++) chisquare[ipt][ichi] = 10.; } FillSignalGraph(histlist,gSignal,gSignalfs,gSignalBC1,gSignalBC2,gSigmaFree,gSigmaFixed,gChiSquareFree,gChiSquareFixed,inoutanis,typeb[iBkgFcn],minMassForFit[iMin],maxMassForFit[iMax],rebin[iReb]); TGraphAsymmErrors *gv2=Computev2(gSignal,resol,averagePt,inoutanis,0x0); TGraphAsymmErrors *gv2fs=Computev2(gSignalfs,resol,averagePt,inoutanis,0x0); TGraphAsymmErrors *gv2BC1=Computev2(gSignalBC1,resol,averagePt,inoutanis,0x0); TGraphAsymmErrors *gv2BC2=Computev2(gSignalBC2,resol,averagePt,inoutanis,0x0); //Fill multi-trial histos for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { Double_t chifree[nphi]; Double_t chifix[nphi]; Bool_t isChiSquareFreeOk=kTRUE; Bool_t isChiSquareFixOk=kTRUE; for(Int_t iPhi=0; iPhi<nphi; iPhi++) { Double_t Y,sigma,phi; gSignal[iPt]->GetPoint(iPhi,phi,Y); gSigmaFree[iPt]->GetPoint(iPhi,phi,sigma); gChiSquareFree[iPt]->GetPoint(iPhi,phi,chifree[iPhi]); hRawYield[iPhi][iPt]->Fill(Y); hSigmaFree[iPhi][iPt]->Fill(sigma); hChiSquareFree[iPhi][iPt]->Fill(chifree[iPhi]); gSignalfs[iPt]->GetPoint(iPhi,phi,Y); gSigmaFixed[iPt]->GetPoint(iPhi,phi,sigma); gChiSquareFixed[iPt]->GetPoint(iPhi,phi,chifix[iPhi]); hRawYieldfs[iPhi][iPt]->Fill(Y); hSigmaFixed[iPhi][iPt]->Fill(sigma); hChiSquareFixed[iPhi][iPt]->Fill(chifix[iPhi]); gSignalBC1[iPt]->GetPoint(iPhi,phi,Y); hRawYieldBC1[iPhi][iPt]->Fill(Y); gSignalBC2[iPt]->GetPoint(iPhi,phi,Y); hRawYieldBC2[iPhi][iPt]->Fill(Y); if(chifree[iPhi]>maxchi) {isChiSquareFreeOk=kFALSE;} if(chifix[iPhi]>maxchi) {isChiSquareFixOk=kFALSE;} } Double_t v2, v2err, pt, v2ref, phi; gv2fsRef->GetPoint(iPt,pt,v2ref); if(isChiSquareFreeOk) {//fill only if chisquare is good gv2->GetPoint(iPt,pt,v2); v2err=gv2->GetErrorY(iPt); hv2[iPt]->Fill(v2-v2ref); hv2VsTrial[iPt]->SetBinContent(iTrial+1,v2); hv2VsTrial[iPt]->SetBinError(iTrial+1,v2err); gv2BC1->GetPoint(iPt,pt,v2); v2err=gv2BC1->GetErrorY(iPt); hv2BC1[iPt]->Fill(v2-v2ref); hv2BC1VsTrial[iPt]->SetBinContent(iTrial+1,v2); hv2BC1VsTrial[iPt]->SetBinError(iTrial+1,v2err); gv2BC2->GetPoint(iPt,pt,v2); v2err=gv2BC2->GetErrorY(iPt); hv2BC2[iPt]->Fill(v2-v2ref); hv2BC2VsTrial[iPt]->SetBinContent(iTrial+1,v2); hv2BC2VsTrial[iPt]->SetBinError(iTrial+1,v2err); } if(isChiSquareFixOk) {//fill only if chisquare is good gv2fs->GetPoint(iPt,pt,v2); v2err=gv2fs->GetErrorY(iPt); hv2fs[iPt]->Fill(v2-v2ref); hv2fsVsTrial[iPt]->SetBinContent(iTrial+1,v2); hv2fsVsTrial[iPt]->SetBinError(iTrial+1,v2err); } } iTrial++; } } } } for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { hv2Syst[iPt]->SetBinContent(1,hv2[iPt]->GetMean()); hv2Syst[iPt]->SetBinError(1,hv2[iPt]->GetRMS()); hv2fsSyst[iPt]->SetBinContent(2,hv2fs[iPt]->GetMean()); hv2fsSyst[iPt]->SetBinError(2,hv2fs[iPt]->GetRMS()); hv2BC1Syst[iPt]->SetBinContent(3,hv2BC1[iPt]->GetMean()); hv2BC1Syst[iPt]->SetBinError(3,hv2BC1[iPt]->GetRMS()); hv2BC2Syst[iPt]->SetBinContent(4,hv2BC2[iPt]->GetMean()); hv2BC2Syst[iPt]->SetBinError(4,hv2BC2[iPt]->GetRMS()); hv2Syst2[iPt]->SetBinContent(1,hv2[iPt]->GetMean()); Double_t xmin, xmax; GetMinMaxHisto(hv2[iPt],xmin,xmax); hv2Syst2[iPt]->SetBinError(1,(xmax-xmin)/TMath::Sqrt(12)); hv2fsSyst2[iPt]->SetBinContent(2,hv2fs[iPt]->GetMean()); GetMinMaxHisto(hv2fs[iPt],xmin,xmax); hv2fsSyst2[iPt]->SetBinError(2,(xmax-xmin)/TMath::Sqrt(12)); hv2BC1Syst2[iPt]->SetBinContent(3,hv2BC1[iPt]->GetMean()); GetMinMaxHisto(hv2BC1[iPt],xmin,xmax); hv2BC1Syst2[iPt]->SetBinError(3,(xmax-xmin)/TMath::Sqrt(12)); hv2BC2Syst2[iPt]->SetBinContent(4,hv2BC2[iPt]->GetMean()); GetMinMaxHisto(hv2BC2[iPt],xmin,xmax); hv2BC2Syst2[iPt]->SetBinError(4,(xmax-xmin)/TMath::Sqrt(12)); hSyst1->SetBinContent(iPt+1,TMath::Sqrt(hv2fs[iPt]->GetMean()*hv2fs[iPt]->GetMean()+hv2fs[iPt]->GetRMS()*hv2fs[iPt]->GetRMS())); } //Prepare output file TFile *fout=new TFile(Form("%s/v2RawYieldSyst_%d_%d_%s%s%s.root",outputdir.Data(),minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data()),"RECREATE"); TPaveStats **pv2 = new TPaveStats*[nptbinsnew]; TPaveStats **pv2fs = new TPaveStats*[nptbinsnew]; TPaveStats **pv2BC1 = new TPaveStats*[nptbinsnew]; TPaveStats **pv2BC2 = new TPaveStats*[nptbinsnew]; TPaveStats ***pRawYield = new TPaveStats**[nphi]; TPaveStats ***pRawYieldfs = new TPaveStats**[nphi]; TPaveStats ***pRawYieldBC1 = new TPaveStats**[nphi]; TPaveStats ***pRawYieldBC2 = new TPaveStats**[nphi]; TPaveStats ***pSigmaFree = new TPaveStats**[nphi]; TPaveStats ***pSigmaFixed = new TPaveStats**[nphi]; TPaveStats ***pChiSquareFree = new TPaveStats**[nphi]; TPaveStats ***pChiSquareFixed = new TPaveStats**[nphi]; for(Int_t iPhi=0; iPhi<nphi; iPhi++) { pRawYield[iPhi] = new TPaveStats*[nptbinsnew]; pRawYieldfs[iPhi] = new TPaveStats*[nptbinsnew]; pRawYieldBC1[iPhi] = new TPaveStats*[nptbinsnew]; pRawYieldBC2[iPhi] = new TPaveStats*[nptbinsnew]; pSigmaFree[iPhi] = new TPaveStats*[nptbinsnew]; pSigmaFixed[iPhi] = new TPaveStats*[nptbinsnew]; pChiSquareFree[iPhi] = new TPaveStats*[nptbinsnew]; pChiSquareFixed[iPhi] = new TPaveStats*[nptbinsnew]; } for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { cv2->cd(iPt+1); hv2[iPt]->GetYaxis()->SetRangeUser(0.,hv2fs[iPt]->GetMaximum()*2.); hv2[iPt]->Draw(); hv2fs[iPt]->Draw("sames"); hv2BC1[iPt]->Draw("sames"); hv2BC2[iPt]->Draw("sames"); cv2->cd(iPt+1)->Update(); pv2[iPt] = (TPaveStats*)hv2[iPt]->FindObject("stats"); pv2[iPt]->SetTextColor(colors[0]); pv2[iPt]->SetY1NDC(0.74); pv2[iPt]->SetY2NDC(0.89); pv2fs[iPt] = (TPaveStats*)hv2fs[iPt]->FindObject("stats"); pv2fs[iPt]->SetTextColor(colors[1]); pv2fs[iPt]->SetY1NDC(0.59); pv2fs[iPt]->SetY2NDC(0.74); pv2BC1[iPt] = (TPaveStats*)hv2BC1[iPt]->FindObject("stats"); pv2BC1[iPt]->SetTextColor(colors[2]); pv2BC1[iPt]->SetY1NDC(0.44); pv2BC1[iPt]->SetY2NDC(0.59); pv2BC2[iPt] = (TPaveStats*)hv2BC2[iPt]->FindObject("stats"); pv2BC2[iPt]->SetTextColor(colors[3]); pv2BC2[iPt]->SetY1NDC(0.29); pv2BC2[iPt]->SetY2NDC(0.44); cv2->cd(iPt+1)->Modified(); cv2VsTrial->cd(iPt+1); hv2VsTrial[iPt]->GetYaxis()->SetRangeUser(-0.3,0.7); hv2fsVsTrial[iPt]->GetYaxis()->SetRangeUser(-0.3,0.7); hv2BC1VsTrial[iPt]->GetYaxis()->SetRangeUser(-0.3,0.7); hv2BC2VsTrial[iPt]->GetYaxis()->SetRangeUser(-0.3,0.7); hv2VsTrial[iPt]->Draw(); hv2fsVsTrial[iPt]->Draw("same"); hv2BC1VsTrial[iPt]->Draw("same"); hv2BC2VsTrial[iPt]->Draw("same"); fout->cd(); hv2[iPt]->Write(); hv2fs[iPt]->Write(); hv2BC1[iPt]->Write(); hv2BC2[iPt]->Write(); hv2VsTrial[iPt]->Write(); hv2fsVsTrial[iPt]->Write(); hv2BC1VsTrial[iPt]->Write(); hv2BC2VsTrial[iPt]->Write(); for(Int_t iPhi=0; iPhi<nphi; iPhi++) { cRawYield[iPhi]->cd(iPt+1); hRawYield[iPhi][iPt]->GetYaxis()->SetRangeUser(0.,hRawYield[iPhi][iPt]->GetMaximum()*2.0); hRawYield[iPhi][iPt]->Draw(); hRawYieldfs[iPhi][iPt]->Draw("sames"); hRawYieldBC1[iPhi][iPt]->Draw("sames"); hRawYieldBC2[iPhi][iPt]->Draw("sames"); cRawYield[iPhi]->cd(iPt+1)->Update(); pRawYield[iPhi][iPt] = (TPaveStats*)hRawYield[iPhi][iPt]->FindObject("stats"); pRawYield[iPhi][iPt]->SetTextColor(colors[0]); pRawYield[iPhi][iPt]->SetY1NDC(0.74); pRawYield[iPhi][iPt]->SetY2NDC(0.89); pRawYieldfs[iPhi][iPt] = (TPaveStats*)hRawYieldfs[iPhi][iPt]->FindObject("stats"); pRawYieldfs[iPhi][iPt]->SetTextColor(colors[1]); pRawYieldfs[iPhi][iPt]->SetY1NDC(0.59); pRawYieldfs[iPhi][iPt]->SetY2NDC(0.74); pRawYieldBC1[iPhi][iPt] = (TPaveStats*)hRawYieldBC1[iPhi][iPt]->FindObject("stats"); pRawYieldBC1[iPhi][iPt]->SetTextColor(colors[2]); pRawYieldBC1[iPhi][iPt]->SetY1NDC(0.44); pRawYieldBC1[iPhi][iPt]->SetY2NDC(0.59); pRawYieldBC2[iPhi][iPt] = (TPaveStats*)hRawYieldBC2[iPhi][iPt]->FindObject("stats"); pRawYieldBC2[iPhi][iPt]->SetTextColor(colors[3]); pRawYieldBC2[iPhi][iPt]->SetY1NDC(0.29); pRawYieldBC2[iPhi][iPt]->SetY2NDC(0.44); cRawYield[iPhi]->cd(iPt+1)->Modified(); cSigma[iPhi]->cd(iPt+1); hSigmaFree[iPhi][iPt]->GetYaxis()->SetRangeUser(0.,hSigmaFixed[iPhi][iPt]->GetMaximum()*2.0); hSigmaFree[iPhi][iPt]->Draw(); hSigmaFixed[iPhi][iPt]->Draw("sames"); cSigma[iPhi]->cd(iPt+1)->Update(); pSigmaFree[iPhi][iPt] = (TPaveStats*)hSigmaFree[iPhi][iPt]->FindObject("stats"); pSigmaFree[iPhi][iPt]->SetTextColor(colors[0]); pSigmaFree[iPhi][iPt]->SetY1NDC(0.74); pSigmaFree[iPhi][iPt]->SetY2NDC(0.89); pSigmaFixed[iPhi][iPt] = (TPaveStats*)hSigmaFixed[iPhi][iPt]->FindObject("stats"); pSigmaFixed[iPhi][iPt]->SetTextColor(colors[1]); pSigmaFixed[iPhi][iPt]->SetY1NDC(0.59); pSigmaFixed[iPhi][iPt]->SetY2NDC(0.74); cSigma[iPhi]->cd(iPt+1)->Modified(); cChiSquare[iPhi]->cd(iPt+1); hChiSquareFree[iPhi][iPt]->GetYaxis()->SetRangeUser(0.,hChiSquareFixed[iPhi][iPt]->GetMaximum()*2.0); hChiSquareFree[iPhi][iPt]->Draw(); hChiSquareFixed[iPhi][iPt]->Draw("sames"); cChiSquare[iPhi]->cd(iPt+1)->Update(); pChiSquareFree[iPhi][iPt] = (TPaveStats*)hChiSquareFree[iPhi][iPt]->FindObject("stats"); pChiSquareFree[iPhi][iPt]->SetTextColor(colors[0]); pChiSquareFree[iPhi][iPt]->SetY1NDC(0.74); pChiSquareFree[iPhi][iPt]->SetY2NDC(0.89); pChiSquareFixed[iPhi][iPt] = (TPaveStats*)hChiSquareFixed[iPhi][iPt]->FindObject("stats"); pChiSquareFixed[iPhi][iPt]->SetTextColor(colors[1]); pChiSquareFixed[iPhi][iPt]->SetY1NDC(0.59); pChiSquareFixed[iPhi][iPt]->SetY2NDC(0.74); cChiSquare[iPhi]->cd(iPt+1)->Modified(); fout->cd(); hRawYield[iPhi][iPt]->Write(); hRawYieldfs[iPhi][iPt]->Write(); hRawYieldBC1[iPhi][iPt]->Write(); hRawYieldBC2[iPhi][iPt]->Write(); hSigmaFree[iPhi][iPt]->Write(); hSigmaFixed[iPhi][iPt]->Write(); hChiSquareFree[iPhi][iPt]->Write(); hChiSquareFixed[iPhi][iPt]->Write(); } } TCanvas** cv2Syst = new TCanvas*[nptbinsnew]; TLine** v2refline = new TLine*[nptbinsnew]; TLine** v2reflinelow = new TLine*[nptbinsnew]; TLine** v2reflinehigh = new TLine*[nptbinsnew]; TLegend** leg = new TLegend*[nptbinsnew]; for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { cv2Syst[iPt] = new TCanvas(Form("cv2Syst_%d",iPt),"",800,800); cv2Syst[iPt]->SetLeftMargin(0.16); Double_t v2staterr = gv2fsRef->GetErrorY(iPt); cv2Syst[iPt]->cd(); v2refline[iPt] = new TLine(-0.5,0,3.5,0); v2refline[iPt]->SetLineWidth(2); v2refline[iPt]->SetLineColor(colors[1]); v2reflinelow[iPt] = new TLine(-0.5,-v2staterr,3.5,-v2staterr); v2reflinelow[iPt]->SetLineWidth(2); v2reflinelow[iPt]->SetLineColor(colors[1]); v2reflinelow[iPt]->SetLineStyle(7); v2reflinehigh[iPt] = new TLine(-0.5,v2staterr,3.5,v2staterr); v2reflinehigh[iPt]->SetLineWidth(2); v2reflinehigh[iPt]->SetLineColor(colors[1]); v2reflinehigh[iPt]->SetLineStyle(7); leg[iPt] = new TLegend(0.5,0.7,0.89,0.89); leg[iPt]->SetFillStyle(0); leg[iPt]->AddEntry(v2reflinelow[iPt],"statistical uncertainty","l"); leg[iPt]->AddEntry(hv2Syst[iPt],"RMS","p"); leg[iPt]->AddEntry(hv2Syst2[iPt],"(x_{max}-x_{min})/#sqrt{12}","p"); hv2Syst[iPt]->GetYaxis()->SetRangeUser(-v2staterr*2,v2staterr*3); hv2Syst[iPt]->Draw("E1X0"); hv2fsSyst[iPt]->Draw("E1sameX0"); hv2BC1Syst[iPt]->Draw("E1sameX0"); hv2BC2Syst[iPt]->Draw("E1sameX0"); hv2Syst2[iPt]->Draw("E1sameX0"); hv2fsSyst2[iPt]->Draw("E1sameX0"); hv2BC1Syst2[iPt]->Draw("E1sameX0"); hv2BC2Syst2[iPt]->Draw("E1sameX0"); v2refline[iPt]->Draw("same"); v2reflinelow[iPt]->Draw("same"); v2reflinehigh[iPt]->Draw("same"); leg[iPt]->Draw("same"); fout->cd(); cv2Syst[iPt]->Write(); cv2Syst[iPt]->SaveAs(Form("%s/v2RawYieldSyst_pt%.1f-%.1f_%d_%d_%s%s%s.pdf",outputdir.Data(),ptbinsnew[iPt],ptbinsnew[iPt+1],minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); } fout->Close(); TCanvas* cv2SystVsPt = new TCanvas("cv2SystVsPt","",1920,1080); cv2SystVsPt->SetLeftMargin(0.15); hSyst1->Draw("hist"); cv2->SaveAs(Form("%s/v2RawYieldSyst_%d_%d_%s%s%s.pdf",outputdir.Data(),minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); cv2SystVsPt->SaveAs(Form("%s/v2RawYieldSyst_RMSshift_%d_%d_%s%s%s.pdf",outputdir.Data(),minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); for(Int_t iPhi=0; iPhi<nphi; iPhi++) { cRawYield[iPhi]->SaveAs(Form("%s/RawYieldSyst_phi%d_%d_%d_%s%s%s.pdf",outputdir.Data(),iPhi,minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); cSigma[iPhi]->SaveAs(Form("%s/RawYieldSyst_phi%d_%d_%d_%s%s%s.pdf",outputdir.Data(),iPhi,minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); cChiSquare[iPhi]->SaveAs(Form("%s/RawYieldSyst_phi%d_%d_%d_%s%s%s.pdf",outputdir.Data(),iPhi,minCent,maxCent,aniss.Data(),suffix.Data(),fine.Data())); } return 0; } //______________________________________________________________ Double_t GetEventPlaneResolution(Double_t& error, TH1F* hsubev1, TH1F* hsubev2, TH1F* hsubev3){ Double_t resolFull=1.; if(evPlaneRes==AliEventPlaneResolutionHandler::kTwoRandSub || evPlaneRes==AliEventPlaneResolutionHandler::kTwoChargeSub){ resolFull=AliVertexingHFUtils::GetFullEvResol(hsubev1); error = TMath::Abs(resolFull-AliVertexingHFUtils::GetFullEvResolLowLim(hsubev1)); }else if(evPlaneRes==AliEventPlaneResolutionHandler::kTwoEtaSub){ if(evPlane==AliEventPlaneResolutionHandler::kTPCFullEta){ resolFull=AliVertexingHFUtils::GetFullEvResol(hsubev1); error = TMath::Abs(resolFull-AliVertexingHFUtils::GetFullEvResolLowLim(hsubev1)); }else if(evPlane==AliEventPlaneResolutionHandler::kTPCPosEta){ resolFull=AliVertexingHFUtils::GetSubEvResol(hsubev1); error = TMath::Abs(resolFull-AliVertexingHFUtils::GetSubEvResolLowLim(hsubev1)); } }else{ Double_t resolSub[3]; Double_t errors[3]; TH1F* hevplresos[3]; hevplresos[0]=hsubev1; hevplresos[1]=hsubev2; hevplresos[2]=hsubev3; for(Int_t ires=0;ires<3;ires++){ resolSub[ires]=hevplresos[ires]->GetMean(); errors[ires]=hevplresos[ires]->GetMeanError(); } Double_t lowlim[3];for(Int_t ie=0;ie<3;ie++)lowlim[ie]=TMath::Abs(resolSub[ie]-errors[ie]); if(evPlane==AliEventPlaneResolutionHandler::kVZEROC || evPlane==AliEventPlaneResolutionHandler::kVZERO){ resolFull=TMath::Sqrt(resolSub[1]*resolSub[2]/resolSub[0]); error=resolFull-TMath::Sqrt(lowlim[2]*lowlim[1]/lowlim[0]); } else if(evPlane==AliEventPlaneResolutionHandler::kVZEROA){ resolFull=TMath::Sqrt(resolSub[0]*resolSub[2]/resolSub[1]); error=resolFull-TMath::Sqrt(lowlim[2]*lowlim[0]/lowlim[1]); } else if(evPlane==AliEventPlaneResolutionHandler::kTPCFullEta || evPlane==AliEventPlaneResolutionHandler::kTPCPosEta){ resolFull=TMath::Sqrt(resolSub[0]*resolSub[1]/resolSub[2]); error=resolFull-TMath::Sqrt(lowlim[0]*lowlim[1]/lowlim[2]); } } return resolFull; } //____________________________________________________________________ TList* LoadResolutionHistos(TList *inputlist){ TList *outlist = new TList(); outlist->SetName("eventplanehistlist"); const Int_t nBins=20; Double_t ncoll[nBins]={1790.77,1578.44,1394.82,1236.17 ,1095.08,969.86,859.571,759.959,669.648,589.588,516.039 ,451.409,392.853,340.493,294.426,252.385,215.484,183.284 ,155.101,130.963}; Int_t minCentTimesTen=minCent*10; Int_t maxCentTimesTen=maxCent*10; TGraphErrors* gResolVsCent=new TGraphErrors(0); Int_t iPt=0; Int_t nSubRes=1; if(evPlaneRes==AliEventPlaneResolutionHandler::kThreeSub|| evPlaneRes==AliEventPlaneResolutionHandler::kThreeSubTPCGap)nSubRes=3; TString namereso[3]={"Reso","Reso2","Reso3"}; TString suffixcentr=Form("centr%d_%d",minCent,maxCent); TH1F* htestversion=(TH1F*)inputlist->FindObject(Form("hEvPlaneResocentr%d_%d",minCentTimesTen,minCentTimesTen+25)); if(htestversion){ printf("Old version of the task\n"); }else{ printf("New version of the task\n"); namereso[0]="Reso1"; } TH2F* hevpls=(TH2F*)inputlist->FindObject(Form("hEvPlanecentr%d_%d",minCentTimesTen,minCentTimesTen+25)); hevpls->SetName(Form("hEvPlane%s",suffixcentr.Data())); hevpls->SetTitle(Form("Event Plane angle %s",suffixcentr.Data())); TH1F* hevplresos[3]; Int_t ncBin=minCentTimesTen/25; for(Int_t ires=0;ires<nSubRes;ires++){ hevplresos[ires]=(TH1F*)inputlist->FindObject(Form("hEvPlane%scentr%d_%d",namereso[ires].Data(),minCentTimesTen,minCentTimesTen+25)); if(hevplresos[ires]){ hevplresos[ires]->SetName(Form("hEvPlane%s%s",namereso[ires].Data(),suffixcentr.Data())); hevplresos[ires]->SetTitle(Form("Event Plane Resolution %s%s",namereso[ires].Data(),suffixcentr.Data())); if(useNcollWeight){ printf("Centr %d Bin %d Ncoll %f\n",minCentTimesTen,ncBin,ncoll[ncBin]); hevplresos[ires]->Scale(ncoll[ncBin]); } } } Double_t error; Double_t lowestRes=1; Double_t highestRes=0; Double_t resolBin=GetEventPlaneResolution(error,hevplresos[0],hevplresos[1],hevplresos[2]); if(resolBin<lowestRes) lowestRes=resolBin; if(resolBin>highestRes) highestRes=resolBin; Double_t binHalfWid=25./20.; Double_t binCentr=(Double_t)minCentTimesTen/10.+binHalfWid; gResolVsCent->SetPoint(iPt,binCentr,resolBin); gResolVsCent->SetPointError(iPt,binHalfWid,error); ++iPt; for(Int_t icentr=minCentTimesTen+25;icentr<maxCentTimesTen;icentr=icentr+25){ TH2F* h=(TH2F*)inputlist->FindObject(Form("hEvPlanecentr%d_%d",icentr,icentr+25)); if(h)hevpls->Add(h); else cout<<"skipping ev plane "<<icentr<<"_"<<icentr+5<<endl; TH1F* htmpresos[3]; for(Int_t ires=0;ires<nSubRes;ires++){ htmpresos[ires]=(TH1F*)inputlist->FindObject(Form("hEvPlane%scentr%d_%d",namereso[ires].Data(),icentr,icentr+25)); if(!htmpresos[ires])cout<<"skipping ev pl reso "<<icentr<<"_"<<icentr+25<<endl; } resolBin=GetEventPlaneResolution(error,htmpresos[0],htmpresos[1],htmpresos[2]); if(resolBin<lowestRes) lowestRes=resolBin; if(resolBin>highestRes) highestRes=resolBin; binCentr=(Double_t)icentr/10.+binHalfWid; gResolVsCent->SetPoint(iPt,binCentr,resolBin); gResolVsCent->SetPointError(iPt,binHalfWid,error); ++iPt; ncBin=icentr/25; for(Int_t ires=0;ires<nSubRes;ires++){ if(htmpresos[ires]){ if(useNcollWeight){ printf("Centr %d Bin %d Ncoll %f\n",icentr,ncBin,ncoll[ncBin]); htmpresos[ires]->Scale(ncoll[ncBin]); } hevplresos[ires]->Add(htmpresos[ires]); } } } outlist->Add(hevpls->Clone()); for(Int_t ires=0;ires<nSubRes;ires++){ if(hevplresos[ires]) outlist->Add(hevplresos[ires]->Clone()); } gResolVsCent->SetName("gResolVsCent"); gResolVsCent->SetTitle("Resolution vs. Centrality"); outlist->Add(gResolVsCent->Clone()); return outlist; } //__________________________________________________________ TList *LoadMassHistos(TList *inputlist,Bool_t inoutanis){ // printf("Start load histos\n"); // const Int_t nptbins=cutobj->GetNPtBins(); TList *outlist = new TList(); outlist->SetName("azimuthalhistoslist"); Int_t nphi=nphibins; if(inoutanis)nphi=2; Int_t minCentTimesTen=minCent*10; Int_t maxCentTimesTen=maxCent*10; //Create 2D histogram in final pt bins for(Int_t iFinalPtBin=0; iFinalPtBin<nptbinsnew; iFinalPtBin++){ for(Int_t iphi=0;iphi<nphi;iphi++){ TH1F *hMass=0x0;//=new TH1F(); for(Int_t iPtBin=minPtBin[iFinalPtBin]; iPtBin<=maxPtBin[iFinalPtBin];iPtBin++){ for(Int_t iHisC=minCentTimesTen; iHisC<=maxCentTimesTen-25; iHisC+=25){ TString hisname=Form("hMdeltaphi_pt%dcentr%d_%d",iPtBin,iHisC,iHisC+25); TH2F* htmp=(TH2F*)inputlist->FindObject(hisname.Data()); printf("---> Histogram: %s\n",htmp->GetName()); Int_t startX=htmp->FindBin(phibinslim[iphi]); Int_t endX=htmp->FindBin(phibinslim[iphi+1]-0.0001); // -0.0001 to be sure that the upper limit of the bin is properly set TH1F *h1tmp; if(inoutanis){ if(iphi==0){ Int_t firstBin=htmp->FindBin(0); Int_t lastBin=htmp->FindBin(TMath::Pi()/4.-0.0001); // -0.0001 to be sure that the upper limit of the bin is pi/4 h1tmp=(TH1F*)htmp->ProjectionY(Form("hMass%d_phi0",iPtBin),firstBin,lastBin); printf("In-plane, Range: bins %d-%d -> phi %f - %f\n",firstBin,lastBin,htmp->GetXaxis()->GetBinLowEdge(firstBin),htmp->GetXaxis()->GetBinUpEdge(lastBin)); firstBin=htmp->FindBin(3.*TMath::Pi()/4.); lastBin=htmp->FindBin(TMath::Pi()-0.0001); // -0.0001 to be sure that the upper limit of the bin is pi h1tmp->Add((TH1F*)htmp->ProjectionY(Form("hMass%d",iPtBin),firstBin,lastBin)); printf("In-plane, Range: bins %d-%d -> phi %f - %f\n",firstBin,lastBin,htmp->GetXaxis()->GetBinLowEdge(firstBin),htmp->GetXaxis()->GetBinUpEdge(lastBin)); }else{ Int_t firstBin=htmp->FindBin(TMath::Pi()/4.); Int_t lastBin=htmp->FindBin(3.*TMath::Pi()/4.-0.0001); // -0.0001 to be sure that the upper limit of the bin is pi/4 h1tmp=(TH1F*)htmp->ProjectionY(Form("hMass%d_phi1",iPtBin),firstBin,lastBin); printf("Out-of-plane, Range: bins %d-%d -> phi %f - %f\n",firstBin,lastBin,htmp->GetXaxis()->GetBinLowEdge(firstBin),htmp->GetXaxis()->GetBinUpEdge(lastBin)); } }else{ h1tmp=(TH1F*)htmp->ProjectionY(Form("hMass%d_phi%d",iPtBin,iphi),startX,endX); } if(hMass==0)hMass=(TH1F*)h1tmp->Clone(); else hMass->Add((TH1F*)h1tmp->Clone()); } } hMass->SetTitle(Form("hMass_pt%d_phi%d",iFinalPtBin,iphi)); hMass->SetName(Form("hMass_pt%d_phi%d",iFinalPtBin,iphi)); outlist->Add(hMass->Clone()); delete hMass; hMass=0x0; } } if(useTemplD0Refl){ Bool_t retCode=LoadD0toKpiMCHistos(outlist); if(!retCode)Printf("ERROR: MC histograms loading failed"); else Printf("******************************************\n MC HISTOGRAMS LOADED\n\n**********************************"); } return outlist; } //______________________________________________________________ Bool_t DefinePtBins(AliRDHFCuts *cutobj){ Int_t nPtBinsCuts=cutobj->GetNPtBins(); Float_t *ptlimsCuts=(Float_t*)cutobj->GetPtBinLimits(); for(Int_t iPtCuts=0; iPtCuts<nPtBinsCuts; iPtCuts++){ for(Int_t iFinalPtBin=0; iFinalPtBin<nptbinsnew; iFinalPtBin++){ if(TMath::Abs(ptlimsCuts[iPtCuts]-ptbinsnew[iFinalPtBin])<0.0001){ minPtBin[iFinalPtBin]=iPtCuts; if(iFinalPtBin>0) maxPtBin[iFinalPtBin-1]=iPtCuts-1; } } if(TMath::Abs(ptlimsCuts[iPtCuts]-ptbinsnew[nptbinsnew])<0.0001) maxPtBin[nptbinsnew-1]=iPtCuts-1; } if(TMath::Abs(ptbinsnew[nptbinsnew]-ptlimsCuts[nPtBinsCuts])<0.0001) maxPtBin[nptbinsnew-1]=nPtBinsCuts-1; for(Int_t iFinalPtBin=0; iFinalPtBin<nptbinsnew; iFinalPtBin++){ printf("Pt bins to be merged: %d %d\n",minPtBin[iFinalPtBin],maxPtBin[iFinalPtBin]); if(minPtBin[iFinalPtBin]<0 || maxPtBin[iFinalPtBin]<0) return kFALSE; } return kTRUE; } //______________________________________________________________ void FillSignalGraph(TList *histlist,TGraphAsymmErrors **gSignal,TGraphAsymmErrors **gSignalfs, TGraphAsymmErrors **gSignalBC1, TGraphAsymmErrors **gSignalBC2,TGraphAsymmErrors **gSigmaFree,TGraphAsymmErrors **gSigmaFixed, TGraphAsymmErrors **gChiSquareFree, TGraphAsymmErrors **gChiSquareFixed, Bool_t inoutanis, Int_t bkgfunc, Double_t minfit, Double_t maxfit, Int_t rebin){ Int_t nphi=nphibins; if(inoutanis)nphi=2; TH1F *hrflTempl=0x0; TH1F *hsigMC=0x0; Float_t sOverRef=0.; Int_t nMassBins; for(Int_t ipt=0;ipt<nptbinsnew;ipt++){ TH1F *histtofitfullsigma=(TH1F*)histlist->FindObject(Form("hMass_pt%d_phi0",ipt))->Clone(); if(useTemplD0Refl){ hrflTempl=(TH1F*)histlist->FindObject(Form("histRfl_%d",ipt)); hsigMC=(TH1F*)histlist->FindObject(Form("histSgn_%d",ipt)); } for(Int_t iphi=0;iphi<nphi;iphi++){ Double_t signal=0,esignal=0; Double_t sigma=0, esigma=0; Double_t chisquare=0; TH1F *histtofit=(TH1F*)histlist->FindObject(Form("hMass_pt%d_phi%d",ipt,iphi))->Clone(); if(iphi>0)histtofitfullsigma->Add((TH1F*)histtofit->Clone()); if(!histtofit){ gSignal[ipt]->SetPoint(iphi,iphi,signal); gSignal[ipt]->SetPointError(iphi,0,0,esignal,esignal); return; } histtofit->SetTitle(Form("%.1f < #it{p}_{T} < %.1f, #phi%d",ptbinsnew[ipt],ptbinsnew[ipt+1],iphi)); nMassBins=histtofit->GetNbinsX(); histtofit->Rebin(rebin); //AliHFMassFitter fitter(histtofit,minfit,maxfit,1,bkgfunc); AliHFMassFitterVAR *fitter=new AliHFMassFitterVAR(histtofit,minfit,maxfit,1,bkgfunc,types); if(useTemplD0Refl){ fitter->SetTemplateReflections(hrflTempl); sOverRef=(hrflTempl->Integral(hrflTempl->FindBin(minfit*1.0001),hrflTempl->FindBin(maxfit*0.999)))/(hsigMC->Integral(hsigMC->FindBin(minfit*1.0001),hsigMC->FindBin(maxfit*0.999))); fitter->SetFixReflOverS(sOverRef,kTRUE); } fitter->SetInitialGaussianMean(massD); fitter->SetInitialGaussianSigma(0.012); Bool_t ok=fitter->MassFitter(kFALSE); Double_t sigmaforcounting=0; Double_t meanforcounting=0; if(ok){ signal=fitter->GetRawYield(); esignal=fitter->GetRawYieldError(); sigma=fitter->GetSigma(); esigma=fitter->GetSigmaUncertainty(); sigmaforcounting=sigma; meanforcounting=fitter->GetMean(); chisquare=fitter->GetReducedChiSquare(); } gSignal[ipt]->SetPoint(iphi,iphi,signal); gSignal[ipt]->SetPointError(iphi,0,0,esignal,esignal); gSigmaFree[ipt]->SetPoint(iphi,iphi,sigma); gSigmaFree[ipt]->SetPointError(iphi,0,0,esigma,esigma); gChiSquareFree[ipt]->SetPoint(iphi,iphi,chisquare); gChiSquareFree[ipt]->SetPointError(iphi,0,0,0,0); TF1* fB1=fitter->GetBackgroundFullRangeFunc(); TF1* fB2=fitter->GetBackgroundRecalcFunc(); Double_t minBinSum=histtofit->FindBin(meanforcounting-nSigmaForCounting*sigmaforcounting); Double_t maxBinSum=histtofit->FindBin(meanforcounting+nSigmaForCounting*sigmaforcounting); Double_t cntSig1=0.; Double_t cntSig2=0.; Double_t cntErr=0.; for(Int_t iMB=minBinSum; iMB<=maxBinSum; iMB++){ Double_t bkg1=fB1 ? fB1->Eval(histtofit->GetBinCenter(iMB)) : 0; Double_t bkg2=fB2 ? fB2->Eval(histtofit->GetBinCenter(iMB)) : 0; cntSig1+=(histtofit->GetBinContent(iMB)-bkg1); cntSig2+=(histtofit->GetBinContent(iMB)-bkg2); cntErr+=(histtofit->GetBinContent(iMB)); } cntErr=TMath::Sqrt(cntErr); gSignalBC1[ipt]->SetPoint(iphi,iphi,cntSig1); gSignalBC1[ipt]->SetPointError(iphi,0,0,cntErr,cntErr); gSignalBC2[ipt]->SetPoint(iphi,iphi,cntSig2); gSignalBC2[ipt]->SetPointError(iphi,0,0,cntErr,cntErr); } //fit for fixed sigma histtofitfullsigma->SetTitle(Form("%.1f < #it{p}_{T} < %.1f GeV/c",ptbinsnew[ipt],ptbinsnew[ipt+1])); histtofitfullsigma->GetXaxis()->SetTitle("M_{K#pi#pi} (GeV/c^{2})"); histtofitfullsigma->GetXaxis()->SetTitleSize(0.05); nMassBins=histtofitfullsigma->GetNbinsX(); histtofitfullsigma->Rebin(rebin); //AliHFMassFitter fitter(histtofitfullsigma,minfit,maxfit,1,bkgfunc); AliHFMassFitterVAR *fitter=new AliHFMassFitterVAR(histtofitfullsigma,minfit,maxfit,1,bkgfunc,types); if(useTemplD0Refl){ fitter->SetTemplateReflections(hrflTempl); sOverRef=hrflTempl->Integral(hrflTempl->FindBin(minfit*1.0001),hrflTempl->FindBin(maxfit*0.999))/hsigMC->Integral(hsigMC->FindBin(minfit*1.0001),hsigMC->FindBin(maxfit*0.999)); fitter->SetFixReflOverS(sOverRef,kTRUE); } fitter->SetInitialGaussianMean(massD); Bool_t ok=fitter->MassFitter(kFALSE); Double_t sigmatot=fitter->GetSigma(); Double_t massFromFit=fitter->GetMean(); for(Int_t iphi=0;iphi<nphi;iphi++){ TH1F *histtofit=(TH1F*)histlist->FindObject(Form("hMass_pt%d_phi%d",ipt,iphi))->Clone(); histtofit->SetTitle(Form("%.1f < #it{p}_{T} < %.1f, #phi%d",ptbinsnew[ipt],ptbinsnew[ipt+1],iphi)); nMassBins=histtofit->GetNbinsX(); histtofit->Rebin(rebin); //AliHFMassFitter fitter2(histtofit,minfit,maxfit,1,bkgfunc); AliHFMassFitterVAR *fitter2=new AliHFMassFitterVAR(histtofit,minfit,maxfit,1,bkgfunc,types); if(useTemplD0Refl){ fitter2->SetTemplateReflections(hrflTempl); sOverRef=hrflTempl->Integral(hrflTempl->FindBin(minfit*1.0001),hrflTempl->FindBin(maxfit*0.999))/hsigMC->Integral(hsigMC->FindBin(minfit*1.0001),hsigMC->FindBin(maxfit*0.999)); fitter2->SetFixReflOverS(sOverRef,kTRUE); } fitter2->SetInitialGaussianMean(massD); fitter2->SetFixGaussianSigma(sigmatot); if(fixAlsoMass) fitter2->SetFixGaussianMean(massFromFit); Bool_t ok2=fitter2->MassFitter(kFALSE); Double_t signal=0,esignal=0; Double_t sigma=0, esigma=0; Double_t chisquare=0; if(ok2){ signal=fitter2->GetRawYield(); esignal=fitter2->GetRawYieldError(); sigma=fitter->GetSigma(); esigma=fitter->GetSigmaUncertainty(); chisquare=fitter2->GetReducedChiSquare(); } gSignalfs[ipt]->SetPoint(iphi,iphi,signal); gSignalfs[ipt]->SetPointError(iphi,0,0,esignal,esignal); gSigmaFixed[ipt]->SetPoint(iphi,iphi,sigma); gSigmaFixed[ipt]->SetPointError(iphi,0,0,esigma,esigma); gChiSquareFixed[ipt]->SetPoint(iphi,iphi,chisquare); gChiSquareFixed[ipt]->SetPointError(iphi,0,0,0,0); } }//end loop on pt bin } //______________________________________________________________ TGraphAsymmErrors* Computev2(TGraphAsymmErrors **gSignal, Double_t resol, Float_t *averagePt, Bool_t inoutanis, TGraphAsymmErrors *gRelSystEff) { TGraphAsymmErrors* gv2 = new TGraphAsymmErrors(nptbinsnew); if(inoutanis) { for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { Double_t *y=gSignal[iPt]->GetY(); Double_t nIn=y[0]; Double_t nOut=y[1]; Double_t enIn=gSignal[iPt]->GetErrorY(0); Double_t enOut=gSignal[iPt]->GetErrorY(1); Double_t anis=0; Double_t eAnis=0; Double_t v2=0.; Double_t ev2=0; if((nIn+nOut)!=0) { anis=(nIn-nOut)/(nIn+nOut); eAnis=2./((nIn+nOut)*(nIn+nOut))*TMath::Sqrt(nIn*nIn*enOut*enOut+nOut*nOut*enIn*enIn); v2=anis*TMath::Pi()/4./resol; ev2=eAnis*TMath::Pi()/4./resol; } gv2->SetPoint(iPt,averagePt[iPt],v2); gv2->SetPointError(iPt,averagePt[iPt]-ptbinsnew[iPt],ptbinsnew[iPt+1]-averagePt[iPt],ev2,ev2); if(gRelSystEff) { //systematic uncertainty for in-out efficiency Double_t anis1=(nIn-nOut*effInOverEffOut)/(nIn+nOut*effInOverEffOut); Double_t anis2=(nIn*effInOverEffOut-nOut)/(nIn*effInOverEffOut+nOut); Double_t systEffUp=0.,systEffDown=0.; if(anis1>anis && anis1>anis2) systEffUp=anis1/anis; if(anis2>anis && anis2>anis1) systEffUp=anis2/anis; if(anis1<anis && anis1<anis2) systEffDown=anis1/anis; if(anis2<anis && anis2<anis1) systEffDown=anis2/anis; cout << Form(" Bin %d <pt>=%.3f v2=%f+-%f systEff=%f %f\n",iPt,averagePt[iPt],v2,ev2,systEffUp*v2,systEffDown*v2)<<endl; gRelSystEff->SetPoint(iPt,averagePt[iPt],v2); gRelSystEff->SetPointError(iPt,0.4,0.4,v2*(1-systEffDown),v2*(systEffUp-1)); } } return gv2; } else { TF1 *flowFunc = new TF1("flow","[0]*(1.+2.*[1]*TMath::Cos(2.*x))"); for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { //v2 from fit to Deltaphi distribution gSignal[iPt]->Fit(flowFunc); Double_t v2 = flowFunc->GetParameter(1)/resol; Double_t ev2=flowFunc->GetParError(1)/resol; gv2->SetPoint(iPt,averagePt[iPt],v2); gv2->SetPointError(iPt,averagePt[iPt]-ptbinsnew[iPt],ptbinsnew[iPt+1]-averagePt[iPt],ev2,ev2); } return gv2; } } //___________________________________________________________ Int_t FindPtBin(Int_t nbins, Double_t* array,Double_t value){ for (Int_t i=0;i<nbins;i++){ if(value>=array[i] && value<array[i+1]){ return i; } } cout<<value<< " out of range "<<array[0]<<", "<<array[nbins]<<endl; return -1; } //___________________________________________________________ Int_t LoadRefGraphs(TString reffilename, TH1F **hRawYieldRef, TH1F **hRawYieldfsRef, TH1F **hRawYieldBC1Ref, TH1F **hRawYieldBC2Ref, TGraphAsymmErrors *&gv2Ref, TGraphAsymmErrors *&gv2fsRef, TGraphAsymmErrors *&gv2BC1Ref, TGraphAsymmErrors *&gv2BC2Ref, Bool_t inoutanis) { Int_t nphi=nphibins; if(inoutanis) nphi=2; TFile* reffile = TFile::Open(reffilename.Data(),"READ"); if(reffile) { gv2Ref=(TGraphAsymmErrors*)reffile->Get("gav2"); gv2fsRef=(TGraphAsymmErrors*)reffile->Get("gav2fs"); gv2BC1Ref=(TGraphAsymmErrors*)reffile->Get("gav2BC1"); gv2BC2Ref=(TGraphAsymmErrors*)reffile->Get("gav2BC2"); if(!gv2Ref) {return 2;} if(!gv2fsRef) {return 3;} if(!gv2BC1Ref) {return 4;} if(!gv2BC2Ref) {return 5;} for(Int_t iPhi=0; iPhi<nphi; iPhi++) { hRawYieldRef[iPhi] = new TH1F(Form("hRawYieldRef_phi%d",iPhi),"",nptbinsnew,ptbinsnew); hRawYieldfsRef[iPhi]= new TH1F(Form("hRawYieldfsRef_phi%d",iPhi),"",nptbinsnew,ptbinsnew); hRawYieldBC1Ref[iPhi]= new TH1F(Form("hRawYieldBC1Ref_phi%d",iPhi),"",nptbinsnew,ptbinsnew); hRawYieldBC2Ref[iPhi]= new TH1F(Form("hRawYieldBC2Ref_phi%d",iPhi),"",nptbinsnew,ptbinsnew); hRawYieldRef[iPhi]->SetDirectory(0); hRawYieldfsRef[iPhi]->SetDirectory(0); hRawYieldBC1Ref[iPhi]->SetDirectory(0); hRawYieldBC2Ref[iPhi]->SetDirectory(0); } for(Int_t iPt=0; iPt<nptbinsnew; iPt++) { TGraphAsymmErrors* gtmp = (TGraphAsymmErrors*)reffile->Get(Form("gasigpt%d",iPt)); TGraphAsymmErrors* gtmpfs = (TGraphAsymmErrors*)reffile->Get(Form("gasigfspt%d",iPt)); TGraphAsymmErrors* gtmpBC1 = (TGraphAsymmErrors*)reffile->Get(Form("gasigBC1pt%d",iPt)); TGraphAsymmErrors* gtmpBC2 = (TGraphAsymmErrors*)reffile->Get(Form("gasigBC2pt%d",iPt)); if(gtmp && gtmpfs && gtmpBC1 && gtmpBC2) { for(Int_t iPhi=0; iPhi<nphi; iPhi++) { Double_t phi,Y, errY; gtmp->GetPoint(iPhi,phi,Y); hRawYieldRef[iPhi]->SetBinContent(iPt+1,Y); gtmpfs->GetPoint(iPhi,phi,Y); hRawYieldfsRef[iPhi]->SetBinContent(iPt+1,Y); gtmpBC1->GetPoint(iPhi,phi,Y); hRawYieldBC1Ref[iPhi]->SetBinContent(iPt+1,Y); gtmpBC2->GetPoint(iPhi,phi,Y); hRawYieldBC2Ref[iPhi]->SetBinContent(iPt+1,Y); } } } reffile->Close(); } else {return 1;} return 0; } //___________________________________________________________ void GetMinMaxHisto(TH1F* histo, Double_t &xmin, Double_t &xmax) { Int_t nbins=histo->GetNbinsX(); xmin=histo->GetBinLowEdge(nbins)+histo->GetBinWidth(nbins); Int_t content=0; for(Int_t iBin=0; iBin<nbins; iBin++) { content=histo->GetBinContent(iBin+1); if(content>0) { xmin=histo->GetBinLowEdge(iBin+1); break; } } content=0; xmax=histo->GetBinLowEdge(1); for(Int_t iBin=nbins; iBin>0; iBin--) { content=histo->GetBinContent(iBin); if(content>0) { xmax=histo->GetBinLowEdge(iBin)+histo->GetBinWidth(iBin); break; } } } //__________________________________________________________________________________________________________________ void DivideCanvas(TCanvas* c, const Int_t nPtBins) { if(nPtBins<2) c->Divide(1,1); if(nPtBins==2 || nPtBins==3) c->Divide(nPtBins,1); else if(nPtBins==4 || nPtBins==6 || nPtBins==8) c->Divide(nPtBins/2,2); else if(nPtBins==5 || nPtBins==7) c->Divide((nPtBins+1)/2,2); else if(nPtBins==9 || nPtBins==12 || nPtBins==15) c->Divide(nPtBins/3,3); else if(nPtBins==10 || nPtBins==11) c->Divide(4,3); else if(nPtBins==13 || nPtBins==14) c->Divide(5,3); else if(nPtBins>15 && nPtBins<=20 && nPtBins%4==0) c->Divide(nPtBins/4,4); else if(nPtBins>15 && nPtBins<=20 && nPtBins%4!=0) c->Divide(5,4); else if(nPtBins==21) c->Divide(7,3); else if(nPtBins>21 && nPtBins<=25) c->Divide(5,5); else if(nPtBins>25 && nPtBins%2==0) c->Divide(nPtBins/2,2); else c->Divide((nPtBins+1)/2,2); } //___________________________________________________________ void SetStyle(Int_t optfit) { gStyle->SetCanvasColor(0); gStyle->SetPadBottomMargin(0.14); gStyle->SetPadLeftMargin(0.12); gStyle->SetTitleFillColor(0); gStyle->SetStatColor(0); gStyle->SetOptStat(1111); gStyle->SetOptFit(optfit); gStyle->SetLabelFont(42,"XYZ"); gStyle->SetTextFont(42); gStyle->SetTitleSize(0.05,"xyz"); gStyle->SetLabelSize(0.05,"xyz"); gStyle->SetStatFont(42); gStyle->SetStatY(0.89); gStyle->SetStatX(0.89); gStyle->SetTitleFont(42,"xyzg"); gStyle->SetHistLineWidth(1); gStyle->SetLegendBorderSize(0); } Bool_t LoadD0toKpiMCHistos(TList *outlist){ TFile *f=new TFile(fileNameMCD0refl.Data(),"READ"); if(!f){ printf("ERROR: file %s does not exist\n",fileNameMCD0refl.Data()); return kFALSE; } f->ls(); TH1F** hsig=new TH1F*[nptbinsnew]; TH1F** hrfl=new TH1F*[nptbinsnew]; for(Int_t j=0;j<nptbinsnew;j++){ hsig[j]=(TH1F*)f->Get(Form("histSgn_%d",j)); if(!hsig[j]) {Printf("histSgn_%d NOT FOUND",j); return kFALSE;} hrfl[j]=(TH1F*)f->Get(Form("histRflFitted%s_ptBin%d",rflFitType.Data(),j)); if(!hrfl[j]) {Printf("histRflFitted%s_ptBin%d",rflFitType.Data(),j); return kFALSE;} } for(Int_t k=0;k<nptbinsnew;k++){ outlist->Add(hsig[k]->Clone(Form("histSgn_%d",k))); outlist->Add(hrfl[k]->Clone(Form("histRfl_%d",k))); } outlist->ls(); //for(Int_t p=0;p<nptbinsnew;p++){ //delete hsig[p]; //delete hrfl[p]; //} //f->Close(); return kTRUE; }
60e69e856cd21bf7fd5ed6e5210f78fb9ce3d4cb
10a8580aa44d33b7458429023c00de8c01ceda98
/axiom/tests/test_slowsqls.c
13b90b0c5ab94ad107b2fc27462edee2d69d61a7
[ "BSD-4-Clause-UC", "Apache-2.0" ]
permissive
newrelic/newrelic-php-agent
87ad20e0a5abf0d2855e7d27a25c36454ae4389a
dfb359f0dbb53e4cbc5106b52c8f3807c7fc8d42
refs/heads/main
2023-08-15T10:28:24.372352
2023-08-14T17:29:31
2023-08-14T17:29:31
302,112,572
116
67
Apache-2.0
2023-09-13T18:33:47
2020-10-07T17:35:01
C
UTF-8
C
false
false
18,375
c
test_slowsqls.c
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "nr_axiom.h" #include <stdio.h> #include "nr_slowsqls.h" #include "util_memory.h" #include "util_sql.h" #include "util_strings.h" #include "util_time.h" #include "tlib_main.h" static nr_slowsqls_params_t sample_slowsql_params(void) { nr_slowsqls_params_t params = { .sql = "my/sql", .duration = 5 * NR_TIME_DIVISOR, .stacktrace_json = "[\"already\\/escaped\"]", .metric_name = "my/metric", .instance_reporting_enabled = 1, .database_name_reporting_enabled = 1, }; return params; } static void test_simple_add(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("simply add", nr_slowsql_id(slow), 2902036434); tlib_pass_if_int_equal("simply add", nr_slowsql_count(slow), 1); tlib_pass_if_time_equal("simply add", nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal("simply add", nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal("simply add", nr_slowsql_total(slow), 5000000); tlib_pass_if_str_equal("simply add", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("simply add", nr_slowsql_query(slow), "my/sql"); tlib_pass_if_str_equal("simply add", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_min_max(void) { nr_slowsqls_t* slowsqls = nr_slowsqls_create(1); const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); params.duration = 5 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); params.duration = 3 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); params.duration = 4 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); params.duration = 6 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); params.duration = 7 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); params.duration = 5 * NR_TIME_DIVISOR; nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("test min/max", nr_slowsql_id(slow), 2902036434); tlib_pass_if_int_equal("test min/max", nr_slowsql_count(slow), 6); tlib_pass_if_time_equal("test min/max", nr_slowsql_min(slow), 3000000); tlib_pass_if_time_equal("test min/max", nr_slowsql_max(slow), 7000000); tlib_pass_if_time_equal("test min/max", nr_slowsql_total(slow), 30000000); tlib_pass_if_str_equal("test min/max", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("test min/max", nr_slowsql_query(slow), "my/sql"); tlib_pass_if_str_equal("test min/max", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_raw_sql_aggregation(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); params.sql = "SELECT * FROM test WHERE foo IN (1)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (2)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (2, 3, 4)"; nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("simple raw aggregation", nr_slowsql_id(slow), 2676686092); tlib_pass_if_int_equal("simple raw aggregation", nr_slowsql_count(slow), 3); tlib_pass_if_time_equal("simple raw aggregation", nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal("simple raw aggregation", nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal("simple raw aggregation", nr_slowsql_total(slow), 15000000); tlib_pass_if_str_equal("simple raw aggregation", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("simple raw aggregation", nr_slowsql_query(slow), "SELECT * FROM test WHERE foo IN (1)"); tlib_pass_if_str_equal("simple raw aggregation", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_obfuscated_sql_aggregation(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); params.sql = "SELECT * FROM test WHERE foo IN (?)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (?)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (?, ?, ?)"; nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("obfuscated", nr_slowsql_id(slow), 2676686092); tlib_pass_if_int_equal("obfuscated", nr_slowsql_count(slow), 3); tlib_pass_if_time_equal("obfuscated", nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal("obfuscated", nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal("obfuscated", nr_slowsql_total(slow), 15000000); tlib_pass_if_str_equal("obfuscated", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("obfuscated", nr_slowsql_query(slow), "SELECT * FROM test WHERE foo IN (?)"); tlib_pass_if_str_equal("obfuscated", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_mixed_aggregation(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); params.sql = "SELECT * FROM test WHERE foo IN (?)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (9)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (?, ?, ?)"; nr_slowsqls_add(slowsqls, &params); params.sql = "SELECT * FROM test WHERE foo IN (9, 9, 9, ?)"; nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("mixed aggregation", nr_slowsql_id(slow), 2676686092); tlib_pass_if_int_equal("mixed aggregation", nr_slowsql_count(slow), 4); tlib_pass_if_time_equal("mixed aggregation", nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal("mixed aggregation", nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal("mixed aggregation", nr_slowsql_total(slow), 20000000); tlib_pass_if_str_equal("mixed aggregation", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("mixed aggregation", nr_slowsql_query(slow), "SELECT * FROM test WHERE foo IN (?)"); tlib_pass_if_str_equal("mixed aggregation", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_slowest_taken(void) { int i; nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; nr_slowsqls_params_t params = sample_slowsql_params(); /* * Add in increasing order */ slowsqls = nr_slowsqls_create(2); for (i = 0; i < 10; i++) { char sql[128]; snprintf(sql, sizeof(sql), "my/sql/%c", 'a' + i); params.duration = (i + 1) * NR_TIME_DIVISOR; params.sql = sql; nr_slowsqls_add(slowsqls, &params); } slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("slowest taken", nr_slowsql_id(slow), 983362361); tlib_pass_if_int_equal("slowest taken", nr_slowsql_count(slow), 1); tlib_pass_if_time_equal("slowest taken", nr_slowsql_min(slow), 9000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_max(slow), 9000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_total(slow), 9000000); tlib_pass_if_str_equal("slowest taken", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_query(slow), "my/sql/i"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); slow = nr_slowsqls_at(slowsqls, 1); tlib_pass_if_uint32_t_equal("slowest taken", nr_slowsql_id(slow), 1860598843); tlib_pass_if_int_equal("slowest taken", nr_slowsql_count(slow), 1); tlib_pass_if_time_equal("slowest taken", nr_slowsql_min(slow), 10000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_max(slow), 10000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_total(slow), 10000000); tlib_pass_if_str_equal("slowest taken", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_query(slow), "my/sql/j"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); /* * Add in decreasing order */ slowsqls = nr_slowsqls_create(2); for (i = 9; i >= 0; i--) { char sql[128]; snprintf(sql, sizeof(sql), "my/sql/%c", 'a' + i); params.duration = (i + 1) * NR_TIME_DIVISOR; params.sql = sql; nr_slowsqls_add(slowsqls, &params); } slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal("slowest taken", nr_slowsql_id(slow), 1860598843); tlib_pass_if_int_equal("slowest taken", nr_slowsql_count(slow), 1); tlib_pass_if_time_equal("slowest taken", nr_slowsql_min(slow), 10000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_max(slow), 10000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_total(slow), 10000000); tlib_pass_if_str_equal("slowest taken", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_query(slow), "my/sql/j"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); slow = nr_slowsqls_at(slowsqls, 1); tlib_pass_if_uint32_t_equal("slowest taken", nr_slowsql_id(slow), 983362361); tlib_pass_if_int_equal("slowest taken", nr_slowsql_count(slow), 1); tlib_pass_if_time_equal("slowest taken", nr_slowsql_min(slow), 9000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_max(slow), 9000000); tlib_pass_if_time_equal("slowest taken", nr_slowsql_total(slow), 9000000); tlib_pass_if_str_equal("slowest taken", nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_query(slow), "my/sql/i"); tlib_pass_if_str_equal("slowest taken", nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slowsqls); } static void test_max_time_ranked(void) { nr_slowsqls_t* slows = nr_slowsqls_create(1); const nr_slowsql_t* slow; const char* testname = "max time, not total time, determines what is saved"; nr_slowsqls_params_t params = sample_slowsql_params(); /* sql/one has largest total, but not largest max */ params.sql = "sql/one"; params.duration = 2 * NR_TIME_DIVISOR; nr_slowsqls_add(slows, &params); nr_slowsqls_add(slows, &params); nr_slowsqls_add(slows, &params); nr_slowsqls_add(slows, &params); /* sql/two has smallest total, but largest max */ params.sql = "sql/two"; params.duration = 5 * NR_TIME_DIVISOR; nr_slowsqls_add(slows, &params); slow = nr_slowsqls_at(slows, 0); tlib_pass_if_uint32_t_equal(testname, nr_slowsql_id(slow), 917616874); tlib_pass_if_int_equal(testname, nr_slowsql_count(slow), 1); tlib_pass_if_time_equal(testname, nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_total(slow), 5000000); tlib_pass_if_str_equal(testname, nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal(testname, nr_slowsql_query(slow), "sql/two"); tlib_pass_if_str_equal(testname, nr_slowsql_params(slow), "{\"backtrace\":[\"already\\/escaped\"]}"); nr_slowsqls_destroy(&slows); } static void test_destroy_bad_params(void) { nr_slowsqls_t* slowsqls = 0; /* Don't blow up! */ nr_slowsqls_destroy(0); nr_slowsqls_destroy(&slowsqls); } static void test_create_bad_params(void) { nr_slowsqls_t* slowsqls; slowsqls = nr_slowsqls_create(0); tlib_pass_if_true("create zero max", 0 == slowsqls, "slowsqls=%p", slowsqls); slowsqls = nr_slowsqls_create(-1); tlib_pass_if_true("create -1 max", 0 == slowsqls, "slowsqls=%p", slowsqls); } static void test_add_bad_params(void) { nr_slowsqls_t* slowsqls; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); /* No slowsqls: Don't blow up! */ nr_slowsqls_add(0, 0); nr_slowsqls_add(0, &params); /* No params */ nr_slowsqls_add(slowsqls, NULL); /* No stacktrace */ params = sample_slowsql_params(); params.stacktrace_json = NULL; nr_slowsqls_add(slowsqls, &params); /* No SQL */ params = sample_slowsql_params(); params.sql = NULL; nr_slowsqls_add(slowsqls, &params); /* Empty SQL */ params = sample_slowsql_params(); params.sql = ""; nr_slowsqls_add(slowsqls, &params); /* No Duration */ params = sample_slowsql_params(); params.duration = 0; nr_slowsqls_add(slowsqls, &params); /* No Metric */ params = sample_slowsql_params(); params.metric_name = NULL; nr_slowsqls_add(slowsqls, &params); tlib_pass_if_int_equal("bad params", nr_slowsqls_saved(slowsqls), 0); nr_slowsqls_destroy(&slowsqls); } static void test_add_all_hash_params(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; const char* testname = "with explain plan, input query, and instance"; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); params.plan_json = "[[\"foo\",\"bar\"],[[1,2]]]"; params.input_query_json = "{\"label\":\"zip\",\"query\":\"zap\"}"; params.instance = nr_datastore_instance_create("super_db_host", "3306", "my_database"); nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal(testname, nr_slowsql_id(slow), 2902036434); tlib_pass_if_int_equal(testname, nr_slowsql_count(slow), 1); tlib_pass_if_time_equal(testname, nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_total(slow), 5000000); tlib_pass_if_str_equal(testname, nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal(testname, nr_slowsql_query(slow), "my/sql"); tlib_pass_if_str_equal( testname, nr_slowsql_params(slow), "{" "\"explain_plan\":[[\"foo\",\"bar\"],[[1,2]]]," "\"backtrace\":[\"already\\/escaped\"]," "\"input_query\":{\"label\":\"zip\",\"query\":\"zap\"}," "\"host\":\"super_db_host\"," "\"port_path_or_id\":\"3306\"," "\"database_name\":\"my_database\"" "}"); nr_slowsqls_destroy(&slowsqls); nr_datastore_instance_destroy(&params.instance); } static void test_instance_info_disabled(void) { nr_slowsqls_t* slowsqls; const nr_slowsql_t* slow; const char* testname = "with instance info disabled"; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(1); params.plan_json = "[[\"foo\",\"bar\"],[[1,2]]]"; params.input_query_json = "{\"label\":\"zip\",\"query\":\"zap\"}"; params.instance = nr_datastore_instance_create("does", "not", "matter"); params.instance_reporting_enabled = 0; params.database_name_reporting_enabled = 0; nr_slowsqls_add(slowsqls, &params); slow = nr_slowsqls_at(slowsqls, 0); tlib_pass_if_uint32_t_equal(testname, nr_slowsql_id(slow), 2902036434); tlib_pass_if_int_equal(testname, nr_slowsql_count(slow), 1); tlib_pass_if_time_equal(testname, nr_slowsql_min(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_max(slow), 5000000); tlib_pass_if_time_equal(testname, nr_slowsql_total(slow), 5000000); tlib_pass_if_str_equal(testname, nr_slowsql_metric(slow), "my/metric"); tlib_pass_if_str_equal(testname, nr_slowsql_query(slow), "my/sql"); tlib_pass_if_str_equal(testname, nr_slowsql_params(slow), "{" "\"explain_plan\":[[\"foo\",\"bar\"],[[1,2]]]," "\"backtrace\":[\"already\\/escaped\"]," "\"input_query\":{\"label\":\"zip\",\"query\":\"zap\"}" "}"); nr_slowsqls_destroy(&slowsqls); nr_datastore_instance_destroy(&params.instance); } static void test_slowsqls_at_bad_params(void) { nr_slowsqls_t* slowsqls; nr_slowsqls_params_t params = sample_slowsql_params(); slowsqls = nr_slowsqls_create(10); nr_slowsqls_add(slowsqls, &params); tlib_pass_if_null("null ptr", nr_slowsqls_at(NULL, 1)); tlib_pass_if_null("negative idx", nr_slowsqls_at(slowsqls, -1)); tlib_pass_if_null("large idx", nr_slowsqls_at(slowsqls, 1)); tlib_pass_if_not_null("success", nr_slowsqls_at(slowsqls, 0)); nr_slowsqls_destroy(&slowsqls); } static void test_slowsql_accessor_bad_params(void) { tlib_pass_if_uint32_t_equal("null sql", nr_slowsql_id(NULL), 0); tlib_pass_if_int_equal("null sql", nr_slowsql_count(NULL), 0); tlib_pass_if_time_equal("null sql", nr_slowsql_min(NULL), 0); tlib_pass_if_time_equal("null sql", nr_slowsql_max(NULL), 0); tlib_pass_if_time_equal("null sql", nr_slowsql_total(NULL), 0); tlib_pass_if_str_equal("null sql", nr_slowsql_metric(NULL), NULL); tlib_pass_if_str_equal("null sql", nr_slowsql_query(NULL), NULL); tlib_pass_if_str_equal("null sql", nr_slowsql_params(NULL), NULL); } tlib_parallel_info_t parallel_info = {.suggested_nthreads = 4, .state_size = 0}; void test_main(void* p NRUNUSED) { test_simple_add(); test_min_max(); test_raw_sql_aggregation(); test_obfuscated_sql_aggregation(); test_mixed_aggregation(); test_slowest_taken(); test_max_time_ranked(); test_destroy_bad_params(); test_create_bad_params(); test_add_bad_params(); test_add_all_hash_params(); test_instance_info_disabled(); test_slowsqls_at_bad_params(); test_slowsql_accessor_bad_params(); }
52a804aaf04f20782174ad5d280fff0662ac4100
fbef550c1f0206aac0582a58f7e3db945f442a9a
/Pods/Headers/Private/Sentry/UIView+Sentry.h
79cc6752466474587575c204831d0b5f9f726998
[ "MIT" ]
permissive
Hammerspoon/hammerspoon
0f03b4dd2ef3b44ea4c0a1cd0b94fcb513b5f2b7
0ccc9d07641a660140d1d2f05b76f682b501a0e8
refs/heads/master
2023-08-19T01:26:41.898873
2023-06-20T22:52:50
2023-06-20T22:52:50
24,956,772
11,379
676
MIT
2023-06-09T02:51:33
2014-10-08T19:24:44
Objective-C
UTF-8
C
false
false
54
h
UIView+Sentry.h
../../../Sentry/Sources/Sentry/include/UIView+Sentry.h
38a62fe07a525d2e34c7746f2bcde835e64d8722
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/games/prboom/files/patch-src_SDL_i__system.c
4ecd359deef2d2ec2ff3280cff037dbdf063c80b
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
388
c
patch-src_SDL_i__system.c
--- src/SDL/i_system.c.orig 2008-11-09 18:19:11 UTC +++ src/SDL/i_system.c @@ -72,6 +72,7 @@ #include <fcntl.h> #include <sys/stat.h> #include <errno.h> +#include <sys/cpuset.h> #ifndef PRBOOM_SERVER #include "m_argv.h" @@ -441,7 +442,7 @@ void I_SetAffinityMask(void) // POSIX version: int i; { - cpu_set_t set; + cpuset_t set; CPU_ZERO(&set);
f85e155b430be165e3179081852978a892fc85c5
7664f318ed04bd0680f3d82321c18896e3ef6ad5
/src/overlays/actors/ovl_En_Anubice_Tag/z_en_anubice_tag.h
0147b30cd54b0b0899ddeeba6a183b28d574229d
[]
no_license
zeldaret/oot
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
refs/heads/master
2023-08-29T05:29:31.356427
2023-08-28T22:48:52
2023-08-28T22:48:52
247,875,738
4,401
802
null
2023-09-14T13:34:38
2020-03-17T04:02:19
C
UTF-8
C
false
false
480
h
z_en_anubice_tag.h
#ifndef Z_EN_ANUBICE_TAG_H #define Z_EN_ANUBICE_TAG_H #include "ultra64.h" #include "global.h" #include "overlays/actors/ovl_En_Anubice/z_en_anubice.h" struct EnAnubiceTag; typedef void (*EnAnubiceTagActionFunc)(struct EnAnubiceTag*, PlayState*); typedef struct EnAnubiceTag { /* 0x0000 */ Actor actor; /* 0x014C */ EnAnubiceTagActionFunc actionFunc; /* 0x0150 */ EnAnubice* anubis; /* 0x0154 */ f32 extraTriggerRange; } EnAnubiceTag; // size = 0x0158 #endif
d5040fdf08a5dcd27c91e93ab2369b9c6de4f337
84f1ce4838c39cec710818d69005f8919ec39994
/src/core/mmu/vmm.c
017f7f515cff6b4811a3e1df6beb2993cbe50116
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
bao-project/bao-hypervisor
adb2689fdd690d10ea11fa693375c4043a9f9309
291cac3df9d5e0b4704006376196cd2231105704
refs/heads/main
2023-08-31T05:50:21.845457
2023-07-25T19:46:28
2023-08-22T12:09:57
233,099,706
231
78
Apache-2.0
2023-09-14T13:58:26
2020-01-10T17:42:11
C
UTF-8
C
false
false
617
c
vmm.c
/** * SPDX-License-Identifier: Apache-2.0 * Copyright (c) Bao Project and Contributors. All rights reserved. */ #include <vmm.h> #include <io.h> void vmm_io_init() { io_init(); } struct vm_install_info vmm_get_vm_install_info(struct vm_allocation* vm_alloc) { struct vm_install_info info = { .base = vm_alloc->base, .vm_section_pte = *pt_get_pte(&cpu()->as.pt, 0, vm_alloc->base), }; return info; } void vmm_vm_install(struct vm_install_info *install_info) { pte_t* pte = pt_get_pte(&cpu()->as.pt, 0, (vaddr_t)install_info->base); *pte = install_info->vm_section_pte; }
5b22a0f48e202fd86011ec1aa93d90f502137e58
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/mips/src/pic32mz/pic32mz_gpioirq.c
1e796857fc4c7b30e47e8294d726e7acadadf0a3
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
20,266
c
pic32mz_gpioirq.c
/**************************************************************************** * arch/mips/src/pic32mz/pic32mz_gpioirq.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <assert.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <arch/board/board.h> #include <arch/pic32mz/irq.h> #include "mips_internal.h" #include "hardware/pic32mz_ioport.h" #include "pic32mz_gpio.h" #ifdef CONFIG_PIC32MZ_GPIOIRQ /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Private Types ****************************************************************************/ /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static inline unsigned int pic32mz_ioport(pinset_t pinset); static inline unsigned int pic32mz_pin(pinset_t pinset); static inline bool pic32mz_input(pinset_t pinset); static inline bool pic32mz_interrupt(pinset_t pinset); static inline bool pic32mz_edgedetect(pinset_t pinset); static inline unsigned int pic32mz_edgemode(pinset_t pinset); static inline bool pic32mz_pullup(pinset_t pinset); static inline bool pic32mz_pulldown(pinset_t pinset); static int pic32mz_cninterrupt(int irq, void *context, void *arg); /**************************************************************************** * Public Data ****************************************************************************/ struct ioport_handler_s { xcpt_t entry; /* Interrupt handler entry point */ void *arg; /* The argument that accompanies the interrupt handler */ }; struct ioport_level2_s { struct ioport_handler_s handler[16]; }; /**************************************************************************** * Private Data ****************************************************************************/ /* Arrays of second level interrupt handlers for each pin of each enabled * I/O port. */ #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTA static struct ioport_level2_s g_ioporta_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTB static struct ioport_level2_s g_ioportb_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTC static struct ioport_level2_s g_ioportc_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTD static struct ioport_level2_s g_ioportd_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTE static struct ioport_level2_s g_ioporte_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTF static struct ioport_level2_s g_ioportf_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTG static struct ioport_level2_s g_ioportg_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTH static struct ioport_level2_s g_ioporth_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTJ static struct ioport_level2_s g_ioportj_cnisrs; #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTK static struct ioport_level2_s g_ioportk_cnisrs; #endif /* Look-up of port to interrupt handler array */ static struct ioport_level2_s * const g_level2_handlers[CHIP_NPORTS] = { #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTA [PIC32MZ_IOPORTA] = &g_ioporta_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTB [PIC32MZ_IOPORTB] = &g_ioportb_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTC [PIC32MZ_IOPORTC] = &g_ioportc_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTD [PIC32MZ_IOPORTD] = &g_ioportd_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTE [PIC32MZ_IOPORTE] = &g_ioporte_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTF [PIC32MZ_IOPORTF] = &g_ioportf_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTG [PIC32MZ_IOPORTG] = &g_ioportg_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTH [PIC32MZ_IOPORTH] = &g_ioporth_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTJ [PIC32MZ_IOPORTJ] = &g_ioportj_cnisrs, #endif #ifdef CONFIG_PIC32MZ_GPIOIRQ_PORTK [PIC32MZ_IOPORTK] = &g_ioportk_cnisrs, #endif }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: Inline PIN set field extractors ****************************************************************************/ static inline bool pic32mz_input(pinset_t pinset) { return (((pinset & GPIO_MODE_MASK) >> GPIO_MODE_SHIFT) == GPIO_INPUT); } static inline bool pic32mz_interrupt(pinset_t pinset) { return ((pinset & GPIO_INTERRUPT) != 0); } static inline bool pic32mz_edgedetect(pinset_t pinset) { return ((pinset & GPIO_EDGE_DETECT) != 0); } static inline unsigned int pic32mz_edgemode(pinset_t pinset) { return ((pinset & GPIO_EDGE_RISING)); } static inline bool pic32mz_pullup(pinset_t pinset) { return ((pinset & GPIO_PULLUP) != 0); } static inline bool pic32mz_pulldown(pinset_t pinset) { return ((pinset & GPIO_PULLDOWN) != 0); } static inline unsigned int pic32mz_ioport(pinset_t pinset) { return ((pinset & GPIO_PORT_MASK) >> GPIO_PORT_SHIFT); } static inline unsigned int pic32mz_pin(pinset_t pinset) { return ((pinset & GPIO_PIN_MASK) >> GPIO_PIN_SHIFT); } /**************************************************************************** * Name: pic32mz_cninterrupt * * Description: * Common change notification interrupt handler. * ****************************************************************************/ static int pic32mz_cninterrupt(int irq, void *context, void *arg) { struct ioport_level2_s *handlers; xcpt_t handler; uintptr_t base; uint32_t cncon; uint32_t cnen; uint32_t cnne; uint32_t cnstat; uint32_t cnf; uint32_t pending; uint32_t regval; int ioport; int status; int ret = OK; int i; /* Get the IO port index from the IRQ number. This, of course, * assumes that the irq numbers are consecutive beginning with * IOPORTA. */ ioport = irq - PIC32MZ_IRQ_PORTA; DEBUGASSERT(ioport >= 0 && ioport < CHIP_NPORTS); /* If we got this interrupt, then there must also be an array * of second level handlers (and a base address) for the IOPORT. */ handlers = g_level2_handlers[ioport]; base = g_gpiobase[ioport]; DEBUGASSERT(handlers && base); /* Get the control registers. It will be used to get the interrupt type. */ cncon = getreg32(base + PIC32MZ_IOPORT_CNCON_OFFSET); if (handlers && base) { /* Mismatch mode selected? */ if ((cncon & IOPORT_CNCON_EDGEDETECT) == 0) { /* Get the interrupt status associated with this interrupt */ cnstat = getreg32(base + PIC32MZ_IOPORT_CNSTAT_OFFSET); cnen = getreg32(base + PIC32MZ_IOPORT_CNEN_OFFSET); pending = cnstat & cnen; /* Call all attached handlers for each pending interrupt */ for (i = 0; i < 16; i++) { /* Is this interrupt pending */ if ((pending & (IOPORT_CNSTAT(i))) != 0) { /* Yes.. Has the user attached a handler? */ handler = handlers->handler[i].entry; if (handler) { /* Yes.. call the attached handler */ status = handler(irq, context, handlers->handler[i].arg); /* Keep track of the status of the last handler that * failed. */ if (status < 0) { ret = status; } } } } /* Clear pending status. */ regval = getreg32(base + PIC32MZ_IOPORT_PORT_OFFSET); UNUSED(regval); } /* Edge detect mode selected. */ else { /* Get the interrupt status associated with this interrupt. * The interrupt is controlled by either CNEN (positive edge) * or CNNE (negative edge). */ cnen = getreg32(base + PIC32MZ_IOPORT_CNEN_OFFSET); cnne = getreg32(base + PIC32MZ_IOPORT_CNNE_OFFSET); cnf = getreg32(base + PIC32MZ_IOPORT_CNF_OFFSET); pending = cnf & (cnen | cnne); /* Call all attached handlers for each pending interrupt */ for (i = 0; i < 16; i++) { /* Is this interrupt pending */ if ((pending & (IOPORT_CNF(i))) != 0) { /* Yes.. Has the user attached a handler? */ handler = handlers->handler[i].entry; if (handler) { /* Yes.. call the attached handler */ status = handler(irq, context, handlers->handler[i].arg); /* Keep track of the status of the last handler that * failed. */ if (status < 0) { ret = status; } } } } /* Clear pending status. */ putreg32(pending, base + PIC32MZ_IOPORT_CNFCLR_OFFSET); } } /* Clear the pending interrupt */ mips_clrpend_irq(irq); return ret; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: pic32mz_gpioirqinitialize * * Description: * Initialize logic to support a GPIO change notification interrupts. * This function is called internally by the system on power up and should * not be called again. * ****************************************************************************/ void pic32mz_gpioirqinitialize(void) { uintptr_t base; uint32_t regval; int ret; int i; /* Perform initialization for each IO port that has interrupt support * enabled. We can tell this because there will be an array of second * level handlers for each enabled IO port. */ for (i = 0; i < CHIP_NPORTS; i++) { /* Get the base address of this IO port peripheral */ base = g_gpiobase[i]; DEBUGASSERT(base); /* Reset all registers and disable the CN module */ putreg32(IOPORT_CNEN_ALL, base + PIC32MZ_IOPORT_CNENCLR_OFFSET); putreg32(IOPORT_CNNE_ALL, base + PIC32MZ_IOPORT_CNNECLR_OFFSET); putreg32(IOPORT_CNPU_ALL, base + PIC32MZ_IOPORT_CNPUCLR_OFFSET); putreg32(IOPORT_CNPD_ALL, base + PIC32MZ_IOPORT_CNPDCLR_OFFSET); putreg32(0, base + PIC32MZ_IOPORT_CNCON_OFFSET); /* Is interrupt support selected for this IO port? */ if (g_level2_handlers[i] != NULL) { /* Yes.. Attach the common change notice interrupt handler * to the IO port interrupt. Notice that this assumes that * each IRQ number is consecutive beginning with IOPORTA. */ ret = irq_attach(PIC32MZ_IRQ_PORTA + i, pic32mz_cninterrupt, NULL); DEBUGASSERT(ret == OK); UNUSED(ret); /* Enable the CN module. NOTE that the CN module is active when * in sleep mode. */ putreg32(IOPORT_CNCON_ON, base + PIC32MZ_IOPORT_CNCON_OFFSET); /* Read the port to clear the interrupt. */ regval = getreg32(base + PIC32MZ_IOPORT_PORT_OFFSET); UNUSED(regval); /* Clear the CN interrupt flag. Same assumption as above. */ mips_clrpend_irq(PIC32MZ_IRQ_PORTA + i); } } } /**************************************************************************** * Name: pic32mz_gpioattach * * Description: * Attach an interrupt service routine to a GPIO interrupt. This will * also reconfigure the pin as an interrupting input. The change * notification number is associated with all interrupt-capabile GPIO pins. * The association could, however, differ from part to part and must be * provided by the caller. * * When an interrupt occurs, it is due to a change on the GPIO input pin. * In that case, all attached handlers will be called. Each handler must * maintain state and determine if the underlying GPIO input value changed. * * Input Parameters: * pinset - GPIO pin configuration * handler - Interrupt handler (may be NULL to detach) * arg - The argument that accompanies the interrupt * * Returned Value: * Zero (OK) is returned on success. A negated error value is returned on * any failure to indicate the nature of the failure. * ****************************************************************************/ int pic32mz_gpioattach(pinset_t pinset, xcpt_t handler, void *arg) { struct ioport_level2_s *handlers; irqstate_t flags; uintptr_t base; int ioport; int pin; /* First verify that the pinset is configured as an interrupting input */ if (pic32mz_input(pinset) && pic32mz_interrupt(pinset)) { /* Get the ioport index and pin number from the pinset */ ioport = pic32mz_ioport(pinset); pin = pic32mz_pin(pinset); DEBUGASSERT(ioport >= 0 && ioport < CHIP_NPORTS); /* Get the register base address for this port */ base = g_gpiobase[ioport]; DEBUGASSERT(base); /* If this IO port has been properly configured for interrupts, then * there should be an array of second level interrupt handlers * allocated for it. */ handlers = g_level2_handlers[ioport]; DEBUGASSERT(handlers); if (handlers) { /* Get the previously attached handler as the return value */ flags = enter_critical_section(); /* Are we attaching or detaching? */ if (handler != NULL) { /* Attaching... Make sure that the GPIO is properly configured * as an input */ pic32mz_configgpio(pinset); /* Pull-up requested? */ if (pic32mz_pullup(pinset)) { putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPUSET_OFFSET); } else { putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPUCLR_OFFSET); } /* Pull-down requested? */ if (pic32mz_pulldown(pinset)) { putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPDSET_OFFSET); } else { putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPDCLR_OFFSET); } } else { /* Disable the pull-up/downs (just so things look better in * the debugger). */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPUCLR_OFFSET); putreg32(1 << pin, base + PIC32MZ_IOPORT_CNPDCLR_OFFSET); } /* Whether attaching or detaching, the next state of the interrupt * should be disabled. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNENCLR_OFFSET); putreg32(1 << pin, base + PIC32MZ_IOPORT_CNNECLR_OFFSET); /* Set the new handler (perhaps NULLifying the current handler) */ handlers->handler[pin].entry = handler; handlers->handler[pin].arg = arg; leave_critical_section(flags); } } return OK; } /**************************************************************************** * Name: pic32mz_gpioirqenable * * Description: * Enable the interrupt for specified GPIO IRQ * ****************************************************************************/ void pic32mz_gpioirqenable(pinset_t pinset) { uintptr_t base; int ioport; int pin; /* Get the ioport index and pin number from the pinset */ ioport = pic32mz_ioport(pinset); pin = pic32mz_pin(pinset); DEBUGASSERT(ioport >= 0 && ioport < CHIP_NPORTS); /* Get the register base address for this port */ base = g_gpiobase[ioport]; DEBUGASSERT(base); if (base) { /* Enable the correct CN interrupt. * NOTE that we don't actually check if * interrupts are configured for this IO port. If not, this operation * should do nothing. */ if (!pic32mz_edgedetect(pinset)) { /* If Edge detect is not selected, then CNEN * controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNENSET_OFFSET); } else { /* Enable edge detect. */ putreg32(IOPORT_CNCON_EDGEDETECT, base + PIC32MZ_IOPORT_CNCONSET_OFFSET); if (pic32mz_edgemode(pinset) == GPIO_EDGE_RISING) { /* Rising edge selected. CNEN controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNENSET_OFFSET); } else { /* Falling edge selected. CNNE controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNNESET_OFFSET); } } /* And enable the interrupt. */ up_enable_irq(ioport + PIC32MZ_IRQ_PORTA); } } /**************************************************************************** * Name: pic32mz_gpioirqdisable * * Description: * Disable the interrupt for specified GPIO IRQ * ****************************************************************************/ void pic32mz_gpioirqdisable(pinset_t pinset) { uintptr_t base; int ioport; int pin; /* Get the ioport index and pin number from the pinset */ ioport = pic32mz_ioport(pinset); pin = pic32mz_pin(pinset); DEBUGASSERT(ioport >= 0 && ioport < CHIP_NPORTS); /* Get the register base address for this port */ base = g_gpiobase[ioport]; DEBUGASSERT(base); if (base) { /* And disable the correct interrupt. * NOTE that we don't actually check if * interrupts are configured for this IO port. If not, this operation * should do nothing. */ if (!pic32mz_edgedetect(pinset)) { /* If Edge detect is not selected, then CNEN * controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNENCLR_OFFSET); } else { if (pic32mz_edgemode(pinset) == GPIO_EDGE_RISING) { /* Rising edge selected. * CNEN controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNENCLR_OFFSET); } else { /* Falling edge selected. * CNNE controls the interrupt. */ putreg32(1 << pin, base + PIC32MZ_IOPORT_CNNECLR_OFFSET); } } } } #endif /* CONFIG_PIC32MZ_GPIOIRQ */
28253f32941766a844085725749156d10a106b91
7e1cd9b94c0c8c443f993362dc185dfc35ceb963
/interface/khronos/ext/egl_brcm_perf_monitor_client.c
16d516443bbc766a883ac5ea49aa5226eeb62624
[ "BSD-3-Clause" ]
permissive
raspberrypi/userland
92e557234bb6d7f701066543e0efc36dfb54a52c
cc1ca18fb0689b01cc2ca2aa4b400dcee624a213
refs/heads/master
2023-08-20T15:41:23.695645
2023-04-19T10:38:04
2023-04-20T13:36:13
6,367,886
1,608
928
BSD-3-Clause
2023-09-13T09:54:26
2012-10-24T09:58:46
C
UTF-8
C
false
false
4,797
c
egl_brcm_perf_monitor_client.c
/* Copyright (c) 2012, Broadcom Europe Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the 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. */ #define EGL_EGLEXT_PROTOTYPES /* we want the prototypes so the compiler will check that the signatures match */ #include "interface/khronos/common/khrn_int_common.h" #include "interface/khronos/common/khrn_client.h" #include "interface/khronos/common/khrn_client_rpc.h" #include "interface/khronos/egl/egl_client_config.h" #include "interface/khronos/ext/egl_brcm_perf_monitor_client.h" #include "interface/khronos/include/EGL/egl.h" #include "interface/khronos/include/EGL/eglext.h" #if EGL_BRCM_perf_monitor EGLAPI EGLBoolean EGLAPIENTRY eglInitPerfMonitorBRCM(EGLDisplay dpy) { CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE(); EGLBoolean result; CLIENT_LOCK(); { CLIENT_PROCESS_STATE_T *process = client_egl_get_process_state(thread, dpy, EGL_TRUE); if (process) { if (!process->perf_monitor_inited) process->perf_monitor_inited = RPC_BOOLEAN_RES(RPC_CALL0_RES(eglInitPerfMonitorBRCM_impl, EGLINITPERFMONITORBRCM_ID)); if (process->perf_monitor_inited) { thread->error = EGL_SUCCESS; result = EGL_TRUE; } else { thread->error = EGL_BAD_ALLOC; result = EGL_FALSE; } } else result = EGL_FALSE; } CLIENT_UNLOCK(); return result; } void egl_perf_monitor_term(CLIENT_PROCESS_STATE_T *process) { if (process->perf_monitor_inited) { RPC_CALL0(eglTermPerfMonitorBRCM_impl, EGLTERMPERFMONITORBRCM_ID); process->perf_monitor_inited = false; } } EGLAPI EGLBoolean EGLAPIENTRY eglTermPerfMonitorBRCM(EGLDisplay dpy) { CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE(); EGLBoolean result; CLIENT_LOCK(); { CLIENT_PROCESS_STATE_T *process = client_egl_get_process_state(thread, dpy, EGL_TRUE); if (process) { egl_perf_monitor_term(process); thread->error = EGL_SUCCESS; result = EGL_TRUE; } else result = EGL_FALSE; } CLIENT_UNLOCK(); return result; } #endif #if EGL_BRCM_perf_stats EGLAPI void eglPerfStatsResetBRCM(void) { CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE(); RPC_CALL0(eglPerfStatsResetBRCM_impl, thread, EGLPERFSTATSRESETBRCM_ID); } EGLAPI void eglPerfStatsGetBRCM(char *buffer, EGLint buffer_len, EGLBoolean reset) { CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE(); // int len = _min(_max(buffer_len, 0), KHDISPATCH_WORKSPACE_SIZE); RPC_CALL3_OUT_BULK(eglPerfStatsGetBRCM_impl, thread, EGLPERFSTATSGETBRCM_ID, RPC_INT(buffer_len), RPC_BOOLEAN(reset), buffer); } #endif #if EGL_BRCM_mem_usage EGLAPI void eglProcessMemUsageGetBRCM(uint32_t id_0, uint32_t id_1, char *buffer, uint32_t buffer_len) { CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE(); RPC_CALL4_OUT_BULK(eglIntGetProcessMemUsage_impl, thread, EGLINTGETPROCESSMEMUSAGE_ID, RPC_UINT(id_0), RPC_UINT(id_1), RPC_UINT(buffer_len), buffer); } #endif
c41c1448193318f204bc2d6f3e9b77d475c4b983
34cfb15a219a735d58fcaadfb71ef1606a9114dc
/ext/src/swow_buffer.c
2415240e9eed4e25feb533a7126b70177ac43a1c
[ "Apache-2.0", "ISC", "BSL-1.0", "MIT", "BSD-2-Clause" ]
permissive
swow/swow
e32007f3cf1c8daf4accd7d64f9b2b728f5ab103
231f580dd1ee84d0364f314387073c5bda9854d2
refs/heads/develop
2023-08-19T13:51:39.840737
2023-08-05T01:51:04
2023-08-05T03:13:03
295,651,066
1,085
117
Apache-2.0
2023-06-15T09:18:12
2020-09-15T07:37:43
C
UTF-8
C
false
false
37,664
c
swow_buffer.c
/* +--------------------------------------------------------------------------+ | Swow | +--------------------------------------------------------------------------+ | 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. See accompanying LICENSE file. | +--------------------------------------------------------------------------+ | Author: Twosee <twosee@php.net> | +--------------------------------------------------------------------------+ */ #include "swow_buffer.h" SWOW_API zend_class_entry *swow_buffer_ce; SWOW_API zend_object_handlers swow_buffer_handlers; SWOW_API zend_class_entry *swow_buffer_exception_ce; #define VECTOR_POSITION_FMT "[%u][%u] " #define VECTOR_POSTION_C vector_index, arg_num - 1 #define ZEND_LONG_ARG_FMT "($%s = " ZEND_LONG_FMT ") " #define ZEND_LONG_ARG_C arg_name, arg static ZEND_COLD zend_never_inline void swow_buffer_unallocated_argument_error(uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num) { #define BUFFER_IS_UNALLOCATED_FMT "buffer is not unallocated" if (vector_arg_num == 0) { zend_argument_value_error(arg_num, BUFFER_IS_UNALLOCATED_FMT); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT "($buffer) " BUFFER_IS_UNALLOCATED_FMT, VECTOR_POSTION_C); } #undef BUFFER_IS_UNALLOCATED_FMT } static ZEND_COLD zend_never_inline void swow_buffer_argument_can_not_be_negative_error(uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name, zend_long arg) { #define CAN_NOT_BE_NEGATIVE_FMT "can not be negative" if (vector_arg_num == 0) { zend_argument_value_error(arg_num, CAN_NOT_BE_NEGATIVE_FMT); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT ZEND_LONG_ARG_FMT CAN_NOT_BE_NEGATIVE_FMT, VECTOR_POSTION_C, ZEND_LONG_ARG_C); } #undef CAN_NOT_BE_NEGATIVE_FMT } static ZEND_COLD zend_never_inline void swow_buffer_argument_can_not_be_greater_than_its_x_error(const char *type, uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name, zend_long arg, const char *x_name, size_t x) { #define CAN_NOT_BE_GREATER_THAN_ITS_X_FMT "can not be greater than %s %s (%zu)" #define CAN_NOT_BE_GREATER_THAN_ITS_X_C type, x_name, x if (vector_arg_num == 0) { zend_argument_value_error(arg_num, CAN_NOT_BE_GREATER_THAN_ITS_X_FMT, CAN_NOT_BE_GREATER_THAN_ITS_X_C); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT ZEND_LONG_ARG_FMT CAN_NOT_BE_GREATER_THAN_ITS_X_FMT, VECTOR_POSTION_C, ZEND_LONG_ARG_C, CAN_NOT_BE_GREATER_THAN_ITS_X_C); } #undef CAN_NOT_BE_GREATER_THAN_ITS_X_C } static ZEND_COLD zend_never_inline void swow_buffer_argument_can_not_be_equal_to_its_x_error(const char *type, uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name, zend_long arg, const char *x_name, size_t x) { #define CAN_NOT_BE_EQUAL_TO_ITS_X_FMT "can not be equal to %s %s (%zu)" #define CAN_NOT_BE_EQUAL_TO_ITS_X_C type, x_name, x if (vector_arg_num == 0) { zend_argument_value_error(arg_num, CAN_NOT_BE_EQUAL_TO_ITS_X_FMT, CAN_NOT_BE_EQUAL_TO_ITS_X_C); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT ZEND_LONG_ARG_FMT CAN_NOT_BE_EQUAL_TO_ITS_X_FMT, VECTOR_POSTION_C, ZEND_LONG_ARG_C, CAN_NOT_BE_EQUAL_TO_ITS_X_C); } #undef CAN_NOT_BE_EQUAL_TO_ITS_X_C } static ZEND_COLD zend_never_inline void swow_buffer_argument_with_x_can_not_be_greater_than_its_y_error(const char *type, uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name, zend_long arg, const char *x_name, size_t x, const char *y_name, size_t y) { #define WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_FMT "with %s (" ZEND_LONG_FMT ") can not be greater than %s %s (%zu)" #define WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_C x_name, x, type, y_name, y if (vector_arg_num == 0) { zend_argument_value_error(arg_num + 0, WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_FMT, WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_C); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT ZEND_LONG_ARG_FMT WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_FMT, VECTOR_POSTION_C, ZEND_LONG_ARG_C, WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_C); } #undef WITH_X_CAN_NOT_BE_GREATER_THAN_ITS_Y_FMT } static ZEND_COLD zend_never_inline void swow_buffer_argument_can_only_be_minus_1_to_refer_to_unlimited_when_it_is_negative_error(uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name, zend_long arg) { #define CAN_ONLY_BE_MINUS_1_TO_REFER_TO_UNLIMITED_WHEN_IT_IS_NEGATIVE_FMT "can only be -1 to refer to unlimited when it is negative" if (vector_arg_num == 0) { zend_argument_value_error(arg_num, CAN_ONLY_BE_MINUS_1_TO_REFER_TO_UNLIMITED_WHEN_IT_IS_NEGATIVE_FMT); } else { zend_argument_value_error(vector_arg_num, VECTOR_POSITION_FMT ZEND_LONG_ARG_FMT CAN_ONLY_BE_MINUS_1_TO_REFER_TO_UNLIMITED_WHEN_IT_IS_NEGATIVE_FMT, VECTOR_POSTION_C, ZEND_LONG_ARG_C); } #undef CAN_ONLY_BE_MINUS_1_TO_REFER_TO_UNLIMITED_WHEN_IT_IS_NEGATIVE_FMT } static ZEND_COLD zend_never_inline void swow_buffer_argument_can_not_be_zero_error(uint32_t vector_arg_num, uint32_t vector_index, uint32_t arg_num, const char *arg_name) { #define NO_ENOUGH_WRITABLE_BUFFER_SPACE_FMT "can not be 0" if (vector_arg_num == 0) { zend_argument_value_error(arg_num, NO_ENOUGH_WRITABLE_BUFFER_SPACE_FMT); } else { zend_argument_value_error( vector_arg_num, VECTOR_POSITION_FMT "($%s)" NO_ENOUGH_WRITABLE_BUFFER_SPACE_FMT, VECTOR_POSTION_C, arg_name ); } #undef NO_ENOUGH_WRITABLE_BUFFER_SPACE_FMT } #undef VECTOR_POSTION_C #undef VECTOR_POSITION_FMT static zend_always_inline bool swow_buffer__check_readable_space(const char *type, size_t buffer_length, zend_long user_start, zend_long *user_length_ptr, uint32_t vector_arg_num, uint32_t vector_index, uint32_t base_arg_num) { if (UNEXPECTED(user_start < 0)) { swow_buffer_argument_can_not_be_negative_error(vector_arg_num, vector_index, base_arg_num, "start", user_start); return false; } if (UNEXPECTED(((size_t) user_start) > buffer_length)) { /* we do not expect user to read uninitialized memory */ swow_buffer_argument_can_not_be_greater_than_its_x_error(type, vector_arg_num, vector_index, base_arg_num, "start", user_start, "length", buffer_length); return false; } zend_long user_length = *user_length_ptr; if (user_length == -1) { user_length = buffer_length - user_start; } if (UNEXPECTED(user_length < 0)) { swow_buffer_argument_can_only_be_minus_1_to_refer_to_unlimited_when_it_is_negative_error(vector_arg_num, vector_index, base_arg_num + 1, "length", user_length); return false; } if (UNEXPECTED(((size_t) (user_start + user_length)) > buffer_length)) { swow_buffer_argument_with_x_can_not_be_greater_than_its_y_error(type, vector_arg_num, vector_index, base_arg_num + 1, "length", user_length, "start", user_start, "length", buffer_length); return false; } *user_length_ptr = user_length; return true; } static zend_always_inline bool swow_buffer__check_writable_space(size_t buffer_size, size_t buffer_length, zend_long user_offset, zend_long *user_size_ptr, uint32_t vector_arg_num, uint32_t vector_index, uint32_t base_arg_num) { if (UNEXPECTED(user_offset < 0)) { swow_buffer_argument_can_not_be_negative_error(vector_arg_num, vector_index, base_arg_num, "offset", user_offset); return false; } if (UNEXPECTED(((size_t) user_offset) > buffer_length)) { ZEND_ASSERT(buffer_length <= buffer_size); /* we do not expect user to cross uninitialized memory to write */ swow_buffer_argument_can_not_be_greater_than_its_x_error("buffer", vector_arg_num, vector_index, base_arg_num, "offset", user_offset, "length", buffer_length); return false; } if (UNEXPECTED(((size_t) user_offset) == buffer_size)) { swow_buffer_argument_can_not_be_equal_to_its_x_error("buffer", vector_arg_num, vector_index, base_arg_num, "offset", user_offset, "size", buffer_size); return false; } zend_long user_size = *user_size_ptr; if (user_size == -1) { user_size = buffer_size - user_offset; } if (UNEXPECTED(user_size < 0)) { swow_buffer_argument_can_only_be_minus_1_to_refer_to_unlimited_when_it_is_negative_error(vector_arg_num, vector_index, base_arg_num + 1, "size", user_size); return false; } if (UNEXPECTED(user_size == 0)) { swow_buffer_argument_can_not_be_zero_error(vector_arg_num, vector_index, base_arg_num + 1, "size"); return false; } if (UNEXPECTED(((size_t) (user_offset + user_size)) > buffer_size)) { swow_buffer_argument_with_x_can_not_be_greater_than_its_y_error("buffer", vector_arg_num, vector_index, base_arg_num + 1, "size", user_size, "offset", user_offset, "size", buffer_size); return false; } *user_size_ptr = user_size; return true; } SWOW_API const char *swow_string_get_readable_space_v(zend_string *string, zend_long start, zend_long *length, uint32_t vector_arg_num, uint32_t vector_index, uint32_t base_arg_num) { if (!swow_buffer__check_readable_space("string", ZSTR_LEN(string), start, length, vector_arg_num, vector_index, base_arg_num + 1)) { return NULL; } return ZSTR_VAL(string) + start; } SWOW_API const char *swow_buffer_get_readable_space_v(swow_buffer_t *s_buffer, zend_long start, zend_long *length, uint32_t vector_arg_num, uint32_t vector_index, uint32_t base_arg_num) { // Note: This seems reasonable for get readable space on unallocated buffer and got a empty string if (UNEXPECTED(s_buffer->buffer.value == NULL)) { *length = 0; return ""; } if (!swow_buffer__check_readable_space("buffer", s_buffer->buffer.length, start, length, vector_arg_num, vector_index, base_arg_num + 1)) { return NULL; } return s_buffer->buffer.value + start; } SWOW_API char *swow_buffer_get_writable_space_v(swow_buffer_t *s_buffer, zend_long offset, zend_long *size, uint32_t vector_arg_num, uint32_t vector_index, uint32_t base_arg_num) { if (UNEXPECTED(s_buffer->buffer.value == NULL)) { swow_buffer_unallocated_argument_error(vector_arg_num, vector_index, base_arg_num); return NULL; } if (!swow_buffer__check_writable_space(s_buffer->buffer.size, s_buffer->buffer.length, offset, size, vector_arg_num, vector_index, base_arg_num + 1)) { return NULL; } return s_buffer->buffer.value + offset; } SWOW_API void swow_buffer_virtual_write(swow_buffer_t *s_buffer, size_t offset, size_t length) { cat_buffer_t *buffer = &s_buffer->buffer; zend_string *string = swow_buffer_get_string_from_handle(buffer); size_t new_length = offset + length; if (EXPECTED(new_length > buffer->length)) { ZSTR_VAL(string)[ZSTR_LEN(string) = (buffer->length = new_length)] = '\0'; } } SWOW_API void swow_buffer_update(swow_buffer_t *s_buffer, size_t length) { cat_buffer_t *buffer = &s_buffer->buffer; zend_string *string = swow_buffer_get_string_from_handle(buffer); ZSTR_VAL(string)[ZSTR_LEN(string) = (buffer->length = length)] = '\0'; } static zend_always_inline void swow_buffer_reset(swow_buffer_t *s_buffer) { ZEND_ASSERT(s_buffer->locker == NULL); } static zend_always_inline void swow_buffer_close(swow_buffer_t *s_buffer) { cat_buffer_close(&s_buffer->buffer); swow_buffer_reset(s_buffer); } static zend_object *swow_buffer_create_object(zend_class_entry *ce) { swow_buffer_t *s_buffer = swow_object_alloc(swow_buffer_t, ce, swow_buffer_handlers); cat_buffer_init(&s_buffer->buffer); s_buffer->locker = NULL; return &s_buffer->std; } static void swow_buffer_free_object(zend_object *object) { swow_buffer_t *s_buffer = swow_buffer_get_from_object(object); cat_buffer_close(&s_buffer->buffer); zend_object_std_dtor(&s_buffer->std); } #define getThisBuffer() (swow_buffer_get_from_object(Z_OBJ_P(ZEND_THIS))) #define SWOW_BUFFER_GETTER(_s_buffer, _buffer) \ swow_buffer_t *_s_buffer = getThisBuffer(); \ cat_buffer_t *buffer = &s_buffer->buffer; \ static zend_never_inline void swow_buffer_separate(swow_buffer_t *s_buffer) { cat_buffer_t new_buffer; CAT_LOG_DEBUG_VA_WITH_LEVEL(BUFFER, 5, { char *s; CAT_LOG_DEBUG_D(HTTP, "Buffer separate occurred (length=%zu, value=%s)", s_buffer->buffer.length, cat_log_str_quote(s_buffer->buffer.value, s_buffer->buffer.length, &s)); cat_free(s); }); (void) cat_buffer_dup(&s_buffer->buffer, &new_buffer); cat_buffer_close(&s_buffer->buffer); s_buffer->buffer = new_buffer; } SWOW_API void swow_buffer_cow(swow_buffer_t *s_buffer) { if (s_buffer->buffer.value != NULL) { zend_string *string = swow_buffer_get_string_from_handle(&s_buffer->buffer); if (GC_REFCOUNT(string) != 1 || ZSTR_IS_INTERNED(string) || (GC_FLAGS(string) & IS_STR_PERSISTENT)) { swow_buffer_separate(s_buffer); } } } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_alignSize, 0, 0, IS_LONG, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, size, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, alignment, IS_LONG, 0, "0") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, alignSize) { zend_long size = 0, alignment = 0; ZEND_PARSE_PARAMETERS_START(0, 2) Z_PARAM_OPTIONAL Z_PARAM_LONG(size) Z_PARAM_LONG(alignment) ZEND_PARSE_PARAMETERS_END(); size = cat_buffer_align_size(size, alignment); RETURN_LONG(size); } static PHP_METHOD_EX(Swow_Buffer, create) { SWOW_BUFFER_GETTER(s_buffer, buffer); zend_long size; cat_bool_t ret; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(size) ZEND_PARSE_PARAMETERS_END(); if (UNEXPECTED(size < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } ret = cat_buffer_alloc(buffer, size); if (UNEXPECTED(!ret)) { swow_throw_exception_with_last(swow_buffer_exception_ce); RETURN_THROWS(); } } ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Swow_Buffer___construct, 0, 0, 1) ZEND_ARG_TYPE_INFO(0, size, IS_LONG, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, __construct) { PHP_METHOD_CALL(Swow_Buffer, create); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_alloc, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, size, IS_LONG, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, alloc) { PHP_METHOD_CALL(Swow_Buffer, create); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_getSize, 0, 0, IS_LONG, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, getSize) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_LONG(buffer->size); } #define arginfo_class_Swow_Buffer_getLength arginfo_class_Swow_Buffer_getSize static PHP_METHOD(Swow_Buffer, getLength) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_LONG(buffer->length); } #define arginfo_class_Swow_Buffer_getAvailableSize arginfo_class_Swow_Buffer_getSize static PHP_METHOD(Swow_Buffer, getAvailableSize) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_LONG(buffer->size - buffer->length); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_isAvailable, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, isAvailable) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_BOOL(buffer->value != NULL); } #define arginfo_class_Swow_Buffer_isEmpty arginfo_class_Swow_Buffer_isAvailable static PHP_METHOD(Swow_Buffer, isEmpty) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_BOOL(buffer->length == 0); } #define arginfo_class_Swow_Buffer_isFull arginfo_class_Swow_Buffer_isAvailable static PHP_METHOD(Swow_Buffer, isFull) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_BOOL(buffer->length == buffer->size); } #define arginfo_class_Swow_Buffer_realloc arginfo_class_Swow_Buffer_alloc static PHP_METHOD(Swow_Buffer, realloc) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_long size; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(size) ZEND_PARSE_PARAMETERS_END(); if (UNEXPECTED(size < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } (void) cat_buffer_realloc(buffer, size); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_extend, 0, 0, IS_VOID, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, recommendSize, IS_LONG, 0, "0") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, extend) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_long recommend_size = 0; ZEND_PARSE_PARAMETERS_START(0, 1) Z_PARAM_OPTIONAL Z_PARAM_LONG(recommend_size) ZEND_PARSE_PARAMETERS_END(); if (recommend_size == 0) { recommend_size = buffer->size + buffer->size; } if (UNEXPECTED(recommend_size < 0 || (size_t) recommend_size <= buffer->size)) { zend_argument_value_error(1, "must be greater than current buffer size"); RETURN_THROWS(); } (void) cat_buffer_extend(buffer, recommend_size); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_prepare, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, appendLength, IS_LONG, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, prepare) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_long append_length; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(append_length) ZEND_PARSE_PARAMETERS_END(); if (UNEXPECTED(append_length < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } (void) cat_buffer_prepare(buffer, append_length); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_mallocTrim, 0, 0, IS_VOID, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, mallocTrim) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); cat_bool_t ret; ZEND_PARSE_PARAMETERS_NONE(); ret = cat_buffer_malloc_trim(buffer); if (UNEXPECTED(!ret)) { swow_throw_exception_with_last(swow_buffer_exception_ce); RETURN_THROWS(); } /* Notice: about shared: it not works when it's shared (due to length == size) */ } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_read, 0, 0, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, start, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "-1") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, read) { swow_buffer_t *s_buffer = getThisBuffer(); zend_long length = -1; zend_long start = 0; ZEND_PARSE_PARAMETERS_START(0, 2) Z_PARAM_OPTIONAL Z_PARAM_LONG(start) Z_PARAM_LONG(length) ZEND_PARSE_PARAMETERS_END(); const char *ptr = swow_buffer_get_readable_space(s_buffer, start, &length, 1); if (UNEXPECTED(ptr == NULL)) { RETURN_THROWS(); } RETURN_STRINGL_FAST(ptr, length); } static PHP_METHOD_EX(Swow_Buffer, _write, const zend_bool append) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_string *string; zend_long offset = append ? buffer->length : 0; zend_long start = 0; zend_long length = -1; const char *ptr; ZEND_PARSE_PARAMETERS_START(append ? 1 : 2, append ? 3 : 4) if (!append) { Z_PARAM_LONG(offset) } SWOW_PARAM_STRINGABLE_EXPECT_BUFFER_FOR_READING(string) Z_PARAM_OPTIONAL /* where to start copying strings */ Z_PARAM_LONG(start) Z_PARAM_LONG(length) ZEND_PARSE_PARAMETERS_END(); ptr = swow_string_get_readable_space(string, start, &length, append ? 1 : 2); // FIXME: strpos argument error is mis pos if (UNEXPECTED(ptr == NULL)) { RETURN_THROWS(); } if (UNEXPECTED(length == 0)) { RETURN_LONG(0); } if (!append) { if (UNEXPECTED(offset < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } if (UNEXPECTED((size_t) offset > buffer->length)) { zend_argument_value_error(1, "can not be greater than current buffer length"); RETURN_THROWS(); } } if (offset == 0 && start == 0 && (size_t) length == ZSTR_LEN(string) && (size_t) length >= buffer->size) { swow_buffer_close(s_buffer); /* Notice: string maybe interned, so we must use zend_string_copy() here */ buffer->value = ZSTR_VAL(zend_string_copy(string)); buffer->size = buffer->length = ZSTR_LEN(string); } else { /* TODO: Optimized COW: it's not required to always copy string, * if we just write to offset which is not the end of buffer, * it maybe better that only copy the data that doesn't change. */ swow_buffer_cow(s_buffer); (void) cat_buffer_write(buffer, offset, ptr, length); } RETURN_LONG(length); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_write, 0, 2, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, offset, IS_LONG, 0) ZEND_ARG_OBJ_TYPE_MASK(0, string, Stringable, MAY_BE_STRING, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, start, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "-1") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, write) { PHP_METHOD_CALL(Swow_Buffer, _write, false); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_append, 0, 1, IS_LONG, 0) ZEND_ARG_OBJ_TYPE_MASK(0, string, Stringable, MAY_BE_STRING, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, start, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "-1") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, append) { PHP_METHOD_CALL(Swow_Buffer, _write, true); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_truncate, 0, 1, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, length, IS_LONG, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, truncate) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_long length; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(length) ZEND_PARSE_PARAMETERS_END(); if (UNEXPECTED(length < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } swow_buffer_cow(s_buffer); cat_buffer_truncate(buffer, length); RETURN_LONG(buffer->length); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_truncateFrom, 0, 0, IS_LONG, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, offset, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "-1") ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, truncateFrom) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); zend_long offset = 0; zend_long length = -1; ZEND_PARSE_PARAMETERS_START(0, 2) Z_PARAM_OPTIONAL Z_PARAM_LONG(offset) Z_PARAM_LONG(length) ZEND_PARSE_PARAMETERS_END(); if (UNEXPECTED(offset < 0)) { zend_argument_value_error(1, "can not be negative"); RETURN_THROWS(); } if (EXPECTED(length == -1)) { length = ZEND_LONG_MAX; } else if (UNEXPECTED(length < 0)) { zend_argument_value_error(2, "should be greater than or equal to -1"); RETURN_THROWS(); } swow_buffer_cow(s_buffer); cat_buffer_truncate_from(buffer, offset, length); RETURN_LONG(buffer->length); } #define arginfo_class_Swow_Buffer_clear arginfo_class_Swow_Buffer_mallocTrim static PHP_METHOD(Swow_Buffer, clear) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); ZEND_PARSE_PARAMETERS_NONE(); swow_buffer_cow(s_buffer); cat_buffer_clear(buffer); swow_buffer_reset(s_buffer); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer_fetchString, 0, 0, IS_STRING, 0) ZEND_END_ARG_INFO() /* different from __toString , it transfers ownership to return_value */ static PHP_METHOD(Swow_Buffer, fetchString) { SWOW_BUFFER_GETTER(s_buffer, buffer); SWOW_BUFFER_CHECK_LOCK(s_buffer); char *value; ZEND_PARSE_PARAMETERS_NONE(); value = cat_buffer_fetch(buffer); if (UNEXPECTED(value == NULL)) { RETURN_EMPTY_STRING(); } swow_buffer_reset(s_buffer); RETURN_STR((zend_string *) (value - offsetof(zend_string, val))); } #define arginfo_class_Swow_Buffer_dupString arginfo_class_Swow_Buffer_fetchString /* return string copy immediately */ static PHP_METHOD(Swow_Buffer, dupString) { SWOW_BUFFER_GETTER(s_buffer, buffer); ZEND_PARSE_PARAMETERS_NONE(); RETURN_STRINGL_FAST(buffer->value, buffer->length); } #define arginfo_class_Swow_Buffer_toString arginfo_class_Swow_Buffer_fetchString /* return string is just readonly (COW) */ static PHP_METHOD(Swow_Buffer, toString) { zend_string *string; ZEND_PARSE_PARAMETERS_NONE(); string = swow_buffer_get_string(getThisBuffer()); if (UNEXPECTED(string == NULL)) { RETURN_EMPTY_STRING(); } /* Notice: string maybe interned, so we must use zend_string_copy() here */ RETURN_STR(zend_string_copy(string)); } #define arginfo_class_Swow_Buffer_isLocked arginfo_class_Swow_Buffer_isAvailable static PHP_METHOD(Swow_Buffer, isLocked) { swow_buffer_t *s_buffer = getThisBuffer(); ZEND_PARSE_PARAMETERS_NONE(); RETURN_BOOL(swow_buffer_get_locker(s_buffer) != NULL); } ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_Swow_Buffer_getLocker, 0, 0, Swow\\Coroutine, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, getLocker) { swow_buffer_t *s_buffer = getThisBuffer(); ZEND_PARSE_PARAMETERS_NONE(); swow_coroutine_t *locker = swow_buffer_get_locker(s_buffer); if (UNEXPECTED(locker == NULL)) { RETURN_NULL(); } RETVAL_OBJ_COPY(&locker->std); } #define arginfo_class_Swow_Buffer_tryLock arginfo_class_Swow_Buffer_isAvailable static PHP_METHOD(Swow_Buffer, tryLock) { swow_buffer_t *s_buffer = getThisBuffer(); ZEND_PARSE_PARAMETERS_NONE(); if (UNEXPECTED(swow_buffer_get_locker(s_buffer) != NULL)) { RETURN_FALSE; } bool ret = swow_buffer_lock(s_buffer); ZEND_ASSERT(ret); RETURN_BOOL(ret); } #define arginfo_class_Swow_Buffer_lock arginfo_class_Swow_Buffer_mallocTrim static PHP_METHOD(Swow_Buffer, lock) { swow_buffer_t *s_buffer = getThisBuffer(); ZEND_PARSE_PARAMETERS_NONE(); if (UNEXPECTED(!swow_buffer_lock(s_buffer))) { RETURN_THROWS(); } } #define arginfo_class_Swow_Buffer_unlock arginfo_class_Swow_Buffer_mallocTrim static PHP_METHOD(Swow_Buffer, unlock) { swow_buffer_t *s_buffer = getThisBuffer(); ZEND_PARSE_PARAMETERS_NONE(); if (UNEXPECTED(!swow_buffer_unlock(s_buffer))) { RETURN_THROWS(); } } #define arginfo_class_Swow_Buffer_close arginfo_class_Swow_Buffer_mallocTrim static PHP_METHOD(Swow_Buffer, close) { swow_buffer_t *s_buffer = getThisBuffer(); SWOW_BUFFER_CHECK_LOCK(s_buffer); ZEND_PARSE_PARAMETERS_NONE(); swow_buffer_close(s_buffer); } #define arginfo_class_Swow_Buffer___toString arginfo_class_Swow_Buffer_fetchString #define zim_Swow_Buffer___toString zim_Swow_Buffer_toString ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Swow_Buffer___debugInfo, 0, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() static PHP_METHOD(Swow_Buffer, __debugInfo) { SWOW_BUFFER_GETTER(s_buffer, buffer); zval z_debug_info; ZEND_PARSE_PARAMETERS_NONE(); array_init(&z_debug_info); // TODO: support configure it to use str_quote() and maxlen if (buffer->value == NULL) { add_assoc_str(&z_debug_info, "value", zend_empty_string); } else { const int maxlen = -1; char *chunk = NULL; if (maxlen > 0 && buffer->length > (size_t) maxlen) { chunk = cat_sprintf("%.*s...", maxlen, buffer->value); } if (chunk != NULL) { add_assoc_stringl(&z_debug_info, "value", chunk, maxlen); cat_free(chunk); } else { zend_string *string = swow_buffer_get_string(s_buffer); add_assoc_str(&z_debug_info, "value", zend_string_copy(string)); } } add_assoc_long(&z_debug_info, "size", buffer->size); add_assoc_long(&z_debug_info, "length", buffer->length); if (s_buffer->locker) { GC_ADDREF(&s_buffer->locker->std); add_assoc_object(&z_debug_info, "locker", &s_buffer->locker->std); } RETURN_DEBUG_INFO_WITH_PROPERTIES(&z_debug_info); } static const zend_function_entry swow_buffer_methods[] = { PHP_ME(Swow_Buffer, alignSize, arginfo_class_Swow_Buffer_alignSize, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_ME(Swow_Buffer, __construct, arginfo_class_Swow_Buffer___construct, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, alloc, arginfo_class_Swow_Buffer_alloc, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, getSize, arginfo_class_Swow_Buffer_getSize, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, getLength, arginfo_class_Swow_Buffer_getLength, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, getAvailableSize, arginfo_class_Swow_Buffer_getAvailableSize, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, isAvailable, arginfo_class_Swow_Buffer_isAvailable, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, isEmpty, arginfo_class_Swow_Buffer_isEmpty, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, isFull, arginfo_class_Swow_Buffer_isFull, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, realloc, arginfo_class_Swow_Buffer_realloc, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, extend, arginfo_class_Swow_Buffer_extend, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, prepare, arginfo_class_Swow_Buffer_prepare, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, mallocTrim, arginfo_class_Swow_Buffer_mallocTrim, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, read, arginfo_class_Swow_Buffer_read, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, write, arginfo_class_Swow_Buffer_write, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, append, arginfo_class_Swow_Buffer_append, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, truncate, arginfo_class_Swow_Buffer_truncate, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, truncateFrom, arginfo_class_Swow_Buffer_truncateFrom, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, clear, arginfo_class_Swow_Buffer_clear, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, fetchString, arginfo_class_Swow_Buffer_fetchString, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, dupString, arginfo_class_Swow_Buffer_dupString, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, toString, arginfo_class_Swow_Buffer_toString, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, isLocked, arginfo_class_Swow_Buffer_isLocked, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, getLocker, arginfo_class_Swow_Buffer_getLocker, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, tryLock, arginfo_class_Swow_Buffer_tryLock, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, lock, arginfo_class_Swow_Buffer_lock, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, unlock, arginfo_class_Swow_Buffer_unlock, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, close, arginfo_class_Swow_Buffer_close, ZEND_ACC_PUBLIC) /* magic */ PHP_ME(Swow_Buffer, __toString, arginfo_class_Swow_Buffer___toString, ZEND_ACC_PUBLIC) PHP_ME(Swow_Buffer, __debugInfo, arginfo_class_Swow_Buffer___debugInfo, ZEND_ACC_PUBLIC) PHP_FE_END }; static zend_object *swow_buffer_clone_object(zend_object *object) { swow_buffer_t *s_buffer, *new_s_buffer; zend_string *string; s_buffer = swow_buffer_get_from_object(object); string = swow_buffer_get_string(s_buffer); new_s_buffer = swow_buffer_get_from_object(swow_object_create(s_buffer->std.ce)); memcpy(new_s_buffer, s_buffer, offsetof(swow_buffer_t, std)); if (string != NULL) { /* Notice: string maybe interned, so we must use zend_string_copy() here */ new_s_buffer->buffer.value = ZSTR_VAL(zend_string_copy(string)); } zend_objects_clone_members(&new_s_buffer->std, object); return &new_s_buffer->std; } static zend_result swow_buffer_cast_object(zend_object *object, zval *result, int type) { /* __toString() function maybe rewritten on PHP layer */ if (EXPECTED(type == IS_STRING && object->ce->__tostring == swow_buffer_ce->__tostring)) { swow_buffer_t *s_buffer = swow_buffer_get_from_object(object); ZVAL_STR_COPY(result, swow_buffer_get_string_for_reading(s_buffer)); return SUCCESS; } return zend_std_cast_object_tostring(object, result, type); } static char *swow_buffer_alloc_standard(size_t size) { zend_string *string = zend_string_alloc(size, 0); ZSTR_VAL(string)[ZSTR_LEN(string) = 0] = '\0'; return ZSTR_VAL(string); } static char *swow_buffer_realloc_standard(char *old_value, size_t new_size) { zend_string *old_string = old_value != NULL ? swow_buffer_get_string_from_value(old_value) : NULL; zend_string *new_string; size_t old_length = old_string != NULL ? ZSTR_LEN(old_string) : 0; size_t new_length = MIN(old_length, new_size); zend_bool do_erealloc; if ( /* zend string do not support realloc from NULL */ old_string != NULL && /* realloc on persistent or interned, it means buffer is shared, * we should allocate a new non-persistent string */ !(GC_FLAGS(old_string) & IS_STR_PERSISTENT) && !ZSTR_IS_INTERNED(old_string) && /* COW can be skipped */ GC_REFCOUNT(old_string) == 1 ) { do_erealloc = true; } else { do_erealloc = false; } if (do_erealloc) { new_string = (zend_string *) erealloc(old_string, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(new_size))); zend_string_forget_hash_val(new_string); } else { new_string = zend_string_alloc(new_size, false); memcpy(ZSTR_VAL(new_string), ZSTR_VAL(old_string), new_length); if (old_string != NULL && !ZSTR_IS_INTERNED(old_string)) { GC_DELREF(old_string); } } ZSTR_VAL(new_string)[ZSTR_LEN(new_string) = new_length] = '\0'; return ZSTR_VAL(new_string); } static void swow_buffer_update_standard(char *value, size_t new_length) { zend_string *string = swow_buffer_get_string_from_value(value); ZSTR_VAL(string)[ZSTR_LEN(string) = new_length] = '\0'; } static void swow_buffer_free_standard(char *value) { /* Notice: string maybe interned or persistent, so we should use zend_string_release() here */ zend_string_release(swow_buffer_get_string_from_value(value)); } SWOW_API const cat_buffer_allocator_t swow_buffer_allocator = { swow_buffer_alloc_standard, swow_buffer_realloc_standard, swow_buffer_update_standard, swow_buffer_free_standard, }; zend_result swow_buffer_module_init(INIT_FUNC_ARGS) { if (unlikely(!cat_buffer_module_init())) { return FAILURE; } if (unlikely(!cat_buffer_register_allocator(&swow_buffer_allocator))) { return FAILURE; } swow_buffer_ce = swow_register_internal_class( "Swow\\Buffer", NULL, swow_buffer_methods, &swow_buffer_handlers, NULL, cat_true, cat_false, swow_buffer_create_object, swow_buffer_free_object, XtOffsetOf(swow_buffer_t, std) ); swow_buffer_handlers.clone_obj = swow_buffer_clone_object; swow_buffer_handlers.cast_object = swow_buffer_cast_object; zend_declare_class_constant_long(swow_buffer_ce, ZEND_STRL("PAGE_SIZE"), cat_getpagesize()); zend_declare_class_constant_long(swow_buffer_ce, ZEND_STRL("COMMON_SIZE"), CAT_BUFFER_COMMON_SIZE); swow_buffer_exception_ce = swow_register_internal_class( "Swow\\BufferException", swow_exception_ce, NULL, NULL, NULL, cat_true, cat_true, NULL, NULL, 0 ); return SUCCESS; }
dabf5da7f1bf9ed2e19f53a5d4581fde4bd67653
39568e19301a7a112398be542154950af25591de
/hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/directed_tests/ibex_macros.h
ac105dc4efd08a17d488fe6bd315d11966efdcd7
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lowRISC/opentitan
493995bc7cf7cb3aee486a5203af3fd62bba3bfc
51f6017b8425b14d5a4aa9abace8fe5a25ef08c8
refs/heads/master
2023-08-31T22:05:09.425796
2023-08-14T14:52:15
2023-08-31T20:31:13
204,516,692
2,077
634
Apache-2.0
2023-09-14T21:16:21
2019-08-26T16:30:16
SystemVerilog
UTF-8
C
false
false
1,017
h
ibex_macros.h
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // Ibex specific macros #define SIGNATURE_ADDR 0x8ffffff8 // signatue type - should be stored at sign_addr[7:0] #define CORE_STATUS 0x0 #define TEST_RESULT 0x1 #define WRITE_GPR 0x2 #define WRITE_CSR 0x3 // core status - should be stored at sign_addr[12:8] #define INITIALIZED 0x0 #define IN_DEBUG_MODE 0x1 #define IN_MACHINE_MODE 0x2 #define IN_HYPERVISOR_MODE 0x3 #define IN_SUPERVISOR_MODE 0x4 #define IN_USER_MODE 0x5 #define HANDLING_IRQ 0x6 #define FINISHED_IRQ 0x7 #define HANDLING_EXCEPTION 0x8 #define INSTR_FAULT_EXCEPTION 0x9 #define ILLEGAL_INSTR_EXCEPTION 0xa #define LOAD_FAULT_EXCEPTION 0xb #define STORE_FAULT_EXCEPTION 0xc #define EBREAK_EXCEPTION 0xd // test result - should be stored at sign_addr[8] #define TEST_PASS 0x0 #define TEST_FAIL 0x1 #define CSR_MSECCFG 0x747 #define MSECCFG_MML 0x1 #define MSECCFG_MMWP 0x2 #define MSECCFG_RLB 0x4
1c4e45951af051b57ddc7f8a69f2a7289f0deb07
ec6a71b57ebe88538269197fd16bede6bc2062ae
/erts/emulator/beam/erl_process_dict.c
b2027fe207d7396438f22f4ace014aee4df1e371
[ "Apache-2.0" ]
permissive
erlang/otp
7c6e88ca955bd6a3ede1530154c80e8ce449a370
334589af62a8db25a81afba2ecc50f33ff69ddb8
refs/heads/master
2023-08-30T23:37:28.061328
2023-08-30T04:20:48
2023-08-30T04:20:48
374,927
9,920
3,018
Apache-2.0
2023-09-14T10:37:26
2009-11-16T17:17:57
Erlang
UTF-8
C
false
false
26,024
c
erl_process_dict.c
/* * %CopyrightBegin% * * Copyright Ericsson AB 1999-2021. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ /* * Code for process dictionaries. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "sys.h" #include "erl_vm.h" #include "global.h" #include "erl_process.h" /* Will include erl_process_dict.h */ #include "error.h" #include "erl_driver.h" #include "bif.h" #include "big.h" #include "dist.h" #include "erl_version.h" /* #define HARDDEBUG */ /* ** Utility macros */ /* Flags to pd_get_hash */ #define PD_GET_OTHER_PROCESS 1UL /* Hash constant macros */ #define MAX_HASH 1342177280UL #define INITIAL_SIZE (erts_pd_initial_size) /* Hash utility macros */ #define HASH_RANGE(PDict) ((PDict)->usedSlots) #define MAKE_HASH(Term) \ ((is_small(Term)) ? (erts_ihash_t) unsigned_val(Term) : \ ((is_atom(Term)) ? \ (erts_ihash_t) atom_val(Term) : \ erts_internal_hash(Term))) #define PD_SZ2BYTES(Sz) (sizeof(ProcDict) + ((Sz) - 1)*sizeof(Eterm)) #define pd_hash_value(Pdict, Key) \ pd_hash_value_to_ix(Pdict, MAKE_HASH((Key))) /* Memory allocation macros */ #define PD_ALLOC(Sz) \ erts_alloc(ERTS_ALC_T_PROC_DICT, (Sz)) #define PD_FREE(P, Sz) \ erts_free(ERTS_ALC_T_PROC_DICT, (P)) #define PD_REALLOC(P, OSz, NSz) \ erts_realloc(ERTS_ALC_T_PROC_DICT, (P), (NSz)) #define TCAR(Term) CAR(list_val(Term)) #define TCDR(Term) CDR(list_val(Term)) /* Array access macro */ #define ARRAY_GET(PDict, Index) (ASSERT((Index) < (PDict)->arraySize), \ (PDict)->data[Index]) #define ARRAY_GET_PTR(PDict, Index) (ASSERT((Index) < (PDict)->arraySize), \ &(PDict)->data[Index]) #define ARRAY_PUT(PDict, Index, Val) (ASSERT((Index) < (PDict)->arraySize), \ (PDict)->data[Index] = (Val)) #define IS_POW2(X) ((X) && !((X) & ((X)-1))) /* * Forward decalarations */ static void pd_hash_erase(Process *p, Eterm id, Eterm *ret); static void pd_hash_erase_all(Process *p); static Eterm pd_hash_get_with_hval(Process *p, Eterm bucket, Eterm id); static Eterm pd_hash_get_keys(Process *p, Eterm value); static Eterm pd_hash_get_all_keys(Process *p, ProcDict *pd); static Eterm pd_hash_get_all(Process *p, ProcDict *pd, int keep_dict); static Eterm pd_hash_put(Process *p, Eterm id, Eterm value); static void shrink(Process *p, Eterm* ret); static void grow(Process *p); static void array_shrink(ProcDict **ppd, unsigned int need); static void ensure_array_size(ProcDict**, unsigned int size); static unsigned int pd_hash_value_to_ix(ProcDict *pdict, erts_ihash_t hx); static unsigned int next_array_size(unsigned int need); /* ** Debugging prototypes and macros */ #ifdef HARDDEBUG #include <stdarg.h> static int hdebugf(char *format, ...); static char *hdebugf_file = ""; static int hdebugf_line; #define HDEBUGF(X) ((int) hdebugf_file = __FILE__, hdebugf_line = __LINE__, \ hdebugf X) #ifndef DEBUG #define DEBUG 1 #endif #else /* !HARDDEBUG */ #define HDEBUGF(X) /* Nothing */ #endif /* HARDDEBUG (else) */ #ifdef DEBUG static void pd_check(ProcDict *pd); #define PD_CHECK(PD) pd_check(PD) #else /* !DEBUG */ #define PD_CHECK(PD) /* Nothing */ #endif /* DEBUG (else) */ /* ** External interface */ int erts_pd_set_initial_size(int size) { if (size <= 0) return 0; erts_pd_initial_size = 1 << erts_fit_in_bits_uint(size-1); return 1; } /* * Called from break handler */ void erts_dictionary_dump(fmtfn_t to, void *to_arg, ProcDict *pd) { unsigned int i; #ifdef DEBUG /*PD_CHECK(pd);*/ if (pd == NULL) return; erts_print(to, to_arg, "(size = %d, usedSlots = %d, " "splitPosition = %d, numElements = %d)\n", pd->arraySize, pd->usedSlots, pd->splitPosition, (unsigned int) pd->numElements); for (i = 0; i < HASH_RANGE(pd); ++i) { erts_print(to, to_arg, "%d: %T\n", i, ARRAY_GET(pd, i)); } #else /* !DEBUG */ int written = 0; Eterm t; erts_print(to, to_arg, "["); if (pd != NULL) { for (i = 0; i < HASH_RANGE(pd); ++i) { t = ARRAY_GET(pd, i); if (is_list(t)) { for (; t != NIL; t = TCDR(t)) { erts_print(to, to_arg, written++ ? ",%T" : "%T", TCAR(t)); } } else if (is_tuple(t)) { erts_print(to, to_arg, written++ ? ",%T" : "%T", t); } } } erts_print(to, to_arg, "]"); #endif /* DEBUG (else) */ } void erts_deep_dictionary_dump(fmtfn_t to, void *to_arg, ProcDict* pd, void (*cb)(fmtfn_t, void *, Eterm)) { unsigned int i; Eterm t; if (pd != NULL) { for (i = 0; i < HASH_RANGE(pd); ++i) { t = ARRAY_GET(pd, i); if (is_list(t)) { for (; t != NIL; t = TCDR(t)) { (*cb)(to, to_arg, TCAR(t)); } } else if (is_tuple(t)) { (*cb)(to, to_arg, t); } } } } Uint erts_dicts_mem_size(Process *p) { Uint size = 0; if (p->dictionary) size += PD_SZ2BYTES(p->dictionary->arraySize); return size; } void erts_erase_dicts(Process *p) { if (p->dictionary) { pd_hash_erase_all(p); p->dictionary = NULL; } } /* * Called from process_info/1,2. */ Eterm erts_dictionary_copy(ErtsHeapFactory *hfact, ProcDict *pd, Uint reserve_size) { Eterm res; unsigned int i, num; Uint *sz; Uint szi, rsz = reserve_size; if (pd == NULL) return NIL; PD_CHECK(pd); num = HASH_RANGE(pd); sz = (Uint *) erts_alloc(ERTS_ALC_T_TMP, sizeof(Uint) * pd->numElements); for (i = 0, szi = 0; i < num; ++i) { Eterm tmp = ARRAY_GET(pd, i); if (is_boxed(tmp)) { Uint size; ASSERT(is_tuple(tmp)); size = size_object(tmp) + 2; sz[szi++] = size; rsz += size; } else if (is_list(tmp)) { while (tmp != NIL) { Uint size = size_object(TCAR(tmp)) + 2; sz[szi++] = size; rsz += size; tmp = TCDR(tmp); } } } res = NIL; for (i = 0, szi = 0; i < num; ++i) { Eterm tmp = ARRAY_GET(pd, i); if (is_boxed(tmp)) { Uint size; Eterm el, *hp; ASSERT(is_tuple(tmp)); size = sz[szi++]; rsz -= size; hp = erts_produce_heap(hfact, size, rsz); el = copy_struct(tmp, size-2, &hp, hfact->off_heap); res = CONS(hp, el, res); } else if (is_list(tmp)) { while (tmp != NIL) { Uint size = sz[szi++]; Eterm el, *hp; rsz -= size; hp = erts_produce_heap(hfact, size, rsz); el = copy_struct(TCAR(tmp), size-2, &hp, hfact->off_heap); res = CONS(hp, el, res); tmp = TCDR(tmp); } } } ASSERT(rsz == reserve_size); erts_free(ERTS_ALC_T_TMP, sz); return res; } /* ** BIF interface */ BIF_RETTYPE get_0(BIF_ALIST_0) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = pd_hash_get_all(BIF_P, BIF_P->dictionary, 1); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE get_1(BIF_ALIST_1) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = erts_pd_hash_get(BIF_P, BIF_ARG_1); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE get_keys_0(BIF_ALIST_0) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = pd_hash_get_all_keys(BIF_P,BIF_P->dictionary); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE get_keys_1(BIF_ALIST_1) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = pd_hash_get_keys(BIF_P, BIF_ARG_1); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE put_2(BIF_ALIST_2) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = pd_hash_put(BIF_P, BIF_ARG_1, BIF_ARG_2); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE erase_0(BIF_ALIST_0) { Eterm ret; PD_CHECK(BIF_P->dictionary); ret = pd_hash_get_all(BIF_P, BIF_P->dictionary, 0); pd_hash_erase_all(BIF_P); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } BIF_RETTYPE erase_1(BIF_ALIST_1) { Eterm ret; PD_CHECK(BIF_P->dictionary); pd_hash_erase(BIF_P, BIF_ARG_1, &ret); PD_CHECK(BIF_P->dictionary); BIF_RET(ret); } /* * BIF implementations */ static void pd_hash_erase(Process *p, Eterm id, Eterm *ret) { unsigned int hval; Eterm old; Eterm tmp; unsigned int range; *ret = am_undefined; if (p->dictionary == NULL) { return; } hval = pd_hash_value(p->dictionary, id); old = ARRAY_GET(p->dictionary, hval); if (is_boxed(old)) { /* Tuple */ ASSERT(is_tuple(old)); if (EQ(tuple_val(old)[1], id)) { ARRAY_PUT(p->dictionary, hval, NIL); --(p->dictionary->numElements); *ret = tuple_val(old)[2]; } } else if (is_list(old)) { /* Find cons cell for identical value */ Eterm* prev = &p->dictionary->data[hval]; for (tmp = *prev; tmp != NIL; prev = &TCDR(tmp), tmp = *prev) { if (EQ(tuple_val(TCAR(tmp))[1], id)) { *prev = TCDR(tmp); *ret = tuple_val(TCAR(tmp))[2]; --(p->dictionary->numElements); } } /* If there is only one element left in the list we must remove the list. */ old = ARRAY_GET(p->dictionary, hval); ASSERT(is_list(old)); if (is_nil(TCDR(old))) { ARRAY_PUT(p->dictionary, hval, TCAR(old)); } } else if (is_not_nil(old)) { #ifdef DEBUG erts_fprintf(stderr, "Process dictionary for process %T is broken, trying to " "display term found in line %d:\n" "%T\n", p->common.id, __LINE__, old); #endif erts_exit(ERTS_ERROR_EXIT, "Damaged process dictionary found during erase/1."); } if ((range = HASH_RANGE(p->dictionary)) > INITIAL_SIZE && range / 2 > (p->dictionary->numElements)) { shrink(p, ret); } } static void pd_hash_erase_all(Process *p) { if (p->dictionary != NULL) { PD_FREE(p->dictionary, PD_SZ2BYTES(p->dictionary->size)); p->dictionary = NULL; } } erts_ihash_t erts_pd_make_hx(Eterm key) { return MAKE_HASH(key); } Eterm erts_pd_hash_get_with_hx(Process *p, erts_ihash_t hx, Eterm id) { unsigned int hval; ProcDict *pd = p->dictionary; ASSERT(hx == MAKE_HASH(id)); if (pd == NULL) return am_undefined; hval = pd_hash_value_to_ix(pd, hx); return pd_hash_get_with_hval(p, ARRAY_GET(pd, hval), id); } Eterm erts_pd_hash_get(Process *p, Eterm id) { unsigned int hval; ProcDict *pd = p->dictionary; if (pd == NULL) return am_undefined; hval = pd_hash_value(pd, id); return pd_hash_get_with_hval(p, ARRAY_GET(pd, hval), id); } Eterm pd_hash_get_with_hval(Process *p, Eterm bucket, Eterm id) { if (is_boxed(bucket)) { /* Tuple */ ASSERT(is_tuple(bucket)); if (EQ(tuple_val(bucket)[1], id)) { return tuple_val(bucket)[2]; } } else if (is_list(bucket)) { for (; bucket != NIL && !EQ(tuple_val(TCAR(bucket))[1], id); bucket = TCDR(bucket)) { ; } if (bucket != NIL) { return tuple_val(TCAR(bucket))[2]; } } else if (is_not_nil(bucket)) { #ifdef DEBUG erts_fprintf(stderr, "Process dictionary for process %T is broken, trying to " "display term found in line %d:\n" "%T\n", p->common.id, __LINE__, bucket); #endif erts_exit(ERTS_ERROR_EXIT, "Damaged process dictionary found during get/1."); } return am_undefined; } #define PD_GET_TKEY(Dst,Src) \ do { \ ASSERT(is_tuple((Src))); \ ASSERT(arityval(*((Eterm*)tuple_val((Src)))) == 2); \ (Dst) = ((Eterm*)tuple_val((Src)))[1]; \ } while(0) static Eterm pd_hash_get_all_keys(Process *p, ProcDict *pd) { Eterm* hp; Eterm res = NIL; Eterm tmp, tmp2; unsigned int i; unsigned int num; if (pd == NULL) { return res; } num = HASH_RANGE(pd); hp = HAlloc(p, pd->numElements * 2); for (i = 0; i < num; ++i) { tmp = ARRAY_GET(pd, i); if (is_boxed(tmp)) { PD_GET_TKEY(tmp,tmp); res = CONS(hp, tmp, res); hp += 2; } else if (is_list(tmp)) { while (tmp != NIL) { tmp2 = TCAR(tmp); PD_GET_TKEY(tmp2,tmp2); res = CONS(hp, tmp2, res); hp += 2; tmp = TCDR(tmp); } } } return res; } #undef PD_GET_TKEY static Eterm pd_hash_get_keys(Process *p, Eterm value) { Eterm *hp; Eterm res = NIL; ProcDict *pd = p->dictionary; unsigned int i, num; Eterm tmp, tmp2; if (pd == NULL) { return res; } num = HASH_RANGE(pd); for (i = 0; i < num; ++i) { tmp = ARRAY_GET(pd, i); if (is_boxed(tmp)) { ASSERT(is_tuple(tmp)); if (EQ(tuple_val(tmp)[2], value)) { hp = HAlloc(p, 2); res = CONS(hp, tuple_val(tmp)[1], res); } } else if (is_list(tmp)) { while (tmp != NIL) { tmp2 = TCAR(tmp); if (EQ(tuple_val(tmp2)[2], value)) { hp = HAlloc(p, 2); res = CONS(hp, tuple_val(tmp2)[1], res); } tmp = TCDR(tmp); } } } return res; } static Eterm pd_hash_get_all(Process *p, ProcDict *pd, int keep_dict) { Eterm* hp; Eterm* tp; Eterm res = NIL; Eterm tmp, tmp2; unsigned int i; unsigned int num; Uint need; if (pd == NULL) { return res; } num = HASH_RANGE(pd); /* * If this is not erase/0, then must copy all key-value tuples * as they may be mutated by put/2. */ need = pd->numElements * (keep_dict ? 2+3 : 2); hp = HAlloc(p, need); for (i = 0; i < num; ++i) { tmp = ARRAY_GET(pd, i); if (is_boxed(tmp)) { if (keep_dict) { tp = tuple_val(tmp); tmp = TUPLE2(hp, tp[1], tp[2]); hp += 3; } res = CONS(hp, tmp, res); hp += 2; } else if (is_list(tmp)) { while (tmp != NIL) { tmp2 = TCAR(tmp); if (keep_dict) { tp = tuple_val(tmp2); tmp2 = TUPLE2(hp, tp[1], tp[2]); hp += 3; } res = CONS(hp, tmp2, res); hp += 2; tmp = TCDR(tmp); } } } return res; } static Eterm pd_hash_put(Process *p, Eterm id, Eterm value) { unsigned int hval; Eterm *hp; Eterm *tp; Eterm *bucket; Eterm tpl; Eterm old; Eterm old_val = am_undefined; Eterm tmp; int needed; int new_key = 1; #ifdef DEBUG Eterm *hp_limit; #endif if (p->dictionary == NULL) { /* Create it */ ensure_array_size(&p->dictionary, INITIAL_SIZE); p->dictionary->usedSlots = INITIAL_SIZE; p->dictionary->sizeMask = INITIAL_SIZE*2 - 1; p->dictionary->splitPosition = 0; p->dictionary->numElements = 0; } hval = pd_hash_value(p->dictionary, id); bucket = ARRAY_GET_PTR(p->dictionary, hval); old = *bucket; /* * Calculate the number of heap words needed and garbage * collect if necessary. (Might be a slight overestimation.) */ needed = 3; /* {Key,Value} tuple */ if (is_boxed(old)) { ASSERT(is_tuple(old)); tp = tuple_val(old); if (EQ(tp[1], id)) { old_val = tp[2]; if (is_immed(value)) { tp[2] = value; /* DESTRUCTIVE HEAP ASSIGNMENT */ return old_val; } new_key = 0; } else { needed += 2+2; } } else if (is_list(old)) { Eterm* prev_cdr = bucket; needed += 2; for (tmp = old; tmp != NIL; prev_cdr = &TCDR(tmp), tmp = *prev_cdr) { tp = tuple_val(TCAR(tmp)); if (EQ(tp[1], id)) { old_val = tp[2]; if (is_immed(value)) { tp[2] = value; /* DESTRUCTIVE HEAP ASSIGNMENT */ return old_val; } new_key = 0; /* Unlink old {Key,Value} from list */ *prev_cdr = TCDR(tmp); /* maybe DESTRUCTIVE HEAP ASSIGNMENT */ break; } } } if (HeapWordsLeft(p) < needed) { Eterm root[3]; root[0] = id; root[1] = value; root[2] = old_val; erts_garbage_collect(p, needed, root, 3); id = root[0]; value = root[1]; old_val = root[2]; ASSERT(bucket == ARRAY_GET_PTR(p->dictionary, hval)); old = *bucket; } #ifdef DEBUG hp_limit = p->htop + needed; #endif /* * Create the {Key,Value} tuple. */ hp = HeapOnlyAlloc(p, 3); tpl = TUPLE2(hp, id, value); /* * Update the dictionary. */ if (is_nil(old)) { *bucket = tpl; } else if (is_boxed(old)) { ASSERT(is_tuple(old)); if (!new_key) { ASSERT(EQ(tuple_val(old)[1],id)); *bucket = tpl; return old_val; } else { hp = HeapOnlyAlloc(p, 4); tmp = CONS(hp, old, NIL); hp += 2; *bucket = CONS(hp, tpl, tmp); hp += 2; ASSERT(hp <= hp_limit); } } else if (is_list(old)) { /* * Simply prepend the tuple to the beginning of the list. */ hp = HeapOnlyAlloc(p, 2); *bucket = CONS(hp, tpl, *bucket); hp += 2; ASSERT(hp <= hp_limit); } else { #ifdef DEBUG erts_fprintf(stderr, "Process dictionary for process %T is broken, trying to " "display term found in line %d:\n" "%T\n", p->common.id, __LINE__, old); #endif erts_exit(ERTS_ERROR_EXIT, "Damaged process dictionary found during put/2."); } p->dictionary->numElements += new_key; if (HASH_RANGE(p->dictionary) <= p->dictionary->numElements) { grow(p); } return old_val; } /* * Hash table utilities, rehashing */ static void shrink(Process *p, Eterm* ret) { ProcDict *pd = p->dictionary; unsigned int range = HASH_RANGE(p->dictionary); unsigned int steps = (range*3) / 10; Eterm hi, lo, tmp; unsigned int i; Eterm *hp; #ifdef DEBUG Eterm *hp_limit; #endif if (range - steps < INITIAL_SIZE) { steps = range - INITIAL_SIZE; } for (i = 0; i < steps; ++i) { if (pd->splitPosition == 0) { ASSERT(IS_POW2(pd->usedSlots)); pd->sizeMask = pd->usedSlots - 1; pd->splitPosition = pd->usedSlots / 2; } --(pd->splitPosition); /* Must wait to decrement 'usedSlots' for GC rootset below */ hi = ARRAY_GET(pd, pd->usedSlots - 1); lo = ARRAY_GET(pd, pd->splitPosition); if (hi != NIL) { if (lo == NIL) { ARRAY_PUT(pd, pd->splitPosition, hi); } else { Sint needed = 4; if (is_list(hi) && is_list(lo)) { needed = 2*erts_list_length(hi); } if (HeapWordsLeft(p) < needed) { erts_garbage_collect(p, needed, ret, 1); hi = pd->data[pd->usedSlots - 1]; lo = pd->data[pd->splitPosition]; } #ifdef DEBUG hp_limit = p->htop + needed; #endif if (is_tuple(lo)) { if (is_tuple(hi)) { hp = HeapOnlyAlloc(p, 4); tmp = CONS(hp, hi, NIL); hp += 2; ARRAY_PUT(pd, pd->splitPosition, CONS(hp,lo,tmp)); hp += 2; ASSERT(hp <= hp_limit); } else { /* hi is a list */ hp = HeapOnlyAlloc(p, 2); ARRAY_PUT(pd, pd->splitPosition, CONS(hp, lo, hi)); hp += 2; ASSERT(hp <= hp_limit); } } else { /* lo is a list */ if (is_tuple(hi)) { hp = HeapOnlyAlloc(p, 2); ARRAY_PUT(pd, pd->splitPosition, CONS(hp, hi, lo)); hp += 2; ASSERT(hp <= hp_limit); } else { /* Two lists */ hp = HeapOnlyAlloc(p, needed); for (tmp = hi; tmp != NIL; tmp = TCDR(tmp)) { lo = CONS(hp, TCAR(tmp), lo); hp += 2; } ASSERT(hp <= hp_limit); ARRAY_PUT(pd, pd->splitPosition, lo); } } } } --pd->usedSlots; ARRAY_PUT(pd, pd->usedSlots, NIL); } if (HASH_RANGE(p->dictionary) <= (p->dictionary->arraySize / 4)) { array_shrink(&(p->dictionary), (HASH_RANGE(p->dictionary) * 3) / 2); } } static void grow(Process *p) { unsigned int i,j; unsigned int steps = (p->dictionary->usedSlots / 4) & 0xf; Eterm l1,l2; Eterm l; Eterm *hp; unsigned int pos; unsigned int homeSize; Sint needed = 0; ProcDict *pd = p->dictionary; #ifdef DEBUG Eterm *hp_limit; #endif HDEBUGF(("grow: steps = %d", steps)); if (steps == 0) steps = 1; /* Dont grow over MAX_HASH */ if ((MAX_HASH - steps) <= HASH_RANGE(pd)) { return; } ensure_array_size(&p->dictionary, HASH_RANGE(pd) + steps); pd = p->dictionary; /* * Calculate total number of heap words needed, and garbage collect * if necessary. */ pos = pd->splitPosition; homeSize = pd->usedSlots - pd->splitPosition; for (i = 0; i < steps; ++i) { if (pos == homeSize) { homeSize *= 2; pos = 0; } l = ARRAY_GET(pd, pos); pos++; if (is_not_tuple(l)) { while (l != NIL) { needed += 2; l = TCDR(l); } } } if (HeapWordsLeft(p) < needed) { erts_garbage_collect(p, needed, 0, 0); } #ifdef DEBUG hp_limit = p->htop + needed; #endif /* * Now grow. */ homeSize = pd->usedSlots - pd->splitPosition; for (i = 0; i < steps; ++i) { if (pd->splitPosition == homeSize) { homeSize *= 2; pd->sizeMask = homeSize*2 - 1; pd->splitPosition = 0; } pos = pd->splitPosition; ++pd->splitPosition; /* For the hashes */ ++pd->usedSlots; ASSERT(pos + homeSize == pd->usedSlots - 1); l = ARRAY_GET(pd, pos); if (is_tuple(l)) { if (pd_hash_value(pd, tuple_val(l)[1]) != pos) { ARRAY_PUT(pd, pos + homeSize, l); ARRAY_PUT(pd, pos, NIL); } } else { l2 = NIL; l1 = l; for (j = 0; l1 != NIL; l1 = TCDR(l1)) j += 2; hp = HeapOnlyAlloc(p, j); while (l != NIL) { if (pd_hash_value(pd, tuple_val(TCAR(l))[1]) == pos) l1 = CONS(hp, TCAR(l), l1); else l2 = CONS(hp, TCAR(l), l2); hp += 2; l = TCDR(l); } if (l1 != NIL && TCDR(l1) == NIL) l1 = TCAR(l1); if (l2 != NIL && TCDR(l2) == NIL) l2 = TCAR(l2); ASSERT(hp <= hp_limit); ARRAY_PUT(pd, pos, l1); ARRAY_PUT(pd, pos + homeSize, l2); } } #ifdef HARDDEBUG dictionary_dump(p->dictionary,CERR); #endif } /* ** Array oriented operations */ static void array_shrink(ProcDict **ppd, unsigned int need) { unsigned int siz = next_array_size(need); HDEBUGF(("array_shrink: size = %d, need = %d", (*ppd)->arraySize, need)); if (siz >= (*ppd)->arraySize) return; /* Only shrink */ *ppd = PD_REALLOC(((void *) *ppd), PD_SZ2BYTES((*ppd)->arraySize), PD_SZ2BYTES(siz)); (*ppd)->arraySize = siz; } static void ensure_array_size(ProcDict **ppdict, unsigned int size) { ProcDict *pd = *ppdict; unsigned int i; if (pd == NULL) { Uint siz = next_array_size(size); pd = PD_ALLOC(PD_SZ2BYTES(siz)); for (i = 0; i < siz; ++i) pd->data[i] = NIL; pd->arraySize = siz; *ppdict = pd; } else if (size > pd->arraySize) { Uint osize = pd->arraySize; Uint nsize = next_array_size(size); pd = PD_REALLOC(((void *) pd), PD_SZ2BYTES(osize), PD_SZ2BYTES(nsize)); for (i = osize; i < nsize; ++i) pd->data[i] = NIL; pd->arraySize = nsize; *ppdict = pd; } } /* ** Basic utilities */ static unsigned int pd_hash_value_to_ix(ProcDict *pdict, erts_ihash_t hx) { Uint high; ASSERT(IS_POW2(pdict->sizeMask+1)); ASSERT(HASH_RANGE(pdict) >= (pdict->sizeMask >> 1)); ASSERT(HASH_RANGE(pdict) <= (pdict->sizeMask + 1)); high = hx & pdict->sizeMask; if (high >= HASH_RANGE(pdict)) return hx & (pdict->sizeMask >> 1); return high; } static unsigned int next_array_size(unsigned int need) { static unsigned int tab[] = { 10UL, 20UL, 40UL, 80UL, 160UL, 320UL, 640UL, 1280UL, 2560UL, 5120UL, 10240UL, 20480UL, 40960UL, 81920UL, 163840UL, 327680UL, 655360UL, 1310720UL, 2621440UL, 5242880UL, 10485760UL, 20971520UL, 41943040UL, 83886080UL, 167772160UL, 335544320UL, 671088640UL, 1342177280UL, 2684354560UL }; int hi = sizeof(tab) / sizeof(tab[0]) - 1; int lo = 1; int cur = 4; while (hi >= lo) { if (tab[cur] >= need && tab[cur - 1] < need) return tab[cur]; if (tab[cur] > need) hi = cur - 1; else lo = cur + 1; cur = (hi + lo) / 2; } return need; } /* ** Debug functions */ #ifdef DEBUG static void pd_check(ProcDict *pd) { unsigned int i; unsigned int used; Uint num; if (pd == NULL) return; used = HASH_RANGE(pd); ASSERT(pd->arraySize >= used); ASSERT(HASH_RANGE(pd) <= MAX_HASH); for (i = 0, num = 0; i < used; ++i) { Eterm t = pd->data[i]; if (is_nil(t)) { continue; } else if (is_tuple(t)) { ++num; ASSERT(arityval(*tuple_val(t)) == 2); ASSERT(pd_hash_value(pd, tuple_val(t)[1]) == i); continue; } else if (is_list(t)) { while (t != NIL) { ++num; ASSERT(is_tuple(TCAR(t))); ASSERT(arityval(*(tuple_val(TCAR(t)))) == 2); ASSERT(pd_hash_value(pd, tuple_val(TCAR(t))[1]) == i); t = TCDR(t); } continue; } else { erts_exit(ERTS_ERROR_EXIT, "Found tag 0x%08x in process dictionary at position %d", (unsigned long) t, (int) i); } } ASSERT(num == pd->numElements); ASSERT(pd->usedSlots >= pd->splitPosition*2); } #endif /* DEBUG */ #ifdef HARDDEBUG static int hdebugf(char *format, ...) { va_list ap; erts_fprintf(stderr, "DEBUG: %s:%d :", hdebugf_file, hdebugf_line); va_start(ap, format); erts_vfprintf(stderr, format, ap); va_end(ap); erts_fprintf(stderr, "\n"); return 0; } #endif /* HARDDEBUG */
55095647fa62021596a97dd1b7f51dee03b12287
58fe7cb3949dd1930e709696659a0296500b64a6
/tests/unit/s2n_cert_status_extension_test.c
e49fc814abea04d72781c3ef8f53cbcf016082c6
[ "Apache-2.0", "MIT" ]
permissive
aws/s2n-tls
3344638a6a69c6f20665cf6847e1bc4b85f2e558
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
refs/heads/main
2023-08-31T23:26:33.780048
2023-08-31T05:17:33
2023-08-31T05:17:33
21,287,076
513
213
Apache-2.0
2023-09-13T23:52:29
2014-06-27T19:37:59
C
UTF-8
C
false
false
20,195
c
s2n_cert_status_extension_test.c
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "s2n_test.h" #include "testlib/s2n_testlib.h" #include "tls/extensions/s2n_cert_status.h" const uint8_t ocsp_data[] = "OCSP DATA"; int s2n_test_enable_sending_extension(struct s2n_connection *conn, struct s2n_cert_chain_and_key *chain_and_key) { conn->status_type = S2N_STATUS_REQUEST_OCSP; conn->handshake_params.our_chain_and_key = chain_and_key; EXPECT_SUCCESS(s2n_cert_chain_and_key_set_ocsp_data(chain_and_key, ocsp_data, s2n_array_len(ocsp_data))); conn->x509_validator.state = VALIDATED; return S2N_SUCCESS; } int main(int argc, char **argv) { BEGIN_TEST(); DEFER_CLEANUP(struct s2n_cert_chain_and_key *chain_and_key = NULL, s2n_cert_chain_and_key_ptr_free); EXPECT_SUCCESS(s2n_test_cert_chain_and_key_new(&chain_and_key, S2N_DEFAULT_TEST_CERT_CHAIN, S2N_DEFAULT_TEST_PRIVATE_KEY)); /* should_send */ { struct s2n_config *config; EXPECT_NOT_NULL(config = s2n_config_new()); struct s2n_connection *conn; EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_CLIENT)); EXPECT_SUCCESS(s2n_connection_set_config(conn, config)); /* Don't send by default */ EXPECT_FALSE(s2n_cert_status_extension.should_send(conn)); /* Send if all prerequisites met */ EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); EXPECT_TRUE(s2n_cert_status_extension.should_send(conn)); /* Send if client */ EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); conn->mode = S2N_CLIENT; EXPECT_TRUE(s2n_cert_status_extension.should_send(conn)); /* Send if server */ EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); conn->mode = S2N_SERVER; EXPECT_TRUE(s2n_cert_status_extension.should_send(conn)); /* Don't send if no certificate set */ EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); conn->handshake_params.our_chain_and_key = NULL; EXPECT_FALSE(s2n_cert_status_extension.should_send(conn)); /* Don't send if no ocsp data */ EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); EXPECT_SUCCESS(s2n_free(&conn->handshake_params.our_chain_and_key->ocsp_status)); EXPECT_FALSE(s2n_cert_status_extension.should_send(conn)); EXPECT_SUCCESS(s2n_connection_free(conn)); EXPECT_SUCCESS(s2n_config_free(config)); }; /* Test send */ { struct s2n_connection *conn; EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER)); EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); struct s2n_stuffer stuffer = { 0 }; EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&stuffer, 0)); EXPECT_SUCCESS(s2n_cert_status_extension.send(conn, &stuffer)); uint8_t request_type; EXPECT_SUCCESS(s2n_stuffer_read_uint8(&stuffer, &request_type)); EXPECT_EQUAL(request_type, S2N_STATUS_REQUEST_OCSP); uint32_t ocsp_size; EXPECT_SUCCESS(s2n_stuffer_read_uint24(&stuffer, &ocsp_size)); EXPECT_EQUAL(ocsp_size, s2n_stuffer_data_available(&stuffer)); EXPECT_EQUAL(ocsp_size, s2n_array_len(ocsp_data)); uint8_t *actual_ocsp_data; EXPECT_NOT_NULL(actual_ocsp_data = s2n_stuffer_raw_read(&stuffer, ocsp_size)); EXPECT_BYTEARRAY_EQUAL(actual_ocsp_data, ocsp_data, ocsp_size); EXPECT_EQUAL(s2n_stuffer_data_available(&stuffer), 0); EXPECT_SUCCESS(s2n_stuffer_free(&stuffer)); EXPECT_SUCCESS(s2n_connection_free(conn)); }; /* Test recv */ { struct s2n_connection *conn; EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER)); EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); struct s2n_stuffer stuffer = { 0 }; EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&stuffer, 0)); EXPECT_SUCCESS(s2n_cert_status_extension.send(conn, &stuffer)); EXPECT_EQUAL(conn->status_response.size, 0); EXPECT_SUCCESS(s2n_cert_status_extension.recv(conn, &stuffer)); EXPECT_BYTEARRAY_EQUAL(conn->status_response.data, ocsp_data, s2n_array_len(ocsp_data)); EXPECT_EQUAL(s2n_stuffer_data_available(&stuffer), 0); EXPECT_SUCCESS(s2n_stuffer_free(&stuffer)); EXPECT_SUCCESS(s2n_connection_free(conn)); }; /* Test recv - not ocsp */ { struct s2n_connection *conn; EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER)); EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); struct s2n_stuffer stuffer = { 0 }; EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&stuffer, 0)); EXPECT_SUCCESS(s2n_stuffer_write_uint8(&stuffer, S2N_STATUS_REQUEST_NONE)); EXPECT_EQUAL(conn->status_response.size, 0); EXPECT_SUCCESS(s2n_cert_status_extension.recv(conn, &stuffer)); EXPECT_EQUAL(conn->status_response.size, 0); EXPECT_SUCCESS(s2n_stuffer_free(&stuffer)); EXPECT_SUCCESS(s2n_connection_free(conn)); }; /* Test recv - bad ocsp data */ { struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT); EXPECT_NOT_NULL(conn); EXPECT_SUCCESS(s2n_test_enable_sending_extension(conn, chain_and_key)); DEFER_CLEANUP(struct s2n_stuffer stuffer = { 0 }, s2n_stuffer_free); EXPECT_SUCCESS(s2n_stuffer_growable_alloc(&stuffer, 0)); EXPECT_SUCCESS(s2n_cert_status_extension.send(conn, &stuffer)); if (s2n_x509_ocsp_stapling_supported()) { EXPECT_FAILURE_WITH_ERRNO(s2n_cert_status_extension.recv(conn, &stuffer), S2N_ERR_INVALID_OCSP_RESPONSE); } else { /* s2n_x509_validator_validate_cert_stapled_ocsp_response returns untrusted error if ocsp is not supported */ EXPECT_FAILURE_WITH_ERRNO(s2n_cert_status_extension.recv(conn, &stuffer), S2N_ERR_CERT_UNTRUSTED); } EXPECT_SUCCESS(s2n_connection_free(conn)); }; /* Self-talk tests */ if (s2n_x509_ocsp_stapling_supported() && s2n_is_tls13_fully_supported()) { uint8_t ocsp_response[S2N_MAX_TEST_PEM_SIZE] = { 0 }; uint32_t ocsp_response_len = 0; EXPECT_SUCCESS(s2n_read_test_pem_and_len(S2N_OCSP_RESPONSE_DER, ocsp_response, &ocsp_response_len, S2N_MAX_TEST_PEM_SIZE)); EXPECT_TRUE(ocsp_response_len > 0); DEFER_CLEANUP(struct s2n_cert_chain_and_key *ocsp_chain_and_key = NULL, s2n_cert_chain_and_key_ptr_free); EXPECT_SUCCESS(s2n_test_cert_chain_and_key_new(&ocsp_chain_and_key, S2N_OCSP_SERVER_CERT, S2N_OCSP_SERVER_KEY)); EXPECT_SUCCESS(s2n_cert_chain_and_key_set_ocsp_data(ocsp_chain_and_key, ocsp_response, ocsp_response_len)); /* Client requests OCSP staple, and server sends OCSP response */ { DEFER_CLEANUP(struct s2n_config *client_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(client_config); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(client_config, S2N_OCSP_CA_CERT, NULL)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(client_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(client_config, S2N_STATUS_REQUEST_OCSP)); DEFER_CLEANUP(struct s2n_config *server_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(server_config); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(server_config, ocsp_chain_and_key)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(server_config, "default_tls13")); DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free); EXPECT_NOT_NULL(server_conn); EXPECT_SUCCESS(s2n_connection_set_config(server_conn, server_config)); DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free); EXPECT_NOT_NULL(client_conn); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); EXPECT_SUCCESS(s2n_set_server_name(client_conn, "s2n Test Cert")); DEFER_CLEANUP(struct s2n_test_io_pair io_pair = { 0 }, s2n_io_pair_close); EXPECT_SUCCESS(s2n_io_pair_init_non_blocking(&io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(client_conn, &io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(server_conn->actual_protocol_version, S2N_TLS13); EXPECT_EQUAL(client_conn->actual_protocol_version, S2N_TLS13); uint32_t client_received_ocsp_response_len = 0; const uint8_t *client_received_ocsp_response = s2n_connection_get_ocsp_response(client_conn, &client_received_ocsp_response_len); EXPECT_NOT_NULL(client_received_ocsp_response); uint32_t server_received_ocsp_response_len = 0; const uint8_t *server_received_ocsp_response = s2n_connection_get_ocsp_response(server_conn, &server_received_ocsp_response_len); /* Only the client requested a response, the server should not have received one. */ EXPECT_NULL(server_received_ocsp_response); /* The server sent an OCSP response, and the client received an OCSP response */ EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(server_conn), 1); EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(client_conn), 1); } /* Server requests OCSP staple, and client sends OCSP response */ { DEFER_CLEANUP(struct s2n_config *client_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(client_config); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(client_config, S2N_OCSP_CA_CERT, NULL)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(client_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(client_config, S2N_STATUS_REQUEST_NONE)); EXPECT_SUCCESS(s2n_config_set_client_auth_type(client_config, S2N_CERT_AUTH_OPTIONAL)); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(client_config, ocsp_chain_and_key)); DEFER_CLEANUP(struct s2n_config *server_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(server_config); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(server_config, ocsp_chain_and_key)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(server_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(server_config, S2N_STATUS_REQUEST_OCSP)); EXPECT_SUCCESS(s2n_config_set_client_auth_type(server_config, S2N_CERT_AUTH_REQUIRED)); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(server_config, S2N_OCSP_CA_CERT, NULL)); DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free); EXPECT_NOT_NULL(server_conn); EXPECT_SUCCESS(s2n_connection_set_config(server_conn, server_config)); DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free); EXPECT_NOT_NULL(client_conn); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); EXPECT_SUCCESS(s2n_set_server_name(client_conn, "s2n Test Cert")); DEFER_CLEANUP(struct s2n_test_io_pair io_pair = { 0 }, s2n_io_pair_close); EXPECT_SUCCESS(s2n_io_pair_init_non_blocking(&io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(client_conn, &io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(server_conn->actual_protocol_version, S2N_TLS13); EXPECT_EQUAL(client_conn->actual_protocol_version, S2N_TLS13); uint32_t client_received_ocsp_response_len = 0; const uint8_t *client_received_ocsp_response = s2n_connection_get_ocsp_response(client_conn, &client_received_ocsp_response_len); /* Only the server requested a response, the client should not have received one. */ EXPECT_NULL(client_received_ocsp_response); uint32_t server_received_ocsp_response_len = 0; const uint8_t *server_received_ocsp_response = s2n_connection_get_ocsp_response(server_conn, &server_received_ocsp_response_len); EXPECT_NOT_NULL(server_received_ocsp_response); /* The server did not send an OCSP response, and the client did not receive an OCSP response */ EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(server_conn), 0); EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(client_conn), 0); } /* Client and server both request OCSP staples, and client and server both send responses */ { DEFER_CLEANUP(struct s2n_config *client_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(client_config); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(client_config, S2N_OCSP_CA_CERT, NULL)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(client_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(client_config, S2N_STATUS_REQUEST_OCSP)); EXPECT_SUCCESS(s2n_config_set_client_auth_type(client_config, S2N_CERT_AUTH_OPTIONAL)); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(client_config, ocsp_chain_and_key)); DEFER_CLEANUP(struct s2n_config *server_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(server_config); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(server_config, ocsp_chain_and_key)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(server_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(server_config, S2N_STATUS_REQUEST_OCSP)); EXPECT_SUCCESS(s2n_config_set_client_auth_type(server_config, S2N_CERT_AUTH_REQUIRED)); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(server_config, S2N_OCSP_CA_CERT, NULL)); DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free); EXPECT_NOT_NULL(server_conn); EXPECT_SUCCESS(s2n_connection_set_config(server_conn, server_config)); DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free); EXPECT_NOT_NULL(client_conn); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); EXPECT_SUCCESS(s2n_set_server_name(client_conn, "s2n Test Cert")); DEFER_CLEANUP(struct s2n_test_io_pair io_pair = { 0 }, s2n_io_pair_close); EXPECT_SUCCESS(s2n_io_pair_init_non_blocking(&io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(client_conn, &io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(server_conn->actual_protocol_version, S2N_TLS13); EXPECT_EQUAL(client_conn->actual_protocol_version, S2N_TLS13); uint32_t client_received_ocsp_response_len = 0; const uint8_t *client_received_ocsp_response = s2n_connection_get_ocsp_response(client_conn, &client_received_ocsp_response_len); EXPECT_NOT_NULL(client_received_ocsp_response); uint32_t server_received_ocsp_response_len = 0; const uint8_t *server_received_ocsp_response = s2n_connection_get_ocsp_response(server_conn, &server_received_ocsp_response_len); EXPECT_NOT_NULL(server_received_ocsp_response); /* The server sent an OCSP response, and the client received an OCSP response */ EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(server_conn), 1); EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(client_conn), 1); } /* Server sets an OCSP response but client does not request OCSP stapling */ { DEFER_CLEANUP(struct s2n_config *client_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(client_config); EXPECT_SUCCESS(s2n_config_set_verification_ca_location(client_config, S2N_OCSP_CA_CERT, NULL)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(client_config, "default_tls13")); EXPECT_SUCCESS(s2n_config_set_status_request_type(client_config, S2N_STATUS_REQUEST_NONE)); DEFER_CLEANUP(struct s2n_config *server_config = s2n_config_new(), s2n_config_ptr_free); EXPECT_NOT_NULL(server_config); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(server_config, ocsp_chain_and_key)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(server_config, "default_tls13")); DEFER_CLEANUP(struct s2n_connection *server_conn = s2n_connection_new(S2N_SERVER), s2n_connection_ptr_free); EXPECT_NOT_NULL(server_conn); EXPECT_SUCCESS(s2n_connection_set_config(server_conn, server_config)); DEFER_CLEANUP(struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT), s2n_connection_ptr_free); EXPECT_NOT_NULL(client_conn); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); EXPECT_SUCCESS(s2n_set_server_name(client_conn, "s2n Test Cert")); DEFER_CLEANUP(struct s2n_test_io_pair io_pair = { 0 }, s2n_io_pair_close); EXPECT_SUCCESS(s2n_io_pair_init_non_blocking(&io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(client_conn, &io_pair)); EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(server_conn->actual_protocol_version, S2N_TLS13); EXPECT_EQUAL(client_conn->actual_protocol_version, S2N_TLS13); uint32_t client_received_ocsp_response_len = 0; const uint8_t *client_received_ocsp_response = s2n_connection_get_ocsp_response(client_conn, &client_received_ocsp_response_len); uint32_t server_received_ocsp_response_len = 0; const uint8_t *server_received_ocsp_response = s2n_connection_get_ocsp_response(server_conn, &server_received_ocsp_response_len); /* Both the server and client did not request OCSP responses, so neither should have received them. */ EXPECT_NULL(client_received_ocsp_response); EXPECT_NULL(server_received_ocsp_response); /* The server did not send an OCSP response, and the client did not receive an OCSP response */ EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(server_conn), 0); EXPECT_EQUAL(s2n_connection_is_ocsp_stapled(client_conn), 0); } } END_TEST(); return 0; }
187db534cef90ae14629b4451fa944113d08ef2e
317410b28757af216145d23259d63fc96d07f613
/cpu/br30/charge.c
0d72d9d98ad825c7503e90b8a75ebfbc05d5fc59
[ "Apache-2.0" ]
permissive
Jieli-Tech/fw-AC63_BT_SDK
48c757dca7e8000ec763bf5466583a4cd8c4a11c
393d63758081d56f0bf0a39ac596bee32c33d493
refs/heads/master
2023-07-18T02:14:56.187266
2023-06-21T03:14:20
2023-06-21T03:14:20
272,586,610
113
76
Apache-2.0
2022-10-20T23:07:31
2020-06-16T02:02:15
C
UTF-8
C
false
false
16,221
c
charge.c
#include "asm/clock.h" #include "timer.h" #include "asm/power/p33.h" #include "asm/charge.h" #include "asm/adc_api.h" #include "uart.h" #include "device/device.h" #include "asm/power_interface.h" /*#include "power/power_hw.h"*/ #include "system/event.h" #include "asm/efuse.h" #include "gpio.h" #include "app_config.h" #define LOG_TAG_CONST CHARGE #define LOG_TAG "[CHARGE]" #define LOG_INFO_ENABLE #define LOG_DUMP_ENABLE #define LOG_ERROR_ENABLE #define LOG_DEBUG_ENABLE #include "debug.h" #define IO_PORT_LDOIN LINDT_IN//IO编号 typedef struct _CHARGE_VAR { struct charge_platform_data *data; volatile u8 charge_online_flag; volatile u8 charge_event_flag; volatile u8 init_ok; volatile u8 detect_stop; volatile int ldo5v_timer; volatile int charge_timer; volatile int power_sw_timer; volatile int cc_timer; //涓流切恒流的sys timer } CHARGE_VAR; #define __this (&charge_var) static CHARGE_VAR charge_var; extern void charge_set_callback(void (*wakup_callback)(void), void (*sub_callback)(void)); static u8 charge_flag; #define BIT_LDO5V_IN BIT(0) #define BIT_LDO5V_OFF BIT(1) #define BIT_LDO5V_ERR BIT(2) void charge_wakeup_isr(void); u8 get_charge_poweron_en(void) { return __this->data->charge_poweron_en; } void charge_check_and_set_pinr(u8 level) { u8 pinr_io; if (P33_CON_GET(P3_PINR_CON) & BIT(0)) { pinr_io = P33_CON_GET(P3_PORT_SEL0); if (pinr_io == IO_PORT_LDOIN) { if (level == 0) { P33_CON_SET(P3_PINR_CON, 2, 1, 0); } else { P33_CON_SET(P3_PINR_CON, 2, 1, 1); } } } } static void udelay(u32 usec) { JL_TIMER0->CON = BIT(14); JL_TIMER0->CNT = 0; JL_TIMER0->PRD = clk_get("timer") / 1000000L * usec; //1us JL_TIMER0->CON = BIT(0) | BIT(2) | BIT(6); //sys clk while ((JL_TIMER0->CON & BIT(15)) == 0); JL_TIMER0->CON = BIT(14); } static u8 check_charge_state(void) { u8 online_cnt = 0; u8 i = 0; __this->charge_online_flag = 0; for (i = 0; i < 20; i++) { if (LVCMP_DET_GET() || LDO5V_DET_GET()) { online_cnt++; } udelay(1000); } log_info("online_cnt = %d\n", online_cnt); if (online_cnt > 5) { __this->charge_online_flag = 1; } return __this->charge_online_flag; } void set_charge_online_flag(u8 flag) { __this->charge_online_flag = flag; } u8 get_charge_online_flag(void) { return __this->charge_online_flag; } void set_charge_event_flag(u8 flag) { __this->charge_event_flag = flag; } u8 get_ldo5v_online_hw(void) { return LDO5V_DET_GET(); } u8 get_lvcmp_det(void) { return LVCMP_DET_GET(); } u8 get_ldo5v_pulldown_en(void) { if (!__this->data) { return 0; } if (get_ldo5v_online_hw()) { if (__this->data->ldo5v_pulldown_keep == 0) { return 0; } } return __this->data->ldo5v_pulldown_en; } u8 get_ldo5v_pulldown_res(void) { if (__this->data) { return __this->data->ldo5v_pulldown_lvl; } return CHARGE_PULLDOWN_200K; } void charge_event_to_user(u8 event) { struct sys_event e; e.type = SYS_DEVICE_EVENT; e.arg = (void *)DEVICE_EVENT_FROM_CHARGE; e.u.dev.event = event; e.u.dev.value = 0; sys_event_notify(&e); } void charge_power_switch_timer(void *priv) { u32 vbat_voltage; vbat_voltage = adc_get_voltage(AD_CH_VBAT) * 4 / 10; if (vbat_voltage > 300) { power_set_charge_mode(0); power_set_mode(PWR_DCDC15); power_set_charge_mode(1); usr_timer_del(__this->power_sw_timer); __this->power_sw_timer = 0; adc_set_sample_freq(AD_CH_VBAT, 5000); } } void power_enter_charge_mode(void) { if (TCFG_LOWPOWER_POWER_SEL == PWR_DCDC15) { u8 chip_id = get_chip_version() & 0x0f; u32 vbat_voltage; if ((chip_id >= 0x0C) || (chip_id == 0x01) || (chip_id == 0x02)) { vbat_voltage = adc_get_voltage(AD_CH_VBAT) * 4 / 10; if (vbat_voltage > 300) { power_set_charge_mode(0); power_set_mode(PWR_DCDC15); power_set_charge_mode(1); } else { power_set_charge_mode(0); power_set_mode(PWR_LDO15); power_set_charge_mode(1); if (__this->power_sw_timer == 0) { //低压充电不进低功耗 adc_set_sample_freq(AD_CH_VBAT, 20); __this->power_sw_timer = usr_timer_add(NULL, charge_power_switch_timer, 1000, 1); } } } else if ((chip_id == 0x03) || (chip_id == 0x04) || (chip_id == 0x06)) { power_set_charge_mode(1); power_set_mode(PWR_DCDC15_FOR_CHARGE); } } } void power_exit_charge_mode(void) { if (TCFG_LOWPOWER_POWER_SEL == PWR_DCDC15) { power_set_charge_mode(0); power_set_mode(TCFG_LOWPOWER_POWER_SEL); if (__this->power_sw_timer) { usr_timer_del(__this->power_sw_timer); __this->power_sw_timer = 0; } } } /*检测是否满足进入恒流充电条件*/ static void charge_cc_check(void *priv) { log_info("%s\n", __func__); if ((adc_get_voltage(AD_CH_VBAT) * 4 / 10) > CHARGE_CCVOL_V) { /*满足进入恒流充电条件 设置恒流充电电流大小*/ set_charge_mA(__this->data->charge_mA); usr_timer_del(__this->cc_timer); __this->cc_timer = 0; /*触发一次满电唤醒服务函数 将满电使能打开*/ charge_wakeup_isr(); } } void charge_start(void) { u8 check_full = 0; log_info("%s\n", __func__); /*充电开始先将满电检测的定时器关闭*/ if (__this->charge_timer) { usr_timer_del(__this->charge_timer); __this->charge_timer = 0; } /*充电开始先将满电唤醒关闭,待过涓流阶段再打开*/ power_wakeup_disable_with_port(IO_CHGFL_DET); /*进入恒流充电之后(VBAT > 3V),才开启充满检测*/ if ((adc_get_voltage(AD_CH_VBAT) * 4 / 10) > CHARGE_CCVOL_V) { /*设置恒流充电电流大小*/ set_charge_mA(__this->data->charge_mA); /*恒流充电开启满电唤醒使能*/ power_wakeup_enable_with_port(IO_CHGFL_DET); check_full = 1; } else { /*设置涓流电流大小*/ set_charge_mA(__this->data->charge_trickle_mA); if (!__this->cc_timer) { /*每1分钟检测一次是否具备进入恒流充电的条件*/ __this->cc_timer = usr_timer_add(NULL, charge_cc_check, 1000, 1); } } power_enter_charge_mode(); CHGBG_EN(1); CHARGE_EN(1); charge_event_to_user(CHARGE_EVENT_CHARGE_START); /*开启充电时,充满标记为1时,主动检测一次是否充满*/ if (check_full && CHARGE_FULL_FLAG_GET()) { charge_wakeup_isr(); } } void charge_close(void) { log_info("%s\n", __func__); if (charge_flag != BIT_LDO5V_IN) { CHGBG_EN(0); CHARGE_EN(0); } power_exit_charge_mode(); power_wakeup_disable_with_port(IO_CHGFL_DET); charge_event_to_user(CHARGE_EVENT_CHARGE_CLOSE); if (__this->charge_timer) { usr_timer_del(__this->charge_timer); __this->charge_timer = 0; } if (__this->cc_timer) { usr_timer_del(__this->cc_timer); __this->cc_timer = 0; } } static void charge_full_detect(void *priv) { static u16 charge_full_cnt = 0; u16 vbat_vol, vpwr_vol; u8 chip_id = get_chip_version() & 0x0f; if (CHARGE_FULL_FLAG_GET() && LVCMP_DET_GET()) { /* putchar('F'); */ //AB版可能出现误判满 if ((chip_id >= 0x0C) || (chip_id == 0x01)) { vbat_vol = adc_get_voltage(AD_CH_VBAT) * 4 / 10; vpwr_vol = adc_get_voltage(AD_CH_LDO5V) * 4 / 10; if ((vpwr_vol < 450) || (vbat_vol < 410)) { /* putchar('P'); */ charge_full_cnt = 0; return; } } if (charge_full_cnt < 5) { charge_full_cnt++; } else { charge_full_cnt = 0; usr_timer_del(__this->charge_timer); __this->charge_timer = 0; charge_event_to_user(CHARGE_EVENT_CHARGE_FULL); } } else { /* putchar('K'); */ charge_full_cnt = 0; usr_timer_del(__this->charge_timer); __this->charge_timer = 0; /*电池未满电,开启满电唤醒使能*/ power_wakeup_enable_with_port(IO_CHGFL_DET); } } static void ldo5v_detect(void *priv) { /* log_info("%s\n",__func__); */ static u16 ldo5v_in_normal_cnt = 0; static u16 ldo5v_in_err_cnt = 0; static u16 ldo5v_off_cnt = 0; if (__this->detect_stop) { return; } if (LVCMP_DET_GET()) { //ldoin > vbat /* putchar('X'); */ if (ldo5v_in_normal_cnt < __this->data->ldo5v_on_filter) { ldo5v_in_normal_cnt++; } else { /* printf("ldo5V_IN\n"); */ set_charge_online_flag(1); ldo5v_off_cnt = 0; ldo5v_in_err_cnt = 0; //消息线程未准备好接收消息,继续扫描 if (__this->charge_event_flag == 0) { return; } ldo5v_in_normal_cnt = 0; usr_timer_del(__this->ldo5v_timer); __this->ldo5v_timer = 0; if ((charge_flag & BIT_LDO5V_IN) == 0) { charge_flag = BIT_LDO5V_IN; charge_event_to_user(CHARGE_EVENT_LDO5V_IN); power_wakeup_set_edge(IO_VBTCH_DET, FALLING_EDGE);//检测ldoin比vbat电压低的情况(充电仓给电池充满后会关断,此时电压会掉下来) } } } else if (LDO5V_DET_GET() == 0) { //ldoin<拔出电压(0.6) /* putchar('Q'); */ if (ldo5v_off_cnt < (__this->data->ldo5v_off_filter + 20)) { ldo5v_off_cnt++; } else { /* printf("ldo5V_OFF\n"); */ set_charge_online_flag(0); ldo5v_in_normal_cnt = 0; ldo5v_in_err_cnt = 0; //消息线程未准备好接收消息,继续扫描 if (__this->charge_event_flag == 0) { return; } ldo5v_off_cnt = 0; usr_timer_del(__this->ldo5v_timer); __this->ldo5v_timer = 0; if ((charge_flag & BIT_LDO5V_OFF) == 0) { charge_flag = BIT_LDO5V_OFF; power_wakeup_set_edge(IO_VBTCH_DET, RISING_EDGE);//拔出后重新检测插入 charge_event_to_user(CHARGE_EVENT_LDO5V_OFF); } } } else { //拔出电压(0.6左右)< ldoin < vbat /* putchar('E'); */ if (ldo5v_in_err_cnt < __this->data->ldo5v_keep_filter) { ldo5v_in_err_cnt++; } else { /* printf("ldo5V_ERR\n"); */ set_charge_online_flag(1); ldo5v_off_cnt = 0; ldo5v_in_normal_cnt = 0; //消息线程未准备好接收消息,继续扫描 if (__this->charge_event_flag == 0) { return; } ldo5v_in_err_cnt = 0; usr_timer_del(__this->ldo5v_timer); __this->ldo5v_timer = 0; if ((charge_flag & BIT_LDO5V_ERR) == 0) { charge_flag = BIT_LDO5V_ERR; power_wakeup_set_edge(IO_VBTCH_DET, RISING_EDGE); if (__this->data->ldo5v_off_filter) { charge_event_to_user(CHARGE_EVENT_LDO5V_KEEP); } } } } } void sub_wakeup_isr(void) { /* printf(" %s \n", __func__); */ if (__this->ldo5v_timer == 0) { __this->ldo5v_timer = usr_timer_add(0, ldo5v_detect, 2, 1); } } /*满电唤醒服务函数*/ void charge_wakeup_isr(void) { /* printf(" %s \n", __func__); */ power_wakeup_disable_with_port(IO_CHGFL_DET); if (__this->charge_timer == 0) { __this->charge_timer = usr_timer_add(0, charge_full_detect, 2, 1); } } #if 0 static void test_func(void *priv) { /* if (P33_CON_GET(P3_CHG_READ) & BIT(0)) { */ /* JL_PORTA->DIR &= ~BIT(3); */ /* JL_PORTA->OUT |= BIT(3); */ /* } else { */ /* JL_PORTA->OUT &= ~BIT(3); */ /* } */ } #endif void charge_set_ldo5v_detect_stop(u8 stop) { __this->detect_stop = stop; } u8 get_charge_mA_config(void) { return __this->data->charge_mA; } void set_charge_mA(u8 charge_mA) { static u8 charge_mA_old = 0xff; if (charge_mA_old != charge_mA) { charge_mA_old = charge_mA; CHARGE_mA_SEL(charge_mA); } } const u16 full_table[CHARGE_FULL_V_MAX] = { 3962, 4002, 4044, 4086, 4130, 4175, 4222, 4270, 4308, 4349, 4391, 4434, 4472, 4517, 4564, 4611 }; u16 get_charge_full_value(void) { ASSERT(__this->init_ok, "charge not init ok!\n"); ASSERT(__this->data->charge_full_V < CHARGE_FULL_V_MAX); return full_table[__this->data->charge_full_V]; } static void charge_config(void) { u8 charge_4202_trim_val = CHARGE_FULL_V_4222; u8 offset = 0; u8 charge_full_v_val = 0; if (get_vbat_trim() == 0xf) { log_info("vbat not trim, use default config!!!!!!"); } else { charge_4202_trim_val = get_vbat_trim(); //4.2V对应的trim出来的实际档位 } log_info("charge_4202_trim_val = %d\n", charge_4202_trim_val); if (__this->data->charge_full_V >= CHARGE_FULL_V_4222) { offset = __this->data->charge_full_V - CHARGE_FULL_V_4222; charge_full_v_val = charge_4202_trim_val + offset; if (charge_full_v_val > 0xf) { charge_full_v_val = 0xf; } } else { offset = CHARGE_FULL_V_4222 - __this->data->charge_full_V; if (charge_4202_trim_val >= offset) { charge_full_v_val = charge_4202_trim_val - offset; } else { charge_full_v_val = 0; } } log_info("charge_full_v_val = %d\n", charge_full_v_val); CHARGE_FULL_V_SEL(charge_full_v_val); CHARGE_FULL_mA_SEL(__this->data->charge_full_mA); /* CHARGE_mA_SEL(__this->data->charge_mA); */ /* CHARGE_mA_SEL(CHARGE_mA_20); */ CHARGE_mA_SEL(__this->data->charge_trickle_mA); } static int charge_init(const struct dev_node *node, void *arg) { log_info("%s\n", __func__); __this->data = (struct charge_platform_data *)arg; ASSERT(__this->data); __this->init_ok = 0; __this->charge_online_flag = 0; /*先关闭充电使能,后面检测到充电插入再开启*/ power_wakeup_disable_with_port(IO_CHGFL_DET); CHGBG_EN(0); CHARGE_EN(0); /*LDO5V的100K下拉电阻使能*/ L5V_RES_DET_S_SEL(__this->data->ldo5v_pulldown_lvl); L5V_LOAD_EN(__this->data->ldo5v_pulldown_en); charge_config(); if (check_charge_state()) { if (__this->ldo5v_timer == 0) { __this->ldo5v_timer = usr_timer_add(0, ldo5v_detect, 2, 1); } } else { charge_flag = BIT_LDO5V_OFF; } charge_set_callback(charge_wakeup_isr, sub_wakeup_isr); /* usr_timer_add(0, test_func, 10); */ //AB版可能出现误判满 u8 chip_id = get_chip_version() & 0x0f; if ((chip_id >= 0x0C) || (chip_id == 0x01)) { adc_add_sample_ch(AD_CH_LDO5V); } __this->init_ok = 1; return 0; } void charge_module_stop(void) { if (!__this->init_ok) { return; } charge_set_callback(NULL, NULL); charge_close(); power_wakeup_disable_with_port(IO_LDOIN_DET); power_wakeup_disable_with_port(IO_VBTCH_DET); if (__this->ldo5v_timer) { usr_timer_del(__this->ldo5v_timer); __this->ldo5v_timer = 0; } } void charge_module_restart(void) { if (!__this->init_ok) { return; } if (!__this->ldo5v_timer) { __this->ldo5v_timer = usr_timer_add(NULL, ldo5v_detect, 2, 1); } charge_set_callback(charge_wakeup_isr, sub_wakeup_isr); power_wakeup_enable_with_port(IO_LDOIN_DET); power_wakeup_enable_with_port(IO_VBTCH_DET); } const struct device_operations charge_dev_ops = { .init = charge_init, };
6825ed7f8f2b561d1eadeb62f7ff894b13268d40
d2253070a3a64b14dee5ca0b3d311919178e590c
/include/constants/field_weather.h
e84dbc48c4ddb78a99fd07f4db81d446fff4c2f2
[]
no_license
pret/pokeemerald
ce232eccdde78502f3c251d672b26af3e1d7e508
d67914e114c937c4c80ce128ddc5523d4dc2cd40
refs/heads/master
2023-08-31T11:23:13.877932
2023-08-27T23:40:59
2023-08-27T23:40:59
43,677,244
1,944
1,903
null
2023-09-12T22:48:06
2015-10-05T10:09:22
C
UTF-8
C
false
false
792
h
field_weather.h
#ifndef GUARD_CONSTANTS_FIELD_WEATHER_H #define GUARD_CONSTANTS_FIELD_WEATHER_H #define MAX_RAIN_SPRITES 24 #define NUM_CLOUD_SPRITES 3 #define NUM_FOG_HORIZONTAL_SPRITES 20 #define NUM_ASH_SPRITES 20 #define NUM_FOG_DIAGONAL_SPRITES 20 #define NUM_SANDSTORM_SPRITES 20 #define NUM_SWIRL_SANDSTORM_SPRITES 5 // Controls how the weather should be changing the screen palettes. #define WEATHER_PAL_STATE_CHANGING_WEATHER 0 #define WEATHER_PAL_STATE_SCREEN_FADING_IN 1 #define WEATHER_PAL_STATE_SCREEN_FADING_OUT 2 #define WEATHER_PAL_STATE_IDLE 3 // Modes for FadeScreen #define FADE_FROM_BLACK 0 #define FADE_TO_BLACK 1 #define FADE_FROM_WHITE 2 #define FADE_TO_WHITE 3 #endif // GUARD_CONSTANTS_FIELD_WEATHER_H
e68245ed1bf5a977f7ee17ae485fdaa925259833
8838eb997879add5759b6dfb23f9a646464e53ca
/third-party/bsp/multiclet/include/adc.h
13529cd12fe35ae26556b1a744499419fe6bd01d
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
540
h
adc.h
//ADCx constant file #ifndef ADC_h #define ADC_h #include "R1_ccf.h" typedef struct { __IO uint32_t CR; __IO uint32_t CH0; __IO uint32_t CH1; __IO uint32_t CH2; __IO uint32_t CH3; } ADC_TypeDef; #define APB1PERIPH_BASE (0xC0100000) //GPIOA #define ADC0_BASE (APB1PERIPH_BASE + 0x000D0000) #define ADC0 ((ADC_TypeDef *) ADC0_BASE) //GPIOB #define ADC1_BASE (APB1PERIPH_BASE + 0x000D0100) #define ADC1 ((ADC_TypeDef *) ADC1_BASE) //adc constant and macro #endif
1a5b31d207cfe56dc3ca1c6b251c2001774bbd26
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/components/stage/blsync_ble/src/encrypt_layer.c
b2f7e03a1c094509df2e0eb9f740db903afa1fc0
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
2,188
c
encrypt_layer.c
/** @file * @brief protocol */ #include "encrypt_layer.h" static int __pack_encrypt_read (void *p_drv, uint8_t pack_type, uint8_t *dst_id, uint8_t *dst_buf, uint8_t *dst_len, uint8_t *src_buf, size_t src_lenght) { struct encrypt *p_enc; uint8_t enc_ctrl; uint32_t ctr, mac; p_enc = (struct encrypt *)p_drv; enc_ctrl = src_buf[0]; if (p_enc->is_head) { ctr = get_cpu_le32(&src_buf[1]); mac = get_cpu_le32(&src_buf[5]); src_buf += 9; src_lenght -= 9; } else { src_buf += 1; src_lenght -= 1; } if (pack_type == PROTOCOL_TYPE_CMD) { p_enc->pyld.pyld_type = PYLD_TYPE_CMD; } else { p_enc->pyld.pyld_type = PYLD_TYPE_DATA; } return payload_read(p_enc->pyld_handle, dst_buf, dst_id, dst_len, src_buf, src_lenght); } static int __pack_encrypt_write (void *p_drv, uint8_t pack_type, uint8_t src_id, uint8_t *dst_buf, uint8_t *dst_len, uint8_t *src_buf, uint8_t src_len, int16_t remain_len) { struct encrypt *p_enc; uint8_t enc_ctrl = 0; uint32_t ctr = 0, mac = 0; p_enc = (struct encrypt *)p_drv; dst_buf[0] = enc_ctrl; if (p_enc->is_head) { put_cpu_le32(&dst_buf[1], ctr); put_cpu_le32(&dst_buf[5], mac); dst_buf += 9; *dst_len += 9; remain_len -= 9; } else { dst_buf += 1; *dst_len += 1; remain_len -= 1; } p_enc->pyld.pyld_type = PYLD_TYPE_DATA; return payload_write(p_enc->pyld_handle, dst_buf, dst_len, src_id, src_buf, src_len, remain_len); } const static struct pro_enc_func __g_enc_func = { __pack_encrypt_read, __pack_encrypt_write }; enc_handle_t pro_encrypt_init (struct encrypt *p_enc, void *p_drv) { p_enc->pyld_handle = pro_payload_init(&p_enc->pyld, (void *)&p_enc->pyld); p_enc->pfnc = &__g_enc_func; p_enc->p_drv = p_drv; return p_enc; }
0285383a076a4fb38e528252bcec4ad179297f6a
51de1ebe7fa09fb262e015fb454829987ed5fc83
/provisioning_service_client/inc/prov_service_client/provisioning_sc_device_registration_state.h
e82d766ef1b280e41289b3e697b714b187175128
[ "MIT" ]
permissive
Azure/azure-iot-sdk-c
54bf46938f5b8089ba06081cb4d7967fa3a8f777
1f3d95b4dae09927ae4bbe479e52d48acef1f93c
refs/heads/main
2023-08-31T03:36:13.694208
2023-08-30T23:56:13
2023-08-30T23:56:13
70,934,373
629
902
NOASSERTION
2023-09-06T17:41:38
2016-10-14T17:54:57
C
UTF-8
C
false
false
2,214
h
provisioning_sc_device_registration_state.h
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifndef PROVISIONING_SC_DEVICE_REGISTRATION_STATE_H #define PROVISIONING_SC_DEVICE_REGISTRATION_STATE_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "umock_c/umock_c_prod.h" #include "azure_macro_utils/macro_utils.h" #include "parson.h" typedef struct DEVICE_REGISTRATION_STATE_TAG* DEVICE_REGISTRATION_STATE_HANDLE; #define REGISTRATION_STATUS_VALUES \ REGISTRATION_STATUS_ERROR, \ REGISTRATION_STATUS_UNASSIGNED, \ REGISTRATION_STATUS_ASSIGNING, \ REGISTRATION_STATUS_ASSIGNED, \ REGISTRATION_STATUS_FAILED, \ REGISTRATION_STATUS_DISABLED \ //Note: REGISTRATION_STATUS_ERROR is invalid, indicating error MU_DEFINE_ENUM_WITHOUT_INVALID(REGISTRATION_STATUS, REGISTRATION_STATUS_VALUES); /* Accessor Functions */ MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getRegistrationId, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getCreatedDateTime, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getDeviceId, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, REGISTRATION_STATUS, deviceRegistrationState_getRegistrationStatus, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getUpdatedDateTime, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, int, deviceRegistrationState_getErrorCode, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getErrorMessage, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, const char*, deviceRegistrationState_getEtag, DEVICE_REGISTRATION_STATE_HANDLE, drs); MOCKABLE_FUNCTION(, void, deviceRegistrationState_destroy, DEVICE_REGISTRATION_STATE_HANDLE, device_reg_state); /*---INTERNAL USAGE ONLY---*/ MOCKABLE_FUNCTION(, DEVICE_REGISTRATION_STATE_HANDLE, deviceRegistrationState_fromJson, JSON_Object*, root_object); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* PROVISIONING_SC_DEVICE_REGISTRATION_STATE_H */
50b6e82a1f6d6c2b4623ae0853c8053f715a275c
07745cfc4ec9843d8aa434db80c6410229dfda2e
/testdata/headers/linux/bpf.h
80db992a2c1b56458a9ffdcc36a07112d4a9ace1
[ "BSD-3-Clause" ]
permissive
cloudflare/xdpcap
703502dd52e124fdd80d57d9e4a61bb66c279384
417804f8035fea98edb2416f3d4c32780bc75b02
refs/heads/master
2023-08-21T15:26:18.414285
2022-10-18T08:06:20
2022-10-18T08:27:13
175,179,794
604
79
BSD-3-Clause
2023-07-24T17:30:37
2019-03-12T09:41:37
Go
UTF-8
C
false
false
1,419
h
bpf.h
#ifndef __LINUX_BPF_H__ #define __LINUX_BPF_H__ #define __u32 int enum bpf_map_type { BPF_MAP_TYPE_UNSPEC, BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PROG_ARRAY, BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_PERCPU_HASH, BPF_MAP_TYPE_PERCPU_ARRAY, BPF_MAP_TYPE_STACK_TRACE, BPF_MAP_TYPE_CGROUP_ARRAY, BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, BPF_MAP_TYPE_LPM_TRIE, BPF_MAP_TYPE_ARRAY_OF_MAPS, BPF_MAP_TYPE_HASH_OF_MAPS, BPF_MAP_TYPE_DEVMAP, BPF_MAP_TYPE_SOCKMAP, BPF_MAP_TYPE_CPUMAP, BPF_MAP_TYPE_XSKMAP, BPF_MAP_TYPE_SOCKHASH, BPF_MAP_TYPE_CGROUP_STORAGE, BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE, BPF_MAP_TYPE_QUEUE, BPF_MAP_TYPE_STACK, }; /* User return codes for XDP prog type. * A valid XDP program must return one of these defined values. All other * return codes are reserved for future use. Unknown return codes will * result in packet drops and a warning via bpf_warn_invalid_xdp_action(). */ enum xdp_action { XDP_ABORTED = 0, XDP_DROP, XDP_PASS, XDP_TX, XDP_REDIRECT, }; /* user accessible metadata for XDP packet hook * new fields must be added to the end of this structure */ struct xdp_md { __u32 data; __u32 data_end; __u32 data_meta; /* Below access go through struct xdp_rxq_info */ __u32 ingress_ifindex; /* rxq->dev->ifindex */ __u32 rx_queue_index; /* rxq->queue_index */ }; #endif /* __LINUX_BPF_H__ */
fa753b2e4c4b79d2bcd182d3086524a9ae41778b
3a30cfb29aac91e5c75d4dbcefddfd1f34d5f18c
/c-tests/gcc/921123-2.c
711de89d43ee943f0bb02d5cfa7ddc8292527dec
[ "GPL-3.0-only", "GPL-2.0-only", "MIT", "MPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LGPL-2.0-only" ]
permissive
vnmakarov/mir
a1725bc9c828e8580df6b7ae94e04175db8abe93
928e28fb3acaa50d051a906e76a55cc48a556574
refs/heads/master
2023-09-02T11:10:37.434581
2023-08-25T19:25:40
2023-08-25T19:25:40
178,932,492
2,005
156
MIT
2023-08-01T20:29:59
2019-04-01T19:24:56
C
UTF-8
C
false
false
292
c
921123-2.c
extern void exit (int); typedef struct { unsigned short b0, b1, b2, b3; } four_quarters; four_quarters x; int a, b; void f (four_quarters j) { b = j.b2; a = j.b3; } main () { four_quarters x; x.b0 = x.b1 = x.b2 = 0; x.b3 = 38; f(x); if (a != 38) abort(); exit (0); }
1fbfaf5f153deca9e73ba4caec9f7a2862707a61
90b45421155e34002fd133c7939d1f3bbb1173ff
/src/conn-tools/s6-sudo.c
56d7dcc3acddf48d7e3c31184058df4e6bffe23f
[ "ISC" ]
permissive
skarnet/s6
6ac71ec910f7d8a40bcd1e668eae3eaf6fab98df
1cbe4b09e027e31d258c24feee0be46958888b93
refs/heads/master
2023-08-18T08:02:16.943355
2023-08-10T15:42:00
2023-08-10T15:42:00
31,460,641
724
48
ISC
2020-06-26T11:56:36
2015-02-28T11:26:29
C
UTF-8
C
false
false
2,146
c
s6-sudo.c
/* ISC license. */ #include <skalibs/types.h> #include <skalibs/sgetopt.h> #include <skalibs/strerr.h> #include <skalibs/exec.h> #include <s6/config.h> #define USAGE "s6-sudo [ -q | -Q | -v ] [ -p bindpath ] [ -l localname ] [ -e ] [ -t timeout ] [ -T timeoutrun ] path [ args... ]" #define dieusage() strerr_dieusage(100, USAGE) int main (int argc, char const *const *argv) { unsigned int verbosity = 1, t = 0, T = 0 ; char const *bindpath = 0 ; char const *localname = 0 ; int nodoenv = 0 ; PROG = "s6-sudo" ; { subgetopt l = SUBGETOPT_ZERO ; for (;;) { int opt = subgetopt_r(argc, argv, "qQvp:l:et:T:", &l) ; if (opt == -1) break ; switch (opt) { case 'q' : if (verbosity) verbosity-- ; break ; case 'Q' : verbosity = 1 ; break ; case 'v' : verbosity++ ; break ; case 'p' : bindpath = l.arg ; break ; case 'l' : localname = l.arg ; break ; case 'e' : nodoenv = 1 ; break ; case 't' : if (!uint0_scan(l.arg, &t)) dieusage() ; break ; case 'T' : if (!uint0_scan(l.arg, &T)) dieusage() ; break ; default : dieusage() ; } } argc -= l.ind ; argv += l.ind ; } if (!argc) dieusage() ; if (verbosity > 4) verbosity = 4 ; { char const *eargv[9 + argc + ((verbosity < 2 ? 1 : verbosity-1)) + ((!!bindpath + !!localname) << 1) + nodoenv] ; char fmt1[UINT_FMT] ; char fmt2[UINT_FMT] ; unsigned int n = 0 ; eargv[n++] = S6_BINPREFIX "s6-ipcclient" ; if (!verbosity) eargv[n++] = "-Q" ; else while (--verbosity) eargv[n++] = "-v" ; if (bindpath) { eargv[n++] = "-p" ; eargv[n++] = bindpath ; } if (localname) { eargv[n++] = "-l" ; eargv[n++] = localname ; } eargv[n++] = "--" ; eargv[n++] = *argv++ ; argc-- ; eargv[n++] = S6_BINPREFIX "s6-sudoc" ; if (nodoenv) eargv[n++] = "-e" ; eargv[n++] = "-t" ; fmt1[uint_fmt(fmt1, t)] = 0 ; eargv[n++] = fmt1 ; eargv[n++] = "-T" ; fmt2[uint_fmt(fmt2, T)] = 0 ; eargv[n++] = fmt2 ; eargv[n++] = "--" ; while (argc--) eargv[n++] = *argv++ ; eargv[n++] = 0 ; xexec(eargv) ; } }
e7c7ee30a550ab11c1d9f50c6a5186c3b204a445
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/sparc-linux-any/asm/msgbuf.h
7c914ed48ae3d97e0e377fed7519abf5150b9cf1
[ "MIT" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
1,217
h
msgbuf.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _SPARC_MSGBUF_H #define _SPARC_MSGBUF_H #include <asm/ipcbuf.h> /* * The msqid64_ds structure for sparc64 architecture. * Note extra padding because this structure is passed back and forth * between kernel and user space. * * Pad space is left for: * - 2 miscellaneous 32-bit values */ struct msqid64_ds { struct ipc64_perm msg_perm; #if defined(__sparc__) && defined(__arch64__) long msg_stime; /* last msgsnd time */ long msg_rtime; /* last msgrcv time */ long msg_ctime; /* last change time */ #else unsigned long msg_stime_high; unsigned long msg_stime; /* last msgsnd time */ unsigned long msg_rtime_high; unsigned long msg_rtime; /* last msgrcv time */ unsigned long msg_ctime_high; unsigned long msg_ctime; /* last change time */ #endif unsigned long msg_cbytes; /* current number of bytes on queue */ unsigned long msg_qnum; /* number of messages in queue */ unsigned long msg_qbytes; /* max number of bytes on queue */ __kernel_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_pid_t msg_lrpid; /* last receive pid */ unsigned long __unused1; unsigned long __unused2; }; #endif /* _SPARC_MSGBUF_H */
dc00fa7ef4a5c000f044aafb4974f7bf8073c590
e48198ffea7b0b80669253fb970fdcc1d2f4c518
/src/dict.c
ce807350cd1c6287a788bda4e74430aeea80f1fa
[ "GPL-1.0-or-later", "Vim", "GPL-2.0-only" ]
permissive
vim/vim
f9ea5913ff884c87bc11f7826b1fc277fba8a2b5
816fbcc262687b81fc46f82f7bbeb1453addfe0c
refs/heads/master
2023-09-01T16:01:56.964678
2023-08-31T21:52:30
2023-08-31T21:52:30
40,997,482
37,589
7,920
Vim
2023-09-14T20:57:43
2015-08-18T21:03:56
Vim Script
UTF-8
C
false
false
34,783
c
dict.c
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * dict.c: Dictionary support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) // List head for garbage collection. Although there can be a reference loop // from partial to dict to partial, we don't need to keep track of the partial, // since it will get freed when the dict is unused and gets freed. static dict_T *first_dict = NULL; /* * Allocate an empty header for a dictionary. * Caller should take care of the reference count. */ dict_T * dict_alloc(void) { dict_T *d; d = ALLOC_CLEAR_ONE(dict_T); if (d == NULL) return NULL; // Add the dict to the list of dicts for garbage collection. if (first_dict != NULL) first_dict->dv_used_prev = d; d->dv_used_next = first_dict; d->dv_used_prev = NULL; first_dict = d; hash_init(&d->dv_hashtab); d->dv_lock = 0; d->dv_scope = 0; d->dv_refcount = 0; d->dv_copyID = 0; return d; } /* * dict_alloc() with an ID for alloc_fail(). */ dict_T * dict_alloc_id(alloc_id_T id UNUSED) { #ifdef FEAT_EVAL if (alloc_fail_id == id && alloc_does_fail(sizeof(list_T))) return NULL; #endif return (dict_alloc()); } dict_T * dict_alloc_lock(int lock) { dict_T *d = dict_alloc(); if (d != NULL) d->dv_lock = lock; return d; } /* * Allocate an empty dict for a return value. * Returns OK or FAIL. */ int rettv_dict_alloc(typval_T *rettv) { dict_T *d = dict_alloc_lock(0); if (d == NULL) return FAIL; rettv_dict_set(rettv, d); return OK; } /* * Set a dictionary as the return value */ void rettv_dict_set(typval_T *rettv, dict_T *d) { rettv->v_type = VAR_DICT; rettv->vval.v_dict = d; if (d != NULL) ++d->dv_refcount; } /* * Free a Dictionary, including all non-container items it contains. * Ignores the reference count. */ void dict_free_contents(dict_T *d) { hashtab_free_contents(&d->dv_hashtab); free_type(d->dv_type); d->dv_type = NULL; } /* * Clear hashtab "ht" and dict items it contains. * If "ht" is not freed then you should call hash_init() next! */ void hashtab_free_contents(hashtab_T *ht) { int todo; hashitem_T *hi; dictitem_T *di; if (check_hashtab_frozen(ht, "clear dict")) return; // Lock the hashtab, we don't want it to resize while freeing items. hash_lock(ht); todo = (int)ht->ht_used; FOR_ALL_HASHTAB_ITEMS(ht, hi, todo) { if (!HASHITEM_EMPTY(hi)) { // Remove the item before deleting it, just in case there is // something recursive causing trouble. di = HI2DI(hi); hash_remove(ht, hi, "clear dict"); dictitem_free(di); --todo; } } // The hashtab is still locked, it has to be re-initialized anyway. hash_clear(ht); } static void dict_free_dict(dict_T *d) { // Remove the dict from the list of dicts for garbage collection. if (d->dv_used_prev == NULL) first_dict = d->dv_used_next; else d->dv_used_prev->dv_used_next = d->dv_used_next; if (d->dv_used_next != NULL) d->dv_used_next->dv_used_prev = d->dv_used_prev; vim_free(d); } static void dict_free(dict_T *d) { if (!in_free_unref_items) { dict_free_contents(d); dict_free_dict(d); } } /* * Unreference a Dictionary: decrement the reference count and free it when it * becomes zero. */ void dict_unref(dict_T *d) { if (d != NULL && --d->dv_refcount <= 0) dict_free(d); } /* * Go through the list of dicts and free items without the copyID. * Returns TRUE if something was freed. */ int dict_free_nonref(int copyID) { dict_T *dd; int did_free = FALSE; for (dd = first_dict; dd != NULL; dd = dd->dv_used_next) if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { // Free the Dictionary and ordinary items it contains, but don't // recurse into Lists and Dictionaries, they will be in the list // of dicts or list of lists. dict_free_contents(dd); did_free = TRUE; } return did_free; } void dict_free_items(int copyID) { dict_T *dd, *dd_next; for (dd = first_dict; dd != NULL; dd = dd_next) { dd_next = dd->dv_used_next; if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) dict_free_dict(dd); } } /* * Allocate a Dictionary item. * The "key" is copied to the new item. * Note that the type and value of the item "di_tv" still needs to be * initialized! * Returns NULL when out of memory. */ dictitem_T * dictitem_alloc(char_u *key) { dictitem_T *di; size_t len = STRLEN(key); di = alloc(offsetof(dictitem_T, di_key) + len + 1); if (di == NULL) return NULL; mch_memmove(di->di_key, key, len + 1); di->di_flags = DI_FLAGS_ALLOC; di->di_tv.v_lock = 0; di->di_tv.v_type = VAR_UNKNOWN; return di; } /* * Make a copy of a Dictionary item. */ static dictitem_T * dictitem_copy(dictitem_T *org) { dictitem_T *di; size_t len = STRLEN(org->di_key); di = alloc(offsetof(dictitem_T, di_key) + len + 1); if (di == NULL) return NULL; mch_memmove(di->di_key, org->di_key, len + 1); di->di_flags = DI_FLAGS_ALLOC; copy_tv(&org->di_tv, &di->di_tv); return di; } /* * Remove item "item" from Dictionary "dict" and free it. * "command" is used for the error message when the hashtab if frozen. */ void dictitem_remove(dict_T *dict, dictitem_T *item, char *command) { hashitem_T *hi; hi = hash_find(&dict->dv_hashtab, item->di_key); if (HASHITEM_EMPTY(hi)) internal_error("dictitem_remove()"); else hash_remove(&dict->dv_hashtab, hi, command); dictitem_free(item); } /* * Free a dict item. Also clears the value. */ void dictitem_free(dictitem_T *item) { clear_tv(&item->di_tv); if (item->di_flags & DI_FLAGS_ALLOC) vim_free(item); } /* * Make a copy of dict "d". Shallow if "deep" is FALSE. * The refcount of the new dict is set to 1. * See item_copy() for "top" and "copyID". * Returns NULL when out of memory. */ dict_T * dict_copy(dict_T *orig, int deep, int top, int copyID) { dict_T *copy; dictitem_T *di; int todo; hashitem_T *hi; if (orig == NULL) return NULL; copy = dict_alloc(); if (copy == NULL) return NULL; if (copyID != 0) { orig->dv_copyID = copyID; orig->dv_copydict = copy; } if (orig->dv_type == NULL || top || deep) copy->dv_type = NULL; else copy->dv_type = alloc_type(orig->dv_type); todo = (int)orig->dv_hashtab.ht_used; for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = dictitem_alloc(hi->hi_key); if (di == NULL) break; if (deep) { if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep, FALSE, copyID) == FAIL) { vim_free(di); break; } } else copy_tv(&HI2DI(hi)->di_tv, &di->di_tv); if (dict_add(copy, di) == FAIL) { dictitem_free(di); break; } } } ++copy->dv_refcount; if (todo > 0) { dict_unref(copy); copy = NULL; } return copy; } /* * Check for adding a function to g: or s: (in Vim9 script) or l:. * If the name is wrong give an error message and return TRUE. */ int dict_wrong_func_name(dict_T *d, typval_T *tv, char_u *name) { return (d == get_globvar_dict() || (in_vim9script() && SCRIPT_ID_VALID(current_sctx.sc_sid) && d == &SCRIPT_ITEM(current_sctx.sc_sid)->sn_vars->sv_dict) || &d->dv_hashtab == get_funccal_local_ht()) && (tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL) && var_wrong_func_name(name, TRUE); } /* * Add item "item" to Dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add(dict_T *d, dictitem_T *item) { if (dict_wrong_func_name(d, &item->di_tv, item->di_key)) return FAIL; return hash_add(&d->dv_hashtab, item->di_key, "add to dictionary"); } /* * Add a number or special entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ static int dict_add_number_special(dict_T *d, char *key, varnumber_T nr, vartype_T vartype) { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_type = vartype; item->di_tv.vval.v_number = nr; if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Add a number entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_number(dict_T *d, char *key, varnumber_T nr) { return dict_add_number_special(d, key, nr, VAR_NUMBER); } /* * Add a special entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_bool(dict_T *d, char *key, varnumber_T nr) { return dict_add_number_special(d, key, nr, VAR_BOOL); } /* * Add a string entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_string(dict_T *d, char *key, char_u *str) { return dict_add_string_len(d, key, str, -1); } /* * Add a string entry to dictionary "d". * "str" will be copied to allocated memory. * When "len" is -1 use the whole string, otherwise only this many bytes. * Returns FAIL when out of memory and when key already exists. */ int dict_add_string_len(dict_T *d, char *key, char_u *str, int len) { dictitem_T *item; char_u *val = NULL; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_type = VAR_STRING; if (str != NULL) { if (len == -1) val = vim_strsave(str); else val = vim_strnsave(str, len); } item->di_tv.vval.v_string = val; if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Add a list entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_list(dict_T *d, char *key, list_T *list) { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_type = VAR_LIST; item->di_tv.vval.v_list = list; ++list->lv_refcount; if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Add a typval_T entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_tv(dict_T *d, char *key, typval_T *tv) { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; copy_tv(tv, &item->di_tv); if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Add a callback to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_callback(dict_T *d, char *key, callback_T *cb) { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; put_callback(cb, &item->di_tv); if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Initializes "iter" for iterating over dictionary items with * dict_iterate_next(). * If "var" is not a Dict or an empty Dict then there will be nothing to * iterate over, no error is given. * NOTE: The dictionary must not change until iterating is finished! */ void dict_iterate_start(typval_T *var, dict_iterator_T *iter) { if (var->v_type != VAR_DICT || var->vval.v_dict == NULL) iter->dit_todo = 0; else { dict_T *d = var->vval.v_dict; iter->dit_todo = d->dv_hashtab.ht_used; iter->dit_hi = d->dv_hashtab.ht_array; } } /* * Iterate over the items referred to by "iter". It should be initialized with * dict_iterate_start(). * Returns a pointer to the key. * "*tv_result" is set to point to the value for that key. * If there are no more items, NULL is returned. */ char_u * dict_iterate_next(dict_iterator_T *iter, typval_T **tv_result) { dictitem_T *di; char_u *result; if (iter->dit_todo == 0) return NULL; while (HASHITEM_EMPTY(iter->dit_hi)) ++iter->dit_hi; di = HI2DI(iter->dit_hi); result = di->di_key; *tv_result = &di->di_tv; --iter->dit_todo; ++iter->dit_hi; return result; } /* * Add a dict entry to dictionary "d". * Returns FAIL when out of memory and when key already exists. */ int dict_add_dict(dict_T *d, char *key, dict_T *dict) { dictitem_T *item; item = dictitem_alloc((char_u *)key); if (item == NULL) return FAIL; item->di_tv.v_type = VAR_DICT; item->di_tv.vval.v_dict = dict; ++dict->dv_refcount; if (dict_add(d, item) == FAIL) { dictitem_free(item); return FAIL; } return OK; } /* * Get the number of items in a Dictionary. */ long dict_len(dict_T *d) { if (d == NULL) return 0L; return (long)d->dv_hashtab.ht_used; } /* * Find item "key[len]" in Dictionary "d". * If "len" is negative use strlen(key). * Returns NULL when not found. */ dictitem_T * dict_find(dict_T *d, char_u *key, int len) { #define AKEYLEN 200 char_u buf[AKEYLEN]; char_u *akey; char_u *tofree = NULL; hashitem_T *hi; if (d == NULL) return NULL; if (len < 0) akey = key; else if (len >= AKEYLEN) { tofree = akey = vim_strnsave(key, len); if (akey == NULL) return NULL; } else { // Avoid a malloc/free by using buf[]. vim_strncpy(buf, key, len); akey = buf; } hi = hash_find(&d->dv_hashtab, akey); vim_free(tofree); if (HASHITEM_EMPTY(hi)) return NULL; return HI2DI(hi); } /* * Returns TRUE if "key" is present in Dictionary "d". */ int dict_has_key(dict_T *d, char *key) { return dict_find(d, (char_u *)key, -1) != NULL; } /* * Get a typval_T item from a dictionary and copy it into "rettv". * Returns FAIL if the entry doesn't exist or out of memory. */ int dict_get_tv(dict_T *d, char *key, typval_T *rettv) { dictitem_T *di; di = dict_find(d, (char_u *)key, -1); if (di == NULL) return FAIL; copy_tv(&di->di_tv, rettv); return OK; } /* * Get a string item from a dictionary. * When "save" is TRUE allocate memory for it. * When FALSE a shared buffer is used, can only be used once! * Returns NULL if the entry doesn't exist or out of memory. */ char_u * dict_get_string(dict_T *d, char *key, int save) { dictitem_T *di; char_u *s; di = dict_find(d, (char_u *)key, -1); if (di == NULL) return NULL; s = tv_get_string(&di->di_tv); if (save && s != NULL) s = vim_strsave(s); return s; } /* * Get a number item from a dictionary. * Returns 0 if the entry doesn't exist. */ varnumber_T dict_get_number(dict_T *d, char *key) { return dict_get_number_def(d, key, 0); } /* * Get a number item from a dictionary. * Returns "def" if the entry doesn't exist. */ varnumber_T dict_get_number_def(dict_T *d, char *key, int def) { dictitem_T *di; di = dict_find(d, (char_u *)key, -1); if (di == NULL) return def; return tv_get_number(&di->di_tv); } /* * Get a number item from a dictionary. * Returns 0 if the entry doesn't exist. * Give an error if the entry is not a number. */ varnumber_T dict_get_number_check(dict_T *d, char_u *key) { dictitem_T *di; di = dict_find(d, key, -1); if (di == NULL) return 0; if (di->di_tv.v_type != VAR_NUMBER) { semsg(_(e_invalid_argument_str), tv_get_string(&di->di_tv)); return 0; } return tv_get_number(&di->di_tv); } /* * Get a bool item (number or true/false) from a dictionary. * Returns "def" if the entry doesn't exist. */ varnumber_T dict_get_bool(dict_T *d, char *key, int def) { dictitem_T *di; di = dict_find(d, (char_u *)key, -1); if (di == NULL) return def; return tv_get_bool(&di->di_tv); } /* * Return an allocated string with the string representation of a Dictionary. * May return NULL. */ char_u * dict2string(typval_T *tv, int copyID, int restore_copyID) { garray_T ga; int first = TRUE; char_u *tofree; char_u numbuf[NUMBUFLEN]; hashitem_T *hi; char_u *s; dict_T *d; int todo; if ((d = tv->vval.v_dict) == NULL) return NULL; ga_init2(&ga, sizeof(char), 80); ga_append(&ga, '{'); todo = (int)d->dv_hashtab.ht_used; FOR_ALL_HASHTAB_ITEMS(&d->dv_hashtab, hi, todo) { if (!HASHITEM_EMPTY(hi)) { --todo; if (first) first = FALSE; else ga_concat(&ga, (char_u *)", "); tofree = string_quote(hi->hi_key, FALSE); if (tofree != NULL) { ga_concat(&ga, tofree); vim_free(tofree); } ga_concat(&ga, (char_u *)": "); s = echo_string_core(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID, FALSE, restore_copyID, TRUE); if (s != NULL) ga_concat(&ga, s); vim_free(tofree); if (s == NULL || did_echo_string_emsg) break; line_breakcheck(); } } if (todo > 0) { vim_free(ga.ga_data); return NULL; } ga_append(&ga, '}'); ga_append(&ga, NUL); return (char_u *)ga.ga_data; } /* * Advance over a literal key, including "-". If the first character is not a * literal key character then "key" is returned. */ static char_u * skip_literal_key(char_u *key) { char_u *p; for (p = key; ASCII_ISALNUM(*p) || *p == '_' || *p == '-'; ++p) ; return p; } /* * Get the key for #{key: val} into "tv" and advance "arg". * Return FAIL when there is no valid key. */ static int get_literal_key_tv(char_u **arg, typval_T *tv) { char_u *p = skip_literal_key(*arg); if (p == *arg) return FAIL; tv->v_type = VAR_STRING; tv->vval.v_string = vim_strnsave(*arg, p - *arg); *arg = p; return OK; } /* * Get a literal key for a Vim9 dict: * {"name": value}, * {'name': value}, * {name: value} use "name" as a literal key * Return the key in allocated memory or NULL in the case of an error. * "arg" is advanced to just after the key. */ char_u * get_literal_key(char_u **arg) { char_u *key; char_u *end; typval_T rettv; if (**arg == '\'') { if (eval_lit_string(arg, &rettv, TRUE, FALSE) == FAIL) return NULL; key = rettv.vval.v_string; } else if (**arg == '"') { if (eval_string(arg, &rettv, TRUE, FALSE) == FAIL) return NULL; key = rettv.vval.v_string; } else { end = skip_literal_key(*arg); if (end == *arg) { semsg(_(e_invalid_key_str), *arg); return NULL; } key = vim_strnsave(*arg, end - *arg); *arg = end; } return key; } /* * Allocate a variable for a Dictionary and fill it from "*arg". * "*arg" points to the "{". * "literal" is TRUE for #{key: val} * Return OK or FAIL. Returns NOTDONE for {expr}. */ int eval_dict(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int literal) { int evaluate = evalarg == NULL ? FALSE : (evalarg->eval_flags & EVAL_EVALUATE); dict_T *d = NULL; typval_T tvkey; typval_T tv; char_u *key = NULL; dictitem_T *item; char_u *curly_expr = skipwhite(*arg + 1); char_u buf[NUMBUFLEN]; int vim9script = in_vim9script(); int had_comma; // First check if it's not a curly-braces expression: {expr}. // Must do this without evaluating, otherwise a function may be called // twice. Unfortunately this means we need to call eval1() twice for the // first item. // "{}" is an empty Dictionary. // "#{abc}" is never a curly-braces expression. if (!vim9script && *curly_expr != '}' && !literal && eval1(&curly_expr, &tv, NULL) == OK && *skipwhite(curly_expr) == '}') return NOTDONE; if (evaluate) { d = dict_alloc(); if (d == NULL) return FAIL; } tvkey.v_type = VAR_UNKNOWN; tv.v_type = VAR_UNKNOWN; *arg = skipwhite_and_linebreak(*arg + 1, evalarg); while (**arg != '}' && **arg != NUL) { int has_bracket = vim9script && **arg == '['; if (literal) { if (get_literal_key_tv(arg, &tvkey) == FAIL) goto failret; } else if (vim9script && !has_bracket) { tvkey.vval.v_string = get_literal_key(arg); if (tvkey.vval.v_string == NULL) goto failret; tvkey.v_type = VAR_STRING; } else { if (has_bracket) *arg = skipwhite(*arg + 1); if (eval1(arg, &tvkey, evalarg) == FAIL) // recursive! goto failret; if (has_bracket) { *arg = skipwhite(*arg); if (**arg != ']') { emsg(_(e_missing_matching_bracket_after_dict_key)); clear_tv(&tvkey); return FAIL; } ++*arg; } } // the colon should come right after the key, but this wasn't checked // previously, so only require it in Vim9 script. if (!vim9script) *arg = skipwhite(*arg); if (**arg != ':') { if (*skipwhite(*arg) == ':') semsg(_(e_no_white_space_allowed_before_str_str), ":", *arg); else semsg(_(e_missing_colon_in_dictionary_str), *arg); clear_tv(&tvkey); goto failret; } if (evaluate) { if (tvkey.v_type == VAR_FLOAT) { tvkey.vval.v_string = typval_tostring(&tvkey, TRUE); tvkey.v_type = VAR_STRING; } key = tv_get_string_buf_chk(&tvkey, buf); if (key == NULL) { // "key" is NULL when tv_get_string_buf_chk() gave an errmsg clear_tv(&tvkey); goto failret; } } if (vim9script && (*arg)[1] != NUL && !VIM_ISWHITE((*arg)[1])) { semsg(_(e_white_space_required_after_str_str), ":", *arg); clear_tv(&tvkey); goto failret; } *arg = skipwhite_and_linebreak(*arg + 1, evalarg); if (eval1(arg, &tv, evalarg) == FAIL) // recursive! { if (evaluate) clear_tv(&tvkey); goto failret; } if (evaluate) { item = dict_find(d, key, -1); if (item != NULL) { semsg(_(e_duplicate_key_in_dictionary_str), key); clear_tv(&tvkey); clear_tv(&tv); goto failret; } item = dictitem_alloc(key); if (item != NULL) { item->di_tv = tv; item->di_tv.v_lock = 0; if (dict_add(d, item) == FAIL) dictitem_free(item); } } clear_tv(&tvkey); // the comma should come right after the value, but this wasn't checked // previously, so only require it in Vim9 script. if (!vim9script) *arg = skipwhite(*arg); had_comma = **arg == ','; if (had_comma) { if (vim9script && (*arg)[1] != NUL && !VIM_ISWHITE((*arg)[1])) { semsg(_(e_white_space_required_after_str_str), ",", *arg); goto failret; } *arg = skipwhite(*arg + 1); } // the "}" can be on the next line *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg == '}') break; if (!had_comma) { if (**arg == ',') semsg(_(e_no_white_space_allowed_before_str_str), ",", *arg); else semsg(_(e_missing_comma_in_dictionary_str), *arg); goto failret; } } if (**arg != '}') { if (evalarg != NULL) semsg(_(e_missing_dict_end_str), *arg); failret: if (d != NULL) dict_free(d); return FAIL; } *arg = *arg + 1; if (evaluate) rettv_dict_set(rettv, d); return OK; } /* * Go over all entries in "d2" and add them to "d1". * When "action" is "error" then a duplicate key is an error. * When "action" is "force" then a duplicate key is overwritten. * When "action" is "move" then move items instead of copying. * Otherwise duplicate keys are ignored ("action" is "keep"). * "func_name" is used for reporting where an error occurred. */ void dict_extend(dict_T *d1, dict_T *d2, char_u *action, char *func_name) { dictitem_T *di1; int todo; char_u *arg_errmsg = (char_u *)N_("extend() argument"); type_T *type; if (check_hashtab_frozen(&d1->dv_hashtab, "extend")) return; if (*action == 'm') { if (check_hashtab_frozen(&d2->dv_hashtab, "extend")) return; hash_lock(&d2->dv_hashtab); // don't rehash on hash_remove() } if (d1->dv_type != NULL && d1->dv_type->tt_member != NULL) type = d1->dv_type->tt_member; else type = NULL; todo = (int)d2->dv_hashtab.ht_used; hashitem_T *hi2; FOR_ALL_HASHTAB_ITEMS(&d2->dv_hashtab, hi2, todo) { if (!HASHITEM_EMPTY(hi2)) { --todo; di1 = dict_find(d1, hi2->hi_key, -1); // Check the key to be valid when adding to any scope. if (d1->dv_scope != 0 && !valid_varname(hi2->hi_key, -1, TRUE)) break; if (type != NULL && check_typval_arg_type(type, &HI2DI(hi2)->di_tv, func_name, 0) == FAIL) break; if (di1 == NULL) { if (*action == 'm') { // Cheap way to move a dict item from "d2" to "d1". // If dict_add() fails then "d2" won't be empty. di1 = HI2DI(hi2); if (dict_add(d1, di1) == OK) hash_remove(&d2->dv_hashtab, hi2, "extend"); } else { di1 = dictitem_copy(HI2DI(hi2)); if (di1 != NULL && dict_add(d1, di1) == FAIL) dictitem_free(di1); } } else if (*action == 'e') { semsg(_(e_key_already_exists_str), hi2->hi_key); break; } else if (*action == 'f' && HI2DI(hi2) != di1) { if (value_check_lock(di1->di_tv.v_lock, arg_errmsg, TRUE) || var_check_ro(di1->di_flags, arg_errmsg, TRUE)) break; // Disallow replacing a builtin function. if (dict_wrong_func_name(d1, &HI2DI(hi2)->di_tv, hi2->hi_key)) break; clear_tv(&di1->di_tv); copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv); } } } if (*action == 'm') hash_unlock(&d2->dv_hashtab); } /* * Return the dictitem that an entry in a hashtable points to. */ dictitem_T * dict_lookup(hashitem_T *hi) { return HI2DI(hi); } /* * Return TRUE when two dictionaries have exactly the same key/values. */ int dict_equal( dict_T *d1, dict_T *d2, int ic, // ignore case for strings int recursive) // TRUE when used recursively { hashitem_T *hi; dictitem_T *item2; int todo; if (d1 == d2) return TRUE; if (dict_len(d1) != dict_len(d2)) return FALSE; if (dict_len(d1) == 0) // empty and NULL dicts are considered equal return TRUE; if (d1 == NULL || d2 == NULL) return FALSE; todo = (int)d1->dv_hashtab.ht_used; FOR_ALL_HASHTAB_ITEMS(&d1->dv_hashtab, hi, todo) { if (!HASHITEM_EMPTY(hi)) { item2 = dict_find(d2, hi->hi_key, -1); if (item2 == NULL) return FALSE; if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic, recursive)) return FALSE; --todo; } } return TRUE; } /* * Count the number of times item "needle" occurs in Dict "d". Case is ignored * if "ic" is TRUE. */ long dict_count(dict_T *d, typval_T *needle, int ic) { int todo; hashitem_T *hi; long n = 0; if (d == NULL) return 0; todo = (int)d->dv_hashtab.ht_used; FOR_ALL_HASHTAB_ITEMS(&d->dv_hashtab, hi, todo) { if (!HASHITEM_EMPTY(hi)) { --todo; if (tv_equal(&HI2DI(hi)->di_tv, needle, ic, FALSE)) ++n; } } return n; } /* * extend() a Dict. Append Dict argvars[1] to Dict argvars[0] and return the * resulting Dict in "rettv". "is_new" is TRUE for extendnew(). */ void dict_extend_func( typval_T *argvars, type_T *type, char *func_name, char_u *arg_errmsg, int is_new, typval_T *rettv) { dict_T *d1, *d2; char_u *action; int i; d1 = argvars[0].vval.v_dict; if (d1 == NULL) { emsg(_(e_cannot_extend_null_dict)); return; } d2 = argvars[1].vval.v_dict; if (d2 == NULL) return; if (!is_new && value_check_lock(d1->dv_lock, arg_errmsg, TRUE)) return; if (is_new) { d1 = dict_copy(d1, FALSE, TRUE, get_copyID()); if (d1 == NULL) return; } // Check the third argument. if (argvars[2].v_type != VAR_UNKNOWN) { static char *(av[]) = {"keep", "force", "error"}; action = tv_get_string_chk(&argvars[2]); if (action == NULL) return; for (i = 0; i < 3; ++i) if (STRCMP(action, av[i]) == 0) break; if (i == 3) { semsg(_(e_invalid_argument_str), action); return; } } else action = (char_u *)"force"; if (type != NULL && check_typval_arg_type(type, &argvars[1], func_name, 2) == FAIL) return; dict_extend(d1, d2, action, func_name); if (is_new) { rettv->v_type = VAR_DICT; rettv->vval.v_dict = d1; rettv->v_lock = FALSE; } else copy_tv(&argvars[0], rettv); } /* * Implementation of map() and filter() for a Dict. Apply "expr" to every * item in Dict "d" and return the result in "rettv". */ void dict_filter_map( dict_T *d, filtermap_T filtermap, type_T *argtype, char *func_name, char_u *arg_errmsg, typval_T *expr, typval_T *rettv) { dict_T *d_ret = NULL; hashtab_T *ht; hashitem_T *hi; dictitem_T *di; int todo; int rem; typval_T newtv; funccall_T *fc; if (filtermap == FILTERMAP_MAPNEW) { rettv->v_type = VAR_DICT; rettv->vval.v_dict = NULL; } if (d == NULL || (filtermap == FILTERMAP_FILTER && value_check_lock(d->dv_lock, arg_errmsg, TRUE))) return; if (filtermap == FILTERMAP_MAPNEW) { if (rettv_dict_alloc(rettv) == FAIL) return; d_ret = rettv->vval.v_dict; } // Create one funccall_T for all eval_expr_typval() calls. fc = eval_expr_get_funccal(expr, &newtv); int prev_lock = d->dv_lock; if (d->dv_lock == 0) d->dv_lock = VAR_LOCKED; ht = &d->dv_hashtab; hash_lock(ht); todo = (int)ht->ht_used; FOR_ALL_HASHTAB_ITEMS(ht, hi, todo) { if (!HASHITEM_EMPTY(hi)) { int r; --todo; di = HI2DI(hi); if (filtermap == FILTERMAP_MAP && (value_check_lock(di->di_tv.v_lock, arg_errmsg, TRUE) || var_check_ro(di->di_flags, arg_errmsg, TRUE))) break; set_vim_var_string(VV_KEY, di->di_key, -1); newtv.v_type = VAR_UNKNOWN; r = filter_map_one(&di->di_tv, expr, filtermap, fc, &newtv, &rem); clear_tv(get_vim_var_tv(VV_KEY)); if (r == FAIL || did_emsg) { clear_tv(&newtv); break; } if (filtermap == FILTERMAP_MAP) { if (argtype != NULL && check_typval_arg_type( argtype->tt_member, &newtv, func_name, 0) == FAIL) { clear_tv(&newtv); break; } // map(): replace the dict item value clear_tv(&di->di_tv); newtv.v_lock = 0; di->di_tv = newtv; } else if (filtermap == FILTERMAP_MAPNEW) { // mapnew(): add the item value to the new dict r = dict_add_tv(d_ret, (char *)di->di_key, &newtv); clear_tv(&newtv); if (r == FAIL) break; } else if (filtermap == FILTERMAP_FILTER && rem) { // filter(false): remove the item from the dict if (var_check_fixed(di->di_flags, arg_errmsg, TRUE) || var_check_ro(di->di_flags, arg_errmsg, TRUE)) break; dictitem_remove(d, di, "filter"); } } } hash_unlock(ht); d->dv_lock = prev_lock; if (fc != NULL) remove_funccal(); } /* * "remove({dict})" function */ void dict_remove(typval_T *argvars, typval_T *rettv, char_u *arg_errmsg) { dict_T *d; char_u *key; dictitem_T *di; if (argvars[2].v_type != VAR_UNKNOWN) { semsg(_(e_too_many_arguments_for_function_str), "remove()"); return; } d = argvars[0].vval.v_dict; if (d == NULL || value_check_lock(d->dv_lock, arg_errmsg, TRUE)) return; key = tv_get_string_chk(&argvars[1]); if (key == NULL) return; di = dict_find(d, key, -1); if (di == NULL) { semsg(_(e_key_not_present_in_dictionary_str), key); return; } if (var_check_fixed(di->di_flags, arg_errmsg, TRUE) || var_check_ro(di->di_flags, arg_errmsg, TRUE)) return; *rettv = di->di_tv; init_tv(&di->di_tv); dictitem_remove(d, di, "remove()"); } typedef enum { DICT2LIST_KEYS, DICT2LIST_VALUES, DICT2LIST_ITEMS, } dict2list_T; /* * Turn a dict into a list. */ static void dict2list(typval_T *argvars, typval_T *rettv, dict2list_T what) { list_T *l2; dictitem_T *di; hashitem_T *hi; listitem_T *li; dict_T *d; int todo; if (rettv_list_alloc(rettv) == FAIL) return; if ((what == DICT2LIST_ITEMS ? check_for_string_or_list_or_dict_arg(argvars, 0) : check_for_dict_arg(argvars, 0)) == FAIL) return; d = argvars[0].vval.v_dict; if (d == NULL) // NULL dict behaves like an empty dict return; todo = (int)d->dv_hashtab.ht_used; FOR_ALL_HASHTAB_ITEMS(&d->dv_hashtab, hi, todo) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); li = listitem_alloc(); if (li == NULL) break; list_append(rettv->vval.v_list, li); if (what == DICT2LIST_KEYS) { // keys() li->li_tv.v_type = VAR_STRING; li->li_tv.v_lock = 0; li->li_tv.vval.v_string = vim_strsave(di->di_key); } else if (what == DICT2LIST_VALUES) { // values() copy_tv(&di->di_tv, &li->li_tv); } else { // items() l2 = list_alloc(); li->li_tv.v_type = VAR_LIST; li->li_tv.v_lock = 0; li->li_tv.vval.v_list = l2; if (l2 == NULL) break; ++l2->lv_refcount; if (list_append_string(l2, di->di_key, -1) == FAIL || list_append_tv(l2, &di->di_tv) == FAIL) break; } } } } /* * "items(dict)" function */ void f_items(typval_T *argvars, typval_T *rettv) { if (argvars[0].v_type == VAR_STRING) string2items(argvars, rettv); else if (argvars[0].v_type == VAR_LIST) list2items(argvars, rettv); else dict2list(argvars, rettv, DICT2LIST_ITEMS); } /* * "keys()" function */ void f_keys(typval_T *argvars, typval_T *rettv) { dict2list(argvars, rettv, DICT2LIST_KEYS); } /* * "values(dict)" function */ void f_values(typval_T *argvars, typval_T *rettv) { dict2list(argvars, rettv, DICT2LIST_VALUES); } /* * Make each item in the dict readonly (not the value of the item). */ void dict_set_items_ro(dict_T *di) { int todo = (int)di->dv_hashtab.ht_used; hashitem_T *hi; // Set readonly FOR_ALL_HASHTAB_ITEMS(&di->dv_hashtab, hi, todo) { if (HASHITEM_EMPTY(hi)) continue; --todo; HI2DI(hi)->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } } /* * "has_key()" function */ void f_has_key(typval_T *argvars, typval_T *rettv) { if (in_vim9script() && (check_for_dict_arg(argvars, 0) == FAIL || check_for_string_or_number_arg(argvars, 1) == FAIL)) return; if (check_for_dict_arg(argvars, 0) == FAIL) return; if (argvars[0].vval.v_dict == NULL) return; rettv->vval.v_number = dict_has_key(argvars[0].vval.v_dict, (char *)tv_get_string(&argvars[1])); } #endif // defined(FEAT_EVAL)
470340391aa4f8b7ba812c048f6f8fb418b541af
db229415713a206a848429321e19006b212d20d5
/test/arm/neon/tbx.c
d973376009ba6da9a246c5be4477628928fb8193
[ "MIT", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
simd-everywhere/simde
66dd029cbd0b3814b0377c72d953f223d38e7e53
4d55fc25bcfddc0e2f0c744448557a070dd310c9
refs/heads/master
2023-09-04T12:55:25.455223
2023-08-18T12:46:56
2023-08-18T14:53:06
86,497,800
1,570
173
MIT
2023-09-07T13:41:28
2017-03-28T19:14:32
C
UTF-8
C
false
false
58,446
c
tbx.c
#define SIMDE_TEST_ARM_NEON_INSN tbx #include "test-neon.h" /* Check that both of these work */ #if defined(__cplusplus) #include "../../../simde/arm/neon/tbx.h" #else #include "../../../simde/arm/neon.h" #endif #if 0 #define PROBABILITY 80 #define probability(p) (rand() < ((HEDLEY_STATIC_CAST(int64_t, RAND_MAX) * (p)) / 100)) #endif static int test_simde_vtbx1_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 int8_t a[8]; SIMDE_ALIGN_TO_16 int8_t b[8]; SIMDE_ALIGN_TO_16 int8_t c[8]; SIMDE_ALIGN_TO_16 int8_t r[8]; } test_vec[] = { { { INT8_C( 37), -INT8_C( 53), INT8_C( 27), INT8_C( 42), -INT8_C( 10), -INT8_C( 65), INT8_C( 122), -INT8_C( 112) }, { -INT8_C( 51), -INT8_C( 51), INT8_C( 80), INT8_C( 6), -INT8_C( 1), -INT8_C( 100), -INT8_C( 123), INT8_C( 47) }, { INT8_C( 1), INT8_C( 112), INT8_C( 7), INT8_C( 3), -INT8_C( 80), -INT8_C( 60), INT8_C( 3), -INT8_C( 89) }, { -INT8_C( 51), -INT8_C( 53), INT8_C( 47), INT8_C( 6), -INT8_C( 10), -INT8_C( 65), INT8_C( 6), -INT8_C( 112) } }, { { INT8_C( 123), INT8_C( 67), -INT8_C( 58), INT8_C( 113), INT8_C( 2), INT8_C( 64), INT8_C( 1), -INT8_C( 48) }, { INT8_C( 13), INT8_C( 81), -INT8_C( 42), INT8_C( 12), -INT8_C( 18), INT8_C( 91), INT8_C( 60), -INT8_C( 17) }, { INT8_C( 3), INT8_C( 3), INT8_C( 2), INT8_C( 4), INT8_C( 0), INT8_C( 5), INT8_C( 3), INT8_C( 7) }, { INT8_C( 12), INT8_C( 12), -INT8_C( 42), -INT8_C( 18), INT8_C( 13), INT8_C( 91), INT8_C( 12), -INT8_C( 17) } }, { { -INT8_C( 59), -INT8_C( 85), INT8_C( 93), -INT8_C( 57), -INT8_C( 21), INT8_C( 94), -INT8_C( 105), -INT8_C( 7) }, { -INT8_C( 80), INT8_C( 109), INT8_C( 5), -INT8_C( 98), -INT8_C( 55), INT8_C( 65), -INT8_C( 115), -INT8_C( 108) }, { INT8_C( 5), INT8_C( 0), INT8_C( 0), INT8_C( 5), INT8_C( 5), INT8_C( 3), INT8_C( 4), INT8_C( 1) }, { INT8_C( 65), -INT8_C( 80), -INT8_C( 80), INT8_C( 65), INT8_C( 65), -INT8_C( 98), -INT8_C( 55), INT8_C( 109) } }, { { INT8_C( 42), -INT8_C( 79), INT8_C( 11), INT8_C( 22), INT8_C( 15), -INT8_C( 93), INT8_C( 15), -INT8_C( 65) }, { INT8_C( 16), INT8_C( 20), INT8_C( 93), -INT8_C( 39), INT8_C( 86), -INT8_C( 21), INT8_C( 110), -INT8_C( 101) }, { INT8_C( 19), INT8_C( 6), INT8_C( 0), -INT8_C( 112), INT8_C( 2), INT8_C( 4), INT8_C( 1), -INT8_C( 89) }, { INT8_C( 42), INT8_C( 110), INT8_C( 16), INT8_C( 22), INT8_C( 93), INT8_C( 86), INT8_C( 20), -INT8_C( 65) } }, { { INT8_C( 19), INT8_C( 24), INT8_C( 60), INT8_C( 34), -INT8_C( 69), INT8_C( 75), -INT8_C( 30), -INT8_C( 53) }, { INT8_C( 95), INT8_C( 63), -INT8_C( 91), -INT8_C( 75), INT8_C( 42), INT8_C( 19), INT8_C( 80), INT8_C( 61) }, { INT8_C( 1), -INT8_C( 8), INT8_C( 6), INT8_C( 3), INT8_C( 4), INT8_C( 7), INT8_C( 3), INT8_C( 6) }, { INT8_C( 63), INT8_C( 24), INT8_C( 80), -INT8_C( 75), INT8_C( 42), INT8_C( 61), -INT8_C( 75), INT8_C( 80) } }, { { INT8_C( 123), -INT8_C( 119), -INT8_C( 111), INT8_C( 54), -INT8_C( 44), INT8_C( 115), INT8_C( 1), INT8_C( 51) }, { -INT8_C( 78), -INT8_C( 90), -INT8_C( 23), -INT8_C( 35), -INT8_C( 71), INT8_C( 57), INT8_C( 26), INT8_C( 75) }, { INT8_C( 50), INT8_C( 0), INT8_C( 6), INT8_C( 6), -INT8_C( 104), INT8_C( 1), INT8_C( 4), -INT8_C( 61) }, { INT8_C( 123), -INT8_C( 78), INT8_C( 26), INT8_C( 26), -INT8_C( 44), -INT8_C( 90), -INT8_C( 71), INT8_C( 51) } }, { { -INT8_C( 64), -INT8_C( 50), INT8_C( 111), -INT8_C( 108), INT8_C( 65), INT8_C( 112), -INT8_C( 56), -INT8_C( 13) }, { INT8_C( 23), -INT8_C( 79), -INT8_C( 48), -INT8_C( 48), -INT8_C( 22), -INT8_C( 21), INT8_C( 27), INT8_C( 28) }, { INT8_C( 3), INT8_C( 2), -INT8_C( 109), INT8_C( 3), INT8_C( 35), INT8_C( 7), INT8_C( 7), INT8_C( 6) }, { -INT8_C( 48), -INT8_C( 48), INT8_C( 111), -INT8_C( 48), INT8_C( 65), INT8_C( 28), INT8_C( 28), INT8_C( 27) } }, { { INT8_C( 112), INT8_C( 88), -INT8_C( 90), -INT8_C( 79), -INT8_C( 55), INT8_C( 110), -INT8_C( 92), -INT8_C( 32) }, { INT8_C( 31), INT8_C( 117), -INT8_C( 80), INT8_C( 9), INT8_C( 96), -INT8_C( 52), INT8_C( 38), INT8_C( 51) }, { INT8_C( 118), INT8_C( 1), INT8_C( 7), -INT8_C( 103), INT8_C( 80), INT8_C( 6), INT8_C( 0), INT8_C( 3) }, { INT8_C( 112), INT8_C( 117), INT8_C( 51), -INT8_C( 79), -INT8_C( 55), INT8_C( 38), INT8_C( 31), INT8_C( 9) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x8_t a = simde_vld1_s8(test_vec[i].a); simde_int8x8_t b = simde_vld1_s8(test_vec[i].b); simde_int8x8_t c = simde_vld1_s8(test_vec[i].c); simde_int8x8_t r = simde_vtbx1_s8(a, b, c); simde_test_arm_neon_assert_equal_i8x8(r, simde_vld1_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x8_t a = simde_test_arm_neon_random_i8x8(); simde_int8x8_t b = simde_test_arm_neon_random_i8x8(); simde_int8x8_private c_ = simde_int8x8_to_private(simde_test_arm_neon_random_i8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 7; } } simde_int8x8_t c = simde_int8x8_from_private(c_); simde_int8x8_t r = simde_vtbx1_s8(a, b, c); simde_test_arm_neon_write_i8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx1_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 uint8_t a[8]; SIMDE_ALIGN_TO_16 uint8_t b[8]; SIMDE_ALIGN_TO_16 uint8_t c[8]; SIMDE_ALIGN_TO_16 uint8_t r[8]; } test_vec[] = { { { UINT8_C( 43), UINT8_C(177), UINT8_C(250), UINT8_C(224), UINT8_C(205), UINT8_C( 54), UINT8_C(248), UINT8_C(150) }, { UINT8_C(177), UINT8_C( 61), UINT8_C(200), UINT8_C( 40), UINT8_C( 83), UINT8_C( 15), UINT8_C( 13), UINT8_C(128) }, { UINT8_C( 5), UINT8_C( 7), UINT8_C( 3), UINT8_C( 4), UINT8_C( 0), UINT8_C( 5), UINT8_C( 2), UINT8_C( 7) }, { UINT8_C( 15), UINT8_C(128), UINT8_C( 40), UINT8_C( 83), UINT8_C(177), UINT8_C( 15), UINT8_C(200), UINT8_C(128) } }, { { UINT8_C( 88), UINT8_C( 17), UINT8_C(177), UINT8_C( 37), UINT8_C( 71), UINT8_C(170), UINT8_C(187), UINT8_C(249) }, { UINT8_C(231), UINT8_C(131), UINT8_C( 33), UINT8_C( 59), UINT8_C(146), UINT8_C( 47), UINT8_C(187), UINT8_C(240) }, { UINT8_C( 6), UINT8_C( 6), UINT8_C( 4), UINT8_C( 6), UINT8_C( 11), UINT8_C( 6), UINT8_C( 6), UINT8_C( 6) }, { UINT8_C(187), UINT8_C(187), UINT8_C(146), UINT8_C(187), UINT8_C( 71), UINT8_C(187), UINT8_C(187), UINT8_C(187) } }, { { UINT8_C(231), UINT8_C(161), UINT8_C( 89), UINT8_C( 46), UINT8_C( 75), UINT8_C( 21), UINT8_C( 39), UINT8_C( 50) }, { UINT8_C(152), UINT8_C( 73), UINT8_C(109), UINT8_C( 43), UINT8_C(120), UINT8_C( 40), UINT8_C( 27), UINT8_C(254) }, { UINT8_C( 30), UINT8_C(127), UINT8_C( 4), UINT8_C( 41), UINT8_C( 6), UINT8_C( 2), UINT8_C( 7), UINT8_C( 7) }, { UINT8_C(231), UINT8_C(161), UINT8_C(120), UINT8_C( 46), UINT8_C( 27), UINT8_C(109), UINT8_C(254), UINT8_C(254) } }, { { UINT8_C(174), UINT8_C(225), UINT8_C( 10), UINT8_C(249), UINT8_C(246), UINT8_C( 49), UINT8_C( 43), UINT8_C(142) }, { UINT8_C(122), UINT8_C(153), UINT8_C(185), UINT8_C(242), UINT8_C(193), UINT8_C(212), UINT8_C(240), UINT8_C(224) }, { UINT8_C( 84), UINT8_C( 5), UINT8_C( 9), UINT8_C( 2), UINT8_C( 71), UINT8_C( 1), UINT8_C(217), UINT8_C( 7) }, { UINT8_C(174), UINT8_C(212), UINT8_C( 10), UINT8_C(185), UINT8_C(246), UINT8_C(153), UINT8_C( 43), UINT8_C(224) } }, { { UINT8_C(123), UINT8_C( 97), UINT8_C(170), UINT8_C(113), UINT8_C(147), UINT8_C(214), UINT8_MAX, UINT8_C( 13) }, { UINT8_C(111), UINT8_C(185), UINT8_C( 0), UINT8_C( 48), UINT8_C(141), UINT8_C(240), UINT8_C( 16), UINT8_C(225) }, { UINT8_C( 5), UINT8_C( 2), UINT8_C(187), UINT8_C( 5), UINT8_C( 3), UINT8_C(148), UINT8_C( 4), UINT8_C( 10) }, { UINT8_C(240), UINT8_C( 0), UINT8_C(170), UINT8_C(240), UINT8_C( 48), UINT8_C(214), UINT8_C(141), UINT8_C( 13) } }, { { UINT8_C( 63), UINT8_C(234), UINT8_C(148), UINT8_C(210), UINT8_C(192), UINT8_C(148), UINT8_C(224), UINT8_C( 47) }, { UINT8_C( 77), UINT8_C(224), UINT8_C( 96), UINT8_C(218), UINT8_C(208), UINT8_C(112), UINT8_C(188), UINT8_C(198) }, { UINT8_C( 2), UINT8_C(119), UINT8_C( 3), UINT8_C( 5), UINT8_C( 4), UINT8_C( 7), UINT8_C( 24), UINT8_C( 7) }, { UINT8_C( 96), UINT8_C(234), UINT8_C(218), UINT8_C(112), UINT8_C(208), UINT8_C(198), UINT8_C(224), UINT8_C(198) } }, { { UINT8_C( 80), UINT8_C(110), UINT8_C(142), UINT8_C( 16), UINT8_C( 2), UINT8_C(110), UINT8_C( 64), UINT8_C( 79) }, { UINT8_C( 78), UINT8_C(160), UINT8_C( 41), UINT8_C( 31), UINT8_C( 16), UINT8_C(229), UINT8_C(229), UINT8_C(155) }, { UINT8_C( 5), UINT8_C( 0), UINT8_C( 0), UINT8_C(105), UINT8_C( 7), UINT8_C( 0), UINT8_C( 0), UINT8_C( 4) }, { UINT8_C(229), UINT8_C( 78), UINT8_C( 78), UINT8_C( 16), UINT8_C(155), UINT8_C( 78), UINT8_C( 78), UINT8_C( 16) } }, { { UINT8_C(242), UINT8_C( 38), UINT8_C(235), UINT8_C(244), UINT8_C(148), UINT8_C( 43), UINT8_C( 67), UINT8_C(227) }, { UINT8_C(203), UINT8_C(108), UINT8_C( 2), UINT8_C(220), UINT8_C( 82), UINT8_C(231), UINT8_C(119), UINT8_C(175) }, { UINT8_C( 7), UINT8_C( 7), UINT8_C( 0), UINT8_C(182), UINT8_C( 0), UINT8_C( 0), UINT8_C(170), UINT8_C( 7) }, { UINT8_C(175), UINT8_C(175), UINT8_C(203), UINT8_C(244), UINT8_C(203), UINT8_C(203), UINT8_C( 67), UINT8_C(175) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x8_t a = simde_vld1_u8(test_vec[i].a); simde_uint8x8_t b = simde_vld1_u8(test_vec[i].b); simde_uint8x8_t c = simde_vld1_u8(test_vec[i].c); simde_uint8x8_t r = simde_vtbx1_u8(a, b, c); simde_test_arm_neon_assert_equal_u8x8(r, simde_vld1_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x8_t a = simde_test_arm_neon_random_u8x8(); simde_uint8x8_t b = simde_test_arm_neon_random_u8x8(); simde_uint8x8_private c_ = simde_uint8x8_to_private(simde_test_arm_neon_random_u8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 7; } } simde_uint8x8_t c = simde_uint8x8_from_private(c_); simde_uint8x8_t r = simde_vtbx1_u8(a, b, c); simde_test_arm_neon_write_u8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x8(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } #if !defined(SIMDE_BUG_INTEL_857088) static int test_simde_vtbx2_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 int8_t a[8]; SIMDE_ALIGN_TO_16 int8_t b[2][8]; SIMDE_ALIGN_TO_16 int8_t c[8]; SIMDE_ALIGN_TO_16 int8_t r[8]; } test_vec[] = { { { INT8_C( 43), -INT8_C( 44), -INT8_C( 14), -INT8_C( 19), INT8_C( 84), INT8_C( 72), INT8_C( 125), INT8_C( 94) }, { { INT8_C( 106), -INT8_C( 98), INT8_C( 24), -INT8_C( 9), -INT8_C( 40), INT8_C( 36), -INT8_C( 25), INT8_C( 3) }, { INT8_C( 113), INT8_C( 40), -INT8_C( 48), -INT8_C( 2), -INT8_C( 25), -INT8_C( 61), INT8_C( 90), -INT8_C( 92) } }, { INT8_C( 13), INT8_C( 8), INT8_C( 0), INT8_C( 9), INT8_C( 7), INT8_C( 3), INT8_C( 5), INT8_C( 2) }, { -INT8_C( 61), INT8_C( 113), INT8_C( 106), INT8_C( 40), INT8_C( 3), -INT8_C( 9), INT8_C( 36), INT8_C( 24) } }, { { INT8_C( 75), -INT8_C( 61), -INT8_C( 95), INT8_C( 35), -INT8_C( 25), -INT8_C( 120), INT8_C( 38), INT8_C( 89) }, { { -INT8_C( 80), -INT8_C( 9), INT8_C( 87), -INT8_C( 105), -INT8_C( 70), -INT8_C( 79), INT8_C( 59), -INT8_C( 57) }, { -INT8_C( 103), -INT8_C( 21), -INT8_C( 111), -INT8_C( 80), INT8_C( 15), -INT8_C( 106), -INT8_C( 14), INT8_C( 7) } }, { INT8_C( 14), INT8_C( 33), INT8_C( 3), INT8_C( 14), -INT8_C( 50), INT8_C( 14), INT8_C( 8), INT8_C( 25) }, { -INT8_C( 14), -INT8_C( 61), -INT8_C( 105), -INT8_C( 14), -INT8_C( 25), -INT8_C( 14), -INT8_C( 103), INT8_C( 89) } }, { { INT8_C( 90), INT8_C( 89), -INT8_C( 22), INT8_C( 20), INT8_C( 11), INT8_C( 37), -INT8_C( 37), -INT8_C( 92) }, { { INT8_C( 17), INT8_C( 108), INT8_C( 85), INT8_C( 32), INT8_C( 3), INT8_C( 71), INT8_C( 39), -INT8_C( 111) }, { INT8_C( 105), INT8_C( 122), INT8_C( 96), INT8_C( 55), INT8_C( 121), -INT8_C( 40), INT8_C( 80), INT8_C( 58) } }, { INT8_C( 2), INT8_C( 12), INT8_C( 3), INT8_C( 4), INT8_C( 15), INT8_C( 5), INT8_C( 6), INT8_C( 73) }, { INT8_C( 85), INT8_C( 121), INT8_C( 32), INT8_C( 3), INT8_C( 58), INT8_C( 71), INT8_C( 39), -INT8_C( 92) } }, { { -INT8_C( 91), INT8_C( 67), INT8_C( 39), -INT8_C( 88), -INT8_C( 117), INT8_C( 78), INT8_C( 58), -INT8_C( 12) }, { { -INT8_C( 56), -INT8_C( 102), INT8_C( 43), INT8_C( 65), INT8_C( 114), INT8_C( 123), INT8_C( 124), INT8_C( 100) }, { INT8_C( 7), INT8_C( 95), -INT8_C( 8), -INT8_C( 9), INT8_C( 69), -INT8_C( 33), INT8_C( 64), -INT8_C( 124) } }, { INT8_C( 15), INT8_C( 14), INT8_C( 14), INT8_C( 5), -INT8_C( 41), INT8_C( 12), INT8_C( 12), INT8_C( 124) }, { -INT8_C( 124), INT8_C( 64), INT8_C( 64), INT8_C( 123), -INT8_C( 117), INT8_C( 69), INT8_C( 69), -INT8_C( 12) } }, { { -INT8_C( 7), -INT8_C( 86), INT8_C( 43), INT8_C( 107), INT8_C( 37), -INT8_C( 89), -INT8_C( 48), INT8_C( 44) }, { { INT8_C( 7), -INT8_C( 56), INT8_C( 35), INT8_C( 76), -INT8_C( 89), INT8_C( 100), -INT8_C( 48), INT8_C( 87) }, { INT8_C( 2), -INT8_C( 98), -INT8_C( 4), -INT8_C( 39), INT8_C( 90), -INT8_C( 87), INT8_C( 85), INT8_C( 90) } }, { INT8_C( 124), INT8_C( 10), -INT8_C( 27), INT8_C( 14), INT8_C( 9), INT8_C( 4), INT8_C( 8), INT8_C( 2) }, { -INT8_C( 7), -INT8_C( 4), INT8_C( 43), INT8_C( 85), -INT8_C( 98), -INT8_C( 89), INT8_C( 2), INT8_C( 35) } }, { { -INT8_C( 42), -INT8_C( 125), -INT8_C( 82), INT8_C( 126), -INT8_C( 25), INT8_C( 126), -INT8_C( 43), -INT8_C( 23) }, { { INT8_C( 28), -INT8_C( 47), -INT8_C( 62), INT8_C( 118), INT8_C( 122), INT8_C( 24), -INT8_C( 47), -INT8_C( 9) }, { -INT8_C( 110), -INT8_C( 74), -INT8_C( 107), INT8_C( 108), INT8_C( 27), INT8_C( 29), INT8_C( 62), INT8_C( 41) } }, { INT8_C( 0), INT8_C( 12), INT8_C( 13), INT8_C( 11), -INT8_C( 118), INT8_C( 13), INT8_C( 13), INT8_C( 1) }, { INT8_C( 28), INT8_C( 27), INT8_C( 29), INT8_C( 108), -INT8_C( 25), INT8_C( 29), INT8_C( 29), -INT8_C( 47) } }, { { -INT8_C( 123), -INT8_C( 44), INT8_C( 76), INT8_C( 0), -INT8_C( 20), INT8_C( 29), -INT8_C( 9), INT8_C( 126) }, { { -INT8_C( 45), -INT8_C( 116), -INT8_C( 22), -INT8_C( 18), -INT8_C( 87), INT8_C( 41), INT8_C( 24), INT8_C( 121) }, { -INT8_C( 91), INT8_C( 117), -INT8_C( 91), INT8_C( 48), INT8_C( 50), INT8_C( 50), -INT8_C( 111), INT8_C( 114) } }, { INT8_C( 110), INT8_C( 112), -INT8_C( 102), INT8_C( 7), INT8_C( 4), INT8_C( 12), INT8_C( 13), INT8_C( 9) }, { -INT8_C( 123), -INT8_C( 44), INT8_C( 76), INT8_C( 121), -INT8_C( 87), INT8_C( 50), INT8_C( 50), INT8_C( 117) } }, { { INT8_C( 44), -INT8_C( 43), INT8_C( 40), -INT8_C( 43), -INT8_C( 2), INT8_C( 64), INT8_C( 79), -INT8_C( 93) }, { { -INT8_C( 75), -INT8_C( 12), -INT8_C( 45), -INT8_C( 25), INT8_C( 38), INT8_C( 100), INT8_C( 89), -INT8_C( 108) }, { -INT8_C( 44), -INT8_C( 12), -INT8_C( 68), -INT8_C( 8), -INT8_C( 96), -INT8_C( 71), -INT8_C( 94), INT8_C( 32) } }, { INT8_C( 2), INT8_C( 11), INT8_C( 12), INT8_C( 8), -INT8_C( 20), INT8_C( 6), INT8_C( 1), INT8_C( 8) }, { -INT8_C( 45), -INT8_C( 8), -INT8_C( 96), -INT8_C( 44), -INT8_C( 2), INT8_C( 89), -INT8_C( 12), -INT8_C( 44) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x8_t a, c, r; simde_int8x8x2_t b; a = simde_vld1_s8(test_vec[i].a); b.val[0] = simde_vld1_s8(test_vec[i].b[0]); b.val[1] = simde_vld1_s8(test_vec[i].b[1]); c = simde_vld1_s8(test_vec[i].c); r = simde_vtbx2_s8(a, b, c); simde_test_arm_neon_assert_equal_i8x8(r, simde_vld1_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x8_t a = simde_test_arm_neon_random_i8x8(); simde_int8x8x2_t b = simde_test_arm_neon_random_i8x8x2(); simde_int8x8_private c_ = simde_int8x8_to_private(simde_test_arm_neon_random_i8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 15; } } simde_int8x8_t c = simde_int8x8_from_private(c_); simde_int8x8_t r = simde_vtbx2_s8(a, b, c); simde_test_arm_neon_write_i8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x8x2(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx2_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 uint8_t a[8]; SIMDE_ALIGN_TO_16 uint8_t b[2][8]; SIMDE_ALIGN_TO_16 uint8_t c[8]; SIMDE_ALIGN_TO_16 uint8_t r[8]; } test_vec[] = { { { UINT8_C(243), UINT8_C(177), UINT8_C( 55), UINT8_C( 17), UINT8_C(166), UINT8_C(193), UINT8_C(205), UINT8_C( 24) }, { { UINT8_C(241), UINT8_C(110), UINT8_C( 3), UINT8_C(203), UINT8_C( 42), UINT8_C(156), UINT8_C( 41), UINT8_C( 49) }, { UINT8_C(205), UINT8_C( 78), UINT8_C( 20), UINT8_C( 3), UINT8_C(123), UINT8_C(104), UINT8_C(193), UINT8_C( 77) } }, { UINT8_C( 12), UINT8_C( 0), UINT8_C(230), UINT8_C( 7), UINT8_C( 2), UINT8_C( 8), UINT8_C( 14), UINT8_C( 6) }, { UINT8_C(123), UINT8_C(241), UINT8_C( 55), UINT8_C( 49), UINT8_C( 3), UINT8_C(205), UINT8_C(193), UINT8_C( 41) } }, { { UINT8_C(130), UINT8_C( 43), UINT8_C( 82), UINT8_C(172), UINT8_C(199), UINT8_C(123), UINT8_C(222), UINT8_C(148) }, { { UINT8_C(201), UINT8_C(242), UINT8_C(151), UINT8_C( 68), UINT8_C( 90), UINT8_C( 88), UINT8_C(145), UINT8_C( 22) }, { UINT8_C(168), UINT8_C(119), UINT8_C(190), UINT8_C(235), UINT8_C( 48), UINT8_C( 92), UINT8_C( 33), UINT8_C(154) } }, { UINT8_C( 1), UINT8_C( 8), UINT8_C( 10), UINT8_C( 7), UINT8_C( 12), UINT8_C(210), UINT8_C( 14), UINT8_C( 14) }, { UINT8_C(242), UINT8_C(168), UINT8_C(190), UINT8_C( 22), UINT8_C( 48), UINT8_C(123), UINT8_C( 33), UINT8_C( 33) } }, { { UINT8_C(123), UINT8_C(240), UINT8_C( 40), UINT8_C(213), UINT8_C( 72), UINT8_C(186), UINT8_C(236), UINT8_C(241) }, { { UINT8_C( 49), UINT8_C(170), UINT8_C(220), UINT8_C( 97), UINT8_C( 6), UINT8_C(253), UINT8_C(251), UINT8_C( 55) }, { UINT8_C(101), UINT8_C(165), UINT8_C(254), UINT8_C(225), UINT8_C(119), UINT8_C( 76), UINT8_C(223), UINT8_C(116) } }, { UINT8_C( 12), UINT8_C( 10), UINT8_C( 8), UINT8_C( 7), UINT8_C( 19), UINT8_C(145), UINT8_C(235), UINT8_C(142) }, { UINT8_C(119), UINT8_C(254), UINT8_C(101), UINT8_C( 55), UINT8_C( 72), UINT8_C(186), UINT8_C(236), UINT8_C(241) } }, { { UINT8_C(250), UINT8_C(150), UINT8_C( 96), UINT8_C( 0), UINT8_C(147), UINT8_C( 92), UINT8_C( 55), UINT8_C(248) }, { { UINT8_C( 1), UINT8_C( 53), UINT8_C(217), UINT8_C(121), UINT8_C(129), UINT8_C(185), UINT8_C(237), UINT8_C(109) }, { UINT8_C( 67), UINT8_C( 38), UINT8_C(116), UINT8_C( 87), UINT8_C(183), UINT8_C( 95), UINT8_C(229), UINT8_C( 56) } }, { UINT8_C( 2), UINT8_C( 9), UINT8_C( 1), UINT8_C( 0), UINT8_C( 9), UINT8_C( 12), UINT8_C( 15), UINT8_C( 3) }, { UINT8_C(217), UINT8_C( 38), UINT8_C( 53), UINT8_C( 1), UINT8_C( 38), UINT8_C(183), UINT8_C( 56), UINT8_C(121) } }, { { UINT8_MAX, UINT8_C(184), UINT8_C(118), UINT8_C(128), UINT8_C(113), UINT8_C( 99), UINT8_C(237), UINT8_C(180) }, { { UINT8_C(137), UINT8_C( 97), UINT8_C( 11), UINT8_C( 64), UINT8_C(192), UINT8_C(241), UINT8_C(120), UINT8_C( 51) }, { UINT8_C( 58), UINT8_C(122), UINT8_C(115), UINT8_C(212), UINT8_C( 54), UINT8_C(178), UINT8_C(103), UINT8_C(136) } }, { UINT8_C( 1), UINT8_C( 11), UINT8_C( 14), UINT8_C( 77), UINT8_C( 5), UINT8_C( 13), UINT8_C( 74), UINT8_C( 5) }, { UINT8_C( 97), UINT8_C(212), UINT8_C(103), UINT8_C(128), UINT8_C(241), UINT8_C(178), UINT8_C(237), UINT8_C(241) } }, { { UINT8_C(148), UINT8_C( 54), UINT8_C(237), UINT8_C( 85), UINT8_C( 39), UINT8_C(102), UINT8_C(136), UINT8_C( 97) }, { { UINT8_C(224), UINT8_C(251), UINT8_C( 53), UINT8_C( 22), UINT8_C(173), UINT8_C(157), UINT8_C(158), UINT8_C(254) }, { UINT8_C(152), UINT8_C( 13), UINT8_C( 75), UINT8_C( 93), UINT8_C( 90), UINT8_C(149), UINT8_C( 34), UINT8_C( 95) } }, { UINT8_C( 85), UINT8_C( 8), UINT8_C( 5), UINT8_C(121), UINT8_C( 11), UINT8_C( 15), UINT8_C( 38), UINT8_C( 15) }, { UINT8_C(148), UINT8_C(152), UINT8_C(157), UINT8_C( 85), UINT8_C( 93), UINT8_C( 95), UINT8_C(136), UINT8_C( 95) } }, { { UINT8_C( 7), UINT8_C(243), UINT8_C(111), UINT8_C(180), UINT8_C(144), UINT8_C( 14), UINT8_C(179), UINT8_C( 40) }, { { UINT8_C( 27), UINT8_C(254), UINT8_C(134), UINT8_C(117), UINT8_C(148), UINT8_C(168), UINT8_C(212), UINT8_C(233) }, { UINT8_C( 16), UINT8_C(169), UINT8_C( 98), UINT8_C(171), UINT8_C(168), UINT8_C(136), UINT8_C(219), UINT8_C(222) } }, { UINT8_C( 12), UINT8_C( 15), UINT8_C( 10), UINT8_C( 5), UINT8_C( 12), UINT8_C( 8), UINT8_C( 15), UINT8_C( 3) }, { UINT8_C(168), UINT8_C(222), UINT8_C( 98), UINT8_C(168), UINT8_C(168), UINT8_C( 16), UINT8_C(222), UINT8_C(117) } }, { { UINT8_C(217), UINT8_C( 43), UINT8_C(124), UINT8_C(109), UINT8_C(211), UINT8_C( 80), UINT8_C( 87), UINT8_C(228) }, { { UINT8_C(249), UINT8_C(185), UINT8_C(143), UINT8_C(162), UINT8_C( 66), UINT8_C(106), UINT8_C(128), UINT8_C(222) }, { UINT8_C(202), UINT8_C(186), UINT8_C(243), UINT8_C( 54), UINT8_C(179), UINT8_C( 98), UINT8_C(169), UINT8_C(159) } }, { UINT8_C( 1), UINT8_C( 1), UINT8_C( 11), UINT8_C( 13), UINT8_C( 12), UINT8_C( 0), UINT8_C( 53), UINT8_C(134) }, { UINT8_C(185), UINT8_C(185), UINT8_C( 54), UINT8_C( 98), UINT8_C(179), UINT8_C(249), UINT8_C( 87), UINT8_C(228) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x8_t a, c, r; simde_uint8x8x2_t b; a = simde_vld1_u8(test_vec[i].a); b.val[0] = simde_vld1_u8(test_vec[i].b[0]); b.val[1] = simde_vld1_u8(test_vec[i].b[1]); c = simde_vld1_u8(test_vec[i].c); r = simde_vtbx2_u8(a, b, c); simde_test_arm_neon_assert_equal_u8x8(r, simde_vld1_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x8_t a = simde_test_arm_neon_random_u8x8(); simde_uint8x8x2_t b = simde_test_arm_neon_random_u8x8x2(); simde_uint8x8_private c_ = simde_uint8x8_to_private(simde_test_arm_neon_random_u8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 15; } } simde_uint8x8_t c = simde_uint8x8_from_private(c_); simde_uint8x8_t r = simde_vtbx2_u8(a, b, c); simde_test_arm_neon_write_u8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x8x2(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx3_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 int8_t a[8]; SIMDE_ALIGN_TO_16 int8_t b[3][8]; SIMDE_ALIGN_TO_16 int8_t c[8]; SIMDE_ALIGN_TO_16 int8_t r[8]; } test_vec[] = { { { -INT8_C( 119), -INT8_C( 54), -INT8_C( 9), -INT8_C( 83), -INT8_C( 77), INT8_C( 35), -INT8_C( 42), INT8_C( 12) }, { { INT8_C( 101), -INT8_C( 93), INT8_C( 97), -INT8_C( 22), INT8_C( 120), -INT8_C( 98), -INT8_C( 56), INT8_C( 75) }, { -INT8_C( 122), INT8_C( 27), -INT8_C( 103), -INT8_C( 64), -INT8_C( 41), INT8_C( 6), INT8_C( 109), -INT8_C( 56) }, { INT8_C( 13), INT8_C( 42), -INT8_C( 24), INT8_C( 48), -INT8_C( 33), -INT8_C( 106), -INT8_C( 21), INT8_C( 104) } }, { INT8_C( 97), -INT8_C( 29), INT8_C( 21), INT8_C( 20), INT8_C( 6), INT8_C( 19), INT8_C( 8), INT8_C( 11) }, { -INT8_C( 119), -INT8_C( 54), -INT8_C( 106), -INT8_C( 33), -INT8_C( 56), INT8_C( 48), -INT8_C( 122), -INT8_C( 64) } }, { { INT8_C( 57), -INT8_C( 20), INT8_C( 103), INT8_C( 16), -INT8_C( 14), -INT8_C( 44), -INT8_C( 40), -INT8_C( 1) }, { { -INT8_C( 2), -INT8_C( 63), INT8_C( 48), -INT8_C( 34), INT8_C( 87), INT8_C( 27), INT8_C( 70), -INT8_C( 72) }, { -INT8_C( 2), INT8_C( 92), -INT8_C( 52), INT8_C( 4), INT8_C( 71), -INT8_C( 19), INT8_C( 111), -INT8_C( 42) }, { INT8_C( 111), -INT8_C( 59), -INT8_C( 35), -INT8_C( 113), -INT8_C( 29), INT8_C( 48), INT8_C( 53), INT8_C( 28) } }, { INT8_C( 28), INT8_C( 12), INT8_C( 20), INT8_C( 14), INT8_C( 16), INT8_C( 5), INT8_C( 14), INT8_C( 15) }, { INT8_C( 57), INT8_C( 71), -INT8_C( 29), INT8_C( 111), INT8_C( 111), INT8_C( 27), INT8_C( 111), -INT8_C( 42) } }, { { -INT8_C( 17), -INT8_C( 94), INT8_C( 92), INT8_C( 55), -INT8_C( 113), -INT8_C( 52), INT8_C( 13), -INT8_C( 2) }, { { -INT8_C( 111), -INT8_C( 21), -INT8_C( 115), INT8_C( 116), INT8_C( 27), -INT8_C( 61), -INT8_C( 112), INT8_C( 55) }, { INT8_C( 95), -INT8_C( 68), INT8_C( 69), -INT8_C( 48), -INT8_C( 63), INT8_C( 83), INT8_C( 63), -INT8_C( 121) }, { -INT8_C( 111), -INT8_C( 116), -INT8_C( 91), -INT8_C( 21), INT8_C( 31), INT8_C( 123), INT8_C( 67), INT8_C( 15) } }, { INT8_C( 29), INT8_C( 15), INT8_C( 22), INT8_C( 5), INT8_C( 107), INT8_C( 11), INT8_C( 3), INT8_C( 12) }, { -INT8_C( 17), -INT8_C( 121), INT8_C( 67), -INT8_C( 61), -INT8_C( 113), -INT8_C( 48), INT8_C( 116), -INT8_C( 63) } }, { { -INT8_C( 67), -INT8_C( 42), INT8_C( 43), INT8_C( 126), INT8_C( 41), INT8_C( 106), INT8_C( 6), -INT8_C( 69) }, { { -INT8_C( 10), -INT8_C( 85), -INT8_C( 90), INT8_C( 22), INT8_C( 38), -INT8_C( 23), INT8_C( 37), INT8_C( 67) }, { -INT8_C( 120), INT8_C( 107), -INT8_C( 16), -INT8_C( 12), -INT8_C( 66), -INT8_C( 100), -INT8_C( 16), -INT8_C( 3) }, { -INT8_C( 43), INT8_C( 97), INT8_C( 86), -INT8_C( 47), INT8_C( 97), -INT8_C( 25), INT8_C( 44), INT8_C( 30) } }, { -INT8_C( 67), INT8_C( 16), INT8_C( 13), INT8_C( 14), INT8_C( 2), INT8_C( 19), INT8_C( 17), -INT8_C( 71) }, { -INT8_C( 67), -INT8_C( 43), -INT8_C( 100), -INT8_C( 16), -INT8_C( 90), -INT8_C( 47), INT8_C( 97), -INT8_C( 69) } }, { { INT8_C( 95), -INT8_C( 88), -INT8_C( 83), INT8_C( 29), INT8_C( 68), -INT8_C( 99), INT8_C( 26), INT8_C( 25) }, { { -INT8_C( 2), INT8_C( 113), -INT8_C( 22), INT8_C( 96), INT8_C( 88), INT8_C( 22), INT8_C( 126), INT8_C( 21) }, { INT8_C( 110), INT8_C( 27), -INT8_C( 5), INT8_C( 49), -INT8_C( 66), -INT8_C( 99), -INT8_C( 22), INT8_C( 12) }, { -INT8_C( 28), -INT8_C( 71), INT8_MIN, INT8_C( 21), -INT8_C( 83), INT8_C( 56), -INT8_C( 50), INT8_C( 12) } }, { INT8_C( 8), INT8_C( 3), INT8_C( 17), INT8_C( 12), INT8_C( 0), INT8_C( 20), INT8_C( 13), INT8_C( 23) }, { INT8_C( 110), INT8_C( 96), -INT8_C( 71), -INT8_C( 66), -INT8_C( 2), -INT8_C( 83), -INT8_C( 99), INT8_C( 12) } }, { { INT8_C( 17), INT8_C( 29), -INT8_C( 35), -INT8_C( 49), -INT8_C( 70), -INT8_C( 57), -INT8_C( 36), -INT8_C( 97) }, { { INT8_MIN, INT8_C( 92), -INT8_C( 76), INT8_C( 45), -INT8_C( 108), -INT8_C( 126), INT8_C( 57), INT8_C( 116) }, { -INT8_C( 3), INT8_C( 98), -INT8_C( 104), INT8_C( 21), -INT8_C( 90), -INT8_C( 43), INT8_C( 44), INT8_C( 91) }, { -INT8_C( 4), -INT8_C( 93), INT8_C( 104), INT8_C( 58), -INT8_C( 103), -INT8_C( 118), -INT8_C( 26), -INT8_C( 86) } }, { INT8_C( 0), INT8_C( 3), INT8_C( 1), INT8_C( 2), INT8_C( 18), INT8_C( 85), INT8_C( 1), INT8_C( 10) }, { INT8_MIN, INT8_C( 45), INT8_C( 92), -INT8_C( 76), INT8_C( 104), -INT8_C( 57), INT8_C( 92), -INT8_C( 104) } }, { { -INT8_C( 46), INT8_C( 83), INT8_C( 74), INT8_C( 121), INT8_C( 41), INT8_C( 118), -INT8_C( 44), INT8_C( 37) }, { { INT8_C( 26), INT8_C( 61), INT8_C( 95), -INT8_C( 77), -INT8_C( 57), INT8_C( 69), INT8_C( 93), INT8_C( 111) }, { INT8_C( 8), -INT8_C( 42), -INT8_C( 46), -INT8_C( 110), INT8_C( 44), -INT8_C( 45), -INT8_C( 100), -INT8_C( 34) }, { -INT8_C( 119), -INT8_C( 45), INT8_C( 36), -INT8_C( 64), INT8_C( 67), -INT8_C( 33), -INT8_C( 11), INT8_C( 22) } }, { INT8_C( 3), INT8_C( 15), INT8_C( 23), INT8_C( 92), INT8_C( 13), INT8_C( 3), INT8_C( 9), -INT8_C( 49) }, { -INT8_C( 77), -INT8_C( 34), INT8_C( 22), INT8_C( 121), -INT8_C( 45), -INT8_C( 77), -INT8_C( 42), INT8_C( 37) } }, { { -INT8_C( 74), -INT8_C( 87), -INT8_C( 63), -INT8_C( 30), INT8_C( 125), INT8_C( 94), -INT8_C( 64), INT8_C( 6) }, { { INT8_C( 49), -INT8_C( 28), -INT8_C( 58), INT8_C( 117), -INT8_C( 60), -INT8_C( 69), -INT8_C( 117), -INT8_C( 9) }, { -INT8_C( 6), INT8_C( 26), INT8_C( 83), -INT8_C( 80), INT8_C( 125), -INT8_C( 44), INT8_MAX, INT8_C( 30) }, { -INT8_C( 75), INT8_C( 2), -INT8_C( 122), -INT8_C( 36), -INT8_C( 31), INT8_C( 93), INT8_C( 11), -INT8_C( 105) } }, { INT8_C( 7), INT8_C( 12), INT8_C( 1), -INT8_C( 124), INT8_C( 18), INT8_C( 9), INT8_C( 18), INT8_C( 20) }, { -INT8_C( 9), INT8_C( 125), -INT8_C( 28), -INT8_C( 30), -INT8_C( 122), INT8_C( 26), -INT8_C( 122), -INT8_C( 31) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x8_t a, c, r; simde_int8x8x3_t b; a = simde_vld1_s8(test_vec[i].a); b.val[0] = simde_vld1_s8(test_vec[i].b[0]); b.val[1] = simde_vld1_s8(test_vec[i].b[1]); b.val[2] = simde_vld1_s8(test_vec[i].b[2]); c = simde_vld1_s8(test_vec[i].c); r = simde_vtbx3_s8(a, b, c); simde_test_arm_neon_assert_equal_i8x8(r, simde_vld1_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x8_t a = simde_test_arm_neon_random_i8x8(); simde_int8x8x3_t b = simde_test_arm_neon_random_i8x8x3(); simde_int8x8_private c_ = simde_int8x8_to_private(simde_test_arm_neon_random_i8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] = HEDLEY_STATIC_CAST(int8_t, HEDLEY_STATIC_CAST(uint8_t, c_.values[j]) % 24); } } simde_int8x8_t c = simde_int8x8_from_private(c_); simde_int8x8_t r = simde_vtbx3_s8(a, b, c); simde_test_arm_neon_write_i8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x8x3(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx3_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 uint8_t a[8]; SIMDE_ALIGN_TO_16 uint8_t b[3][8]; SIMDE_ALIGN_TO_16 uint8_t c[8]; SIMDE_ALIGN_TO_16 uint8_t r[8]; } test_vec[] = { { { UINT8_C( 32), UINT8_C(243), UINT8_C(142), UINT8_C( 4), UINT8_C( 43), UINT8_C(102), UINT8_C(233), UINT8_C( 31) }, { { UINT8_C(210), UINT8_C(176), UINT8_C(234), UINT8_C(207), UINT8_C( 39), UINT8_C(178), UINT8_C( 37), UINT8_C(233) }, { UINT8_C(129), UINT8_C(164), UINT8_C(149), UINT8_C(232), UINT8_C(245), UINT8_C(178), UINT8_C( 90), UINT8_C( 42) }, { UINT8_C(189), UINT8_C(140), UINT8_C(136), UINT8_C( 81), UINT8_C(218), UINT8_C(117), UINT8_C(123), UINT8_C(251) } }, { UINT8_C( 8), UINT8_C( 10), UINT8_C( 15), UINT8_C( 4), UINT8_C( 16), UINT8_C(232), UINT8_C( 11), UINT8_C( 19) }, { UINT8_C(129), UINT8_C(149), UINT8_C( 42), UINT8_C( 39), UINT8_C(189), UINT8_C(102), UINT8_C(232), UINT8_C( 81) } }, { { UINT8_C(219), UINT8_C( 62), UINT8_C(185), UINT8_C(208), UINT8_C(241), UINT8_C( 19), UINT8_C(251), UINT8_C(174) }, { { UINT8_C(159), UINT8_C(131), UINT8_MAX, UINT8_C(122), UINT8_C(248), UINT8_C(123), UINT8_C(117), UINT8_C( 97) }, { UINT8_C(133), UINT8_C(116), UINT8_C(245), UINT8_C(245), UINT8_C( 93), UINT8_C(168), UINT8_C( 56), UINT8_C(245) }, { UINT8_C( 69), UINT8_C( 75), UINT8_C(181), UINT8_C(149), UINT8_C(130), UINT8_C( 94), UINT8_C(102), UINT8_C( 94) } }, { UINT8_C(156), UINT8_C( 7), UINT8_C( 46), UINT8_C( 21), UINT8_C( 2), UINT8_C( 17), UINT8_C( 12), UINT8_C( 18) }, { UINT8_C(219), UINT8_C( 97), UINT8_C(185), UINT8_C( 94), UINT8_MAX, UINT8_C( 75), UINT8_C( 93), UINT8_C(181) } }, { { UINT8_C( 53), UINT8_C(251), UINT8_C( 49), UINT8_C(146), UINT8_C(163), UINT8_C(105), UINT8_C(136), UINT8_C(233) }, { { UINT8_C(180), UINT8_C( 61), UINT8_C(126), UINT8_C( 55), UINT8_C(155), UINT8_C(228), UINT8_C(149), UINT8_C( 55) }, { UINT8_C( 3), UINT8_C(195), UINT8_C(197), UINT8_C( 53), UINT8_C(237), UINT8_C( 1), UINT8_C( 7), UINT8_C(154) }, { UINT8_C( 60), UINT8_C( 83), UINT8_C( 63), UINT8_C(243), UINT8_C( 20), UINT8_C( 70), UINT8_C( 46), UINT8_C( 74) } }, { UINT8_C( 17), UINT8_C( 23), UINT8_C( 4), UINT8_C( 13), UINT8_C( 9), UINT8_C( 4), UINT8_C( 14), UINT8_C(125) }, { UINT8_C( 83), UINT8_C( 74), UINT8_C(155), UINT8_C( 1), UINT8_C(195), UINT8_C(155), UINT8_C( 7), UINT8_C(233) } }, { { UINT8_C( 13), UINT8_C( 57), UINT8_C(104), UINT8_C(250), UINT8_C( 58), UINT8_C(112), UINT8_C(148), UINT8_C(118) }, { { UINT8_C(195), UINT8_C(211), UINT8_C(105), UINT8_C(216), UINT8_C( 25), UINT8_C(152), UINT8_C( 34), UINT8_C( 91) }, { UINT8_C(247), UINT8_C(254), UINT8_C( 64), UINT8_C(192), UINT8_C( 99), UINT8_C( 14), UINT8_C( 62), UINT8_C( 4) }, { UINT8_C( 90), UINT8_C(242), UINT8_C( 65), UINT8_C(138), UINT8_C( 60), UINT8_C(181), UINT8_C(189), UINT8_C( 73) } }, { UINT8_C( 22), UINT8_C( 13), UINT8_C( 19), UINT8_C( 16), UINT8_C(149), UINT8_C( 23), UINT8_C( 14), UINT8_C( 17) }, { UINT8_C(189), UINT8_C( 14), UINT8_C(138), UINT8_C( 90), UINT8_C( 58), UINT8_C( 73), UINT8_C( 62), UINT8_C(242) } }, { { UINT8_C( 81), UINT8_C( 95), UINT8_C( 88), UINT8_C(180), UINT8_C(109), UINT8_C(150), UINT8_C(185), UINT8_C(199) }, { { UINT8_C(136), UINT8_C(250), UINT8_C( 81), UINT8_C(196), UINT8_C(175), UINT8_C( 14), UINT8_C( 13), UINT8_C(157) }, { UINT8_C( 51), UINT8_C( 80), UINT8_C(197), UINT8_C(201), UINT8_C( 39), UINT8_C( 99), UINT8_C( 34), UINT8_C(210) }, { UINT8_C(107), UINT8_C( 83), UINT8_C(150), UINT8_C( 11), UINT8_C(166), UINT8_C(181), UINT8_C(163), UINT8_C(247) } }, { UINT8_C( 20), UINT8_C( 11), UINT8_C( 4), UINT8_C( 9), UINT8_C( 1), UINT8_C( 5), UINT8_C( 0), UINT8_C( 1) }, { UINT8_C(166), UINT8_C(201), UINT8_C(175), UINT8_C( 80), UINT8_C(250), UINT8_C( 14), UINT8_C(136), UINT8_C(250) } }, { { UINT8_C( 60), UINT8_C(112), UINT8_C(163), UINT8_C( 99), UINT8_C(211), UINT8_C(197), UINT8_C( 53), UINT8_C( 63) }, { { UINT8_C( 24), UINT8_C(203), UINT8_C( 74), UINT8_C(190), UINT8_C(128), UINT8_C(237), UINT8_C(182), UINT8_C(148) }, { UINT8_C(232), UINT8_C( 98), UINT8_C( 21), UINT8_C(121), UINT8_C(199), UINT8_C( 93), UINT8_C(147), UINT8_C( 38) }, { UINT8_C(246), UINT8_C(113), UINT8_C( 52), UINT8_C(157), UINT8_C( 92), UINT8_C(223), UINT8_C(120), UINT8_C(152) } }, { UINT8_C( 7), UINT8_C( 3), UINT8_C( 12), UINT8_C( 10), UINT8_C( 9), UINT8_C( 1), UINT8_C( 1), UINT8_C( 9) }, { UINT8_C(148), UINT8_C(190), UINT8_C(199), UINT8_C( 21), UINT8_C( 98), UINT8_C(203), UINT8_C(203), UINT8_C( 98) } }, { { UINT8_C(208), UINT8_C( 39), UINT8_C(251), UINT8_C(151), UINT8_C(133), UINT8_C(142), UINT8_C(189), UINT8_C(123) }, { { UINT8_MAX, UINT8_C(241), UINT8_C( 25), UINT8_C( 92), UINT8_C(208), UINT8_C(145), UINT8_C(244), UINT8_C( 31) }, { UINT8_C(172), UINT8_C(240), UINT8_C( 65), UINT8_C(141), UINT8_C( 34), UINT8_C(163), UINT8_C(135), UINT8_C( 31) }, { UINT8_C( 79), UINT8_C( 63), UINT8_C(156), UINT8_C(232), UINT8_C(173), UINT8_C(174), UINT8_C(106), UINT8_C(125) } }, { UINT8_C( 22), UINT8_C( 6), UINT8_C( 20), UINT8_C( 19), UINT8_C( 4), UINT8_C( 17), UINT8_C( 22), UINT8_C( 4) }, { UINT8_C(106), UINT8_C(244), UINT8_C(173), UINT8_C(232), UINT8_C(208), UINT8_C( 63), UINT8_C(106), UINT8_C(208) } }, { { UINT8_C( 53), UINT8_C(242), UINT8_C(186), UINT8_C( 87), UINT8_C(149), UINT8_C( 65), UINT8_C(118), UINT8_C(228) }, { { UINT8_C(128), UINT8_C( 18), UINT8_C(205), UINT8_C( 45), UINT8_C(193), UINT8_C( 55), UINT8_C(170), UINT8_C(151) }, { UINT8_C(157), UINT8_C(190), UINT8_C(242), UINT8_C(146), UINT8_C(143), UINT8_C(200), UINT8_C(134), UINT8_C( 81) }, { UINT8_C(184), UINT8_C(214), UINT8_C(227), UINT8_C( 56), UINT8_C( 26), UINT8_C(148), UINT8_C(101), UINT8_C( 79) } }, { UINT8_C( 15), UINT8_C( 32), UINT8_C( 22), UINT8_C( 4), UINT8_C( 97), UINT8_C( 4), UINT8_C( 1), UINT8_C( 10) }, { UINT8_C( 81), UINT8_C(242), UINT8_C(101), UINT8_C(193), UINT8_C(149), UINT8_C(193), UINT8_C( 18), UINT8_C(242) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x8_t a, c, r; simde_uint8x8x3_t b; a = simde_vld1_u8(test_vec[i].a); b.val[0] = simde_vld1_u8(test_vec[i].b[0]); b.val[1] = simde_vld1_u8(test_vec[i].b[1]); b.val[2] = simde_vld1_u8(test_vec[i].b[2]); c = simde_vld1_u8(test_vec[i].c); r = simde_vtbx3_u8(a, b, c); simde_test_arm_neon_assert_equal_u8x8(r, simde_vld1_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x8_t a = simde_test_arm_neon_random_u8x8(); simde_uint8x8x3_t b = simde_test_arm_neon_random_u8x8x3(); simde_uint8x8_private c_ = simde_uint8x8_to_private(simde_test_arm_neon_random_u8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] %= 24; } } simde_uint8x8_t c = simde_uint8x8_from_private(c_); simde_uint8x8_t r = simde_vtbx3_u8(a, b, c); simde_test_arm_neon_write_u8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x8x3(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx4_s8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 int8_t a[8]; SIMDE_ALIGN_TO_16 int8_t b[4][8]; SIMDE_ALIGN_TO_16 int8_t c[8]; SIMDE_ALIGN_TO_16 int8_t r[8]; } test_vec[] = { { { -INT8_C( 5), INT8_C( 1), INT8_C( 61), -INT8_C( 12), INT8_C( 126), -INT8_C( 85), INT8_C( 88), INT8_C( 104) }, { { INT8_C( 87), -INT8_C( 84), INT8_C( 12), INT8_C( 71), -INT8_C( 6), INT8_C( 22), INT8_C( 6), INT8_C( 106) }, { -INT8_C( 2), INT8_C( 85), INT8_C( 63), -INT8_C( 77), INT8_C( 5), -INT8_C( 22), INT8_C( 81), -INT8_C( 33) }, { -INT8_C( 13), -INT8_C( 70), INT8_C( 54), INT8_C( 26), INT8_C( 35), INT8_C( 67), INT8_C( 109), INT8_C( 30) }, { INT8_C( 68), -INT8_C( 86), INT8_C( 18), -INT8_C( 61), INT8_C( 86), INT8_C( 106), INT8_C( 43), -INT8_C( 83) } }, { INT8_C( 22), INT8_C( 23), INT8_C( 21), INT8_C( 16), INT8_C( 13), INT8_C( 27), INT8_C( 26), INT8_C( 11) }, { INT8_C( 109), INT8_C( 30), INT8_C( 67), -INT8_C( 13), -INT8_C( 22), -INT8_C( 61), INT8_C( 18), -INT8_C( 77) } }, { { INT8_C( 11), INT8_C( 107), -INT8_C( 79), INT8_C( 46), -INT8_C( 82), INT8_C( 31), INT8_C( 76), -INT8_C( 13) }, { { -INT8_C( 55), INT8_C( 94), -INT8_C( 74), INT8_C( 31), -INT8_C( 56), -INT8_C( 31), -INT8_C( 51), -INT8_C( 33) }, { INT8_C( 24), -INT8_C( 62), -INT8_C( 17), INT8_C( 101), -INT8_C( 67), INT8_C( 106), -INT8_C( 80), INT8_C( 14) }, { INT8_C( 36), -INT8_C( 81), INT8_C( 101), -INT8_C( 56), INT8_C( 0), -INT8_C( 102), INT8_C( 95), INT8_C( 11) }, { INT8_C( 6), INT8_C( 16), INT8_C( 57), -INT8_C( 76), INT8_C( 47), -INT8_C( 123), -INT8_C( 89), -INT8_C( 7) } }, { INT8_C( 3), INT8_C( 93), INT8_C( 24), INT8_C( 11), INT8_C( 30), INT8_C( 5), INT8_C( 10), INT8_C( 22) }, { INT8_C( 31), INT8_C( 107), INT8_C( 6), INT8_C( 101), -INT8_C( 89), -INT8_C( 31), -INT8_C( 17), INT8_C( 95) } }, { { INT8_C( 27), -INT8_C( 40), -INT8_C( 48), INT8_C( 27), INT8_C( 115), INT8_C( 47), INT8_C( 38), INT8_C( 121) }, { { INT8_C( 63), INT8_C( 95), INT8_C( 45), INT8_C( 111), -INT8_C( 28), -INT8_C( 43), INT8_C( 104), -INT8_C( 57) }, { INT8_C( 50), INT8_MIN, INT8_C( 115), INT8_C( 113), INT8_C( 102), -INT8_C( 3), -INT8_C( 57), INT8_C( 13) }, { INT8_C( 119), -INT8_C( 125), INT8_C( 114), INT8_C( 91), -INT8_C( 17), -INT8_C( 26), INT8_C( 99), INT8_C( 10) }, { -INT8_C( 66), INT8_C( 51), INT8_C( 38), INT8_C( 49), INT8_C( 98), INT8_C( 76), -INT8_C( 86), -INT8_C( 94) } }, { INT8_C( 12), INT8_C( 24), INT8_C( 17), INT8_C( 16), INT8_C( 13), INT8_C( 25), INT8_C( 24), INT8_C( 31) }, { INT8_C( 102), -INT8_C( 66), -INT8_C( 125), INT8_C( 119), -INT8_C( 3), INT8_C( 51), -INT8_C( 66), -INT8_C( 94) } }, { { -INT8_C( 101), -INT8_C( 33), -INT8_C( 101), -INT8_C( 118), -INT8_C( 59), -INT8_C( 1), -INT8_C( 108), -INT8_C( 124) }, { { INT8_C( 50), -INT8_C( 70), -INT8_C( 75), -INT8_C( 107), INT8_C( 7), INT8_C( 96), INT8_C( 55), -INT8_C( 77) }, { INT8_C( 56), INT8_C( 72), INT8_C( 67), -INT8_C( 27), -INT8_C( 63), -INT8_C( 101), -INT8_C( 60), -INT8_C( 70) }, { INT8_C( 102), INT8_C( 21), INT8_C( 26), INT8_C( 47), INT8_C( 45), -INT8_C( 121), INT8_C( 111), -INT8_C( 56) }, { INT8_C( 102), INT8_C( 10), INT8_C( 82), INT8_C( 44), INT8_C( 9), -INT8_C( 26), -INT8_C( 80), INT8_C( 60) } }, { INT8_C( 1), INT8_C( 5), INT8_C( 17), INT8_C( 8), INT8_C( 5), INT8_C( 8), INT8_C( 27), -INT8_C( 3) }, { -INT8_C( 70), INT8_C( 96), INT8_C( 21), INT8_C( 56), INT8_C( 96), INT8_C( 56), INT8_C( 44), -INT8_C( 124) } }, { { -INT8_C( 68), -INT8_C( 27), -INT8_C( 49), -INT8_C( 23), INT8_C( 108), INT8_C( 62), -INT8_C( 79), -INT8_C( 45) }, { { INT8_C( 73), INT8_C( 3), -INT8_C( 1), INT8_C( 82), -INT8_C( 23), -INT8_C( 81), -INT8_C( 114), -INT8_C( 118) }, { INT8_C( 20), INT8_C( 95), INT8_C( 50), -INT8_C( 38), INT8_C( 103), -INT8_C( 115), -INT8_C( 41), -INT8_C( 73) }, { INT8_C( 44), -INT8_C( 70), -INT8_C( 56), INT8_C( 102), INT8_C( 97), -INT8_C( 108), INT8_C( 6), INT8_C( 29) }, { INT8_C( 121), -INT8_C( 42), INT8_C( 6), -INT8_C( 26), INT8_C( 20), -INT8_C( 73), -INT8_C( 71), INT8_C( 93) } }, { INT8_C( 26), -INT8_C( 72), INT8_C( 16), INT8_C( 3), INT8_C( 7), INT8_C( 30), INT8_C( 14), INT8_C( 27) }, { INT8_C( 6), -INT8_C( 27), INT8_C( 44), INT8_C( 82), -INT8_C( 118), -INT8_C( 71), -INT8_C( 41), -INT8_C( 26) } }, { { -INT8_C( 25), -INT8_C( 123), INT8_MIN, INT8_C( 72), INT8_C( 25), -INT8_C( 122), INT8_C( 101), -INT8_C( 109) }, { { INT8_C( 92), INT8_C( 107), INT8_C( 121), INT8_C( 113), INT8_C( 34), INT8_C( 50), -INT8_C( 50), -INT8_C( 36) }, { -INT8_C( 22), INT8_C( 126), INT8_MAX, INT8_C( 81), -INT8_C( 67), -INT8_C( 83), -INT8_C( 52), INT8_C( 91) }, { INT8_C( 14), INT8_C( 34), INT8_C( 96), -INT8_C( 4), INT8_C( 79), INT8_C( 29), INT8_C( 22), INT8_C( 54) }, { -INT8_C( 93), -INT8_C( 106), INT8_C( 126), -INT8_C( 68), INT8_C( 28), -INT8_C( 29), INT8_C( 79), INT8_C( 121) } }, { INT8_C( 14), -INT8_C( 56), INT8_C( 10), INT8_C( 16), INT8_C( 26), -INT8_C( 72), INT8_C( 76), INT8_C( 4) }, { -INT8_C( 52), -INT8_C( 123), INT8_MAX, INT8_C( 14), INT8_C( 126), -INT8_C( 122), INT8_C( 101), INT8_C( 34) } }, { { INT8_C( 36), -INT8_C( 81), -INT8_C( 125), INT8_C( 115), -INT8_C( 51), -INT8_C( 103), -INT8_C( 87), INT8_C( 112) }, { { INT8_C( 47), INT8_C( 39), INT8_C( 44), INT8_C( 75), INT8_C( 10), INT8_C( 124), -INT8_C( 60), INT8_C( 88) }, { INT8_C( 68), -INT8_C( 82), -INT8_C( 56), INT8_C( 63), INT8_C( 103), INT8_C( 20), INT8_C( 35), -INT8_C( 98) }, { -INT8_C( 33), INT8_C( 89), -INT8_C( 110), INT8_C( 88), INT8_C( 91), -INT8_C( 31), -INT8_C( 33), INT8_MAX }, { -INT8_C( 112), INT8_C( 98), -INT8_C( 14), INT8_C( 93), -INT8_C( 5), -INT8_C( 101), -INT8_C( 51), INT8_C( 42) } }, { INT8_C( 2), -INT8_C( 6), INT8_C( 118), -INT8_C( 52), INT8_C( 22), INT8_C( 26), INT8_C( 4), INT8_C( 26) }, { INT8_C( 44), -INT8_C( 81), -INT8_C( 125), INT8_C( 115), -INT8_C( 33), -INT8_C( 14), INT8_C( 10), -INT8_C( 14) } }, { { INT8_C( 118), INT8_MIN, INT8_C( 56), -INT8_C( 47), INT8_C( 97), INT8_C( 23), INT8_C( 80), -INT8_C( 15) }, { { INT8_C( 122), INT8_C( 66), INT8_C( 79), INT8_C( 117), -INT8_C( 35), INT8_C( 28), -INT8_C( 96), -INT8_C( 97) }, { INT8_C( 22), INT8_C( 22), INT8_C( 107), -INT8_C( 116), INT8_C( 80), -INT8_C( 113), INT8_C( 71), INT8_C( 57) }, { INT8_C( 123), INT8_C( 64), -INT8_C( 119), INT8_C( 123), INT8_C( 93), INT8_C( 119), INT8_C( 90), -INT8_C( 45) }, { -INT8_C( 9), -INT8_C( 110), -INT8_C( 92), INT8_C( 88), -INT8_C( 86), -INT8_C( 12), INT8_C( 74), INT8_C( 36) } }, { INT8_C( 22), INT8_C( 25), INT8_C( 25), INT8_C( 19), INT8_C( 21), INT8_C( 57), INT8_C( 18), INT8_C( 12) }, { INT8_C( 90), -INT8_C( 110), -INT8_C( 110), INT8_C( 123), INT8_C( 119), INT8_C( 23), -INT8_C( 119), INT8_C( 80) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_int8x8_t a, c, r; simde_int8x8x4_t b; a = simde_vld1_s8(test_vec[i].a); b.val[0] = simde_vld1_s8(test_vec[i].b[0]); b.val[1] = simde_vld1_s8(test_vec[i].b[1]); b.val[2] = simde_vld1_s8(test_vec[i].b[2]); b.val[3] = simde_vld1_s8(test_vec[i].b[3]); c = simde_vld1_s8(test_vec[i].c); r = simde_vtbx4_s8(a, b, c); simde_test_arm_neon_assert_equal_i8x8(r, simde_vld1_s8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_int8x8_t a = simde_test_arm_neon_random_i8x8(); simde_int8x8x4_t b = simde_test_arm_neon_random_i8x8x4(); simde_int8x8_private c_ = simde_int8x8_to_private(simde_test_arm_neon_random_i8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 31; } } simde_int8x8_t c = simde_int8x8_from_private(c_); simde_int8x8_t r = simde_vtbx4_s8(a, b, c); simde_test_arm_neon_write_i8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_i8x8x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_i8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } static int test_simde_vtbx4_u8 (SIMDE_MUNIT_TEST_ARGS) { #if 1 struct { SIMDE_ALIGN_TO_16 uint8_t a[8]; SIMDE_ALIGN_TO_16 uint8_t b[4][8]; SIMDE_ALIGN_TO_16 uint8_t c[8]; SIMDE_ALIGN_TO_16 uint8_t r[8]; } test_vec[] = { { { UINT8_C(242), UINT8_C(225), UINT8_C(193), UINT8_C( 59), UINT8_C(239), UINT8_C(138), UINT8_C(184), UINT8_C(104) }, { { UINT8_C( 77), UINT8_C( 36), UINT8_C( 30), UINT8_C( 81), UINT8_C(112), UINT8_C(130), UINT8_C( 60), UINT8_C(231) }, { UINT8_C(122), UINT8_C( 21), UINT8_C( 38), UINT8_C( 44), UINT8_C( 62), UINT8_C( 98), UINT8_C(206), UINT8_C(238) }, { UINT8_C(114), UINT8_C( 68), UINT8_C(207), UINT8_C( 74), UINT8_C(164), UINT8_C(109), UINT8_C( 79), UINT8_C(150) }, { UINT8_C( 78), UINT8_C( 16), UINT8_C(209), UINT8_C( 61), UINT8_C(155), UINT8_C(137), UINT8_C(166), UINT8_C(232) } }, { UINT8_C( 14), UINT8_C(196), UINT8_C( 25), UINT8_C( 30), UINT8_C( 6), UINT8_C(117), UINT8_C( 5), UINT8_C( 1) }, { UINT8_C(206), UINT8_C(225), UINT8_C( 16), UINT8_C(166), UINT8_C( 60), UINT8_C(138), UINT8_C(130), UINT8_C( 36) } }, { { UINT8_C( 0), UINT8_C(133), UINT8_C( 73), UINT8_C(164), UINT8_C(242), UINT8_C(152), UINT8_C( 58), UINT8_C( 65) }, { { UINT8_C(169), UINT8_C( 11), UINT8_C(126), UINT8_C( 68), UINT8_C(149), UINT8_C( 36), UINT8_C( 44), UINT8_C( 67) }, { UINT8_C(233), UINT8_C(101), UINT8_C( 97), UINT8_C( 47), UINT8_C(218), UINT8_C(102), UINT8_C(240), UINT8_C(100) }, { UINT8_C(145), UINT8_C(222), UINT8_C( 45), UINT8_C( 30), UINT8_C(154), UINT8_C(227), UINT8_C( 30), UINT8_C(154) }, { UINT8_C(105), UINT8_C(103), UINT8_C( 62), UINT8_C( 91), UINT8_C( 0), UINT8_C(120), UINT8_C(156), UINT8_C(169) } }, { UINT8_C( 3), UINT8_C( 27), UINT8_C( 13), UINT8_C( 24), UINT8_C( 31), UINT8_C( 25), UINT8_C( 91), UINT8_C( 8) }, { UINT8_C( 68), UINT8_C( 91), UINT8_C(102), UINT8_C(105), UINT8_C(169), UINT8_C(103), UINT8_C( 58), UINT8_C(233) } }, { { UINT8_C( 38), UINT8_C(233), UINT8_C(210), UINT8_C(192), UINT8_C(205), UINT8_C(240), UINT8_C( 90), UINT8_C( 54) }, { { UINT8_C( 87), UINT8_C(152), UINT8_C(145), UINT8_C( 87), UINT8_C( 16), UINT8_C( 46), UINT8_C( 0), UINT8_C(148) }, { UINT8_C( 73), UINT8_C(237), UINT8_C(172), UINT8_C(136), UINT8_C( 6), UINT8_C( 8), UINT8_C(177), UINT8_C(132) }, { UINT8_C(196), UINT8_C( 9), UINT8_C(220), UINT8_C(231), UINT8_C( 81), UINT8_C(153), UINT8_C(154), UINT8_C(120) }, { UINT8_C(130), UINT8_C(108), UINT8_C( 56), UINT8_C( 79), UINT8_C( 92), UINT8_C(147), UINT8_C(133), UINT8_C(180) } }, { UINT8_C( 11), UINT8_C( 23), UINT8_C( 11), UINT8_C( 60), UINT8_C( 5), UINT8_C( 12), UINT8_C( 16), UINT8_C( 14) }, { UINT8_C(136), UINT8_C(120), UINT8_C(136), UINT8_C(192), UINT8_C( 46), UINT8_C( 6), UINT8_C(196), UINT8_C(177) } }, { { UINT8_C(208), UINT8_C( 97), UINT8_C( 48), UINT8_C( 34), UINT8_C(250), UINT8_C(202), UINT8_C(154), UINT8_C(124) }, { { UINT8_C( 55), UINT8_C(210), UINT8_C(204), UINT8_C(147), UINT8_C(101), UINT8_C( 81), UINT8_C( 71), UINT8_C(145) }, { UINT8_C(104), UINT8_C( 83), UINT8_C(205), UINT8_C(173), UINT8_C( 95), UINT8_C(157), UINT8_C( 59), UINT8_C( 88) }, { UINT8_C( 25), UINT8_C( 82), UINT8_C( 88), UINT8_C(158), UINT8_C( 25), UINT8_C(221), UINT8_C(231), UINT8_C(234) }, { UINT8_C( 62), UINT8_C( 23), UINT8_C( 12), UINT8_C( 56), UINT8_C(225), UINT8_C(166), UINT8_C(180), UINT8_C( 24) } }, { UINT8_C( 24), UINT8_C( 0), UINT8_C(172), UINT8_C( 30), UINT8_C( 18), UINT8_C(243), UINT8_C( 15), UINT8_C( 26) }, { UINT8_C( 62), UINT8_C( 55), UINT8_C( 48), UINT8_C(180), UINT8_C( 88), UINT8_C(202), UINT8_C( 88), UINT8_C( 12) } }, { { UINT8_C(117), UINT8_C( 86), UINT8_C(144), UINT8_C(143), UINT8_C( 51), UINT8_C(119), UINT8_C(121), UINT8_C(113) }, { { UINT8_C(142), UINT8_C(133), UINT8_C(169), UINT8_C(112), UINT8_C( 43), UINT8_C( 94), UINT8_C(136), UINT8_C(163) }, { UINT8_C(222), UINT8_C( 52), UINT8_C(129), UINT8_C(176), UINT8_C( 40), UINT8_C(240), UINT8_C(235), UINT8_C(110) }, { UINT8_C( 44), UINT8_C(211), UINT8_C( 20), UINT8_C( 5), UINT8_C(246), UINT8_C( 18), UINT8_C(248), UINT8_C(108) }, { UINT8_C(104), UINT8_C(136), UINT8_C(251), UINT8_C(156), UINT8_C( 0), UINT8_C(116), UINT8_C( 13), UINT8_C(142) } }, { UINT8_C( 25), UINT8_C(183), UINT8_C( 30), UINT8_C( 4), UINT8_C( 21), UINT8_C(135), UINT8_C(199), UINT8_C( 19) }, { UINT8_C(136), UINT8_C( 86), UINT8_C( 13), UINT8_C( 43), UINT8_C( 18), UINT8_C(119), UINT8_C(121), UINT8_C( 5) } }, { { UINT8_C( 98), UINT8_C(102), UINT8_C(107), UINT8_C( 88), UINT8_C(120), UINT8_C( 99), UINT8_C(196), UINT8_C(224) }, { { UINT8_C(236), UINT8_C(191), UINT8_C(124), UINT8_C(236), UINT8_C( 51), UINT8_C(138), UINT8_C(122), UINT8_C( 44) }, { UINT8_C( 65), UINT8_C(121), UINT8_C( 80), UINT8_C( 86), UINT8_C( 0), UINT8_C( 24), UINT8_C( 73), UINT8_C(187) }, { UINT8_C( 97), UINT8_C(237), UINT8_C(159), UINT8_C(154), UINT8_C(124), UINT8_C(241), UINT8_C( 0), UINT8_C(222) }, { UINT8_C( 87), UINT8_C(108), UINT8_C( 55), UINT8_C(207), UINT8_C(207), UINT8_C(251), UINT8_C(175), UINT8_C(187) } }, { UINT8_C( 27), UINT8_C( 12), UINT8_C( 7), UINT8_C(238), UINT8_C( 22), UINT8_C( 2), UINT8_C( 27), UINT8_C( 23) }, { UINT8_C(207), UINT8_C( 0), UINT8_C( 44), UINT8_C( 88), UINT8_C( 0), UINT8_C(124), UINT8_C(207), UINT8_C(222) } }, { { UINT8_C(132), UINT8_C(245), UINT8_C(127), UINT8_C( 0), UINT8_C(230), UINT8_C(127), UINT8_C(223), UINT8_C( 61) }, { { UINT8_C(235), UINT8_C( 22), UINT8_C( 12), UINT8_C(187), UINT8_C( 17), UINT8_C(188), UINT8_C(118), UINT8_C(204) }, { UINT8_C(232), UINT8_C( 30), UINT8_C(187), UINT8_C(158), UINT8_C( 64), UINT8_C(214), UINT8_C(149), UINT8_C(219) }, { UINT8_C( 65), UINT8_C(226), UINT8_C(118), UINT8_C(197), UINT8_C(120), UINT8_C(204), UINT8_C(169), UINT8_C(252) }, { UINT8_C(194), UINT8_C( 40), UINT8_C(253), UINT8_C(168), UINT8_C(168), UINT8_C(220), UINT8_C(230), UINT8_C(147) } }, { UINT8_C( 18), UINT8_C( 18), UINT8_C( 14), UINT8_C( 3), UINT8_C( 14), UINT8_C( 5), UINT8_C( 16), UINT8_C( 22) }, { UINT8_C(118), UINT8_C(118), UINT8_C(149), UINT8_C(187), UINT8_C(149), UINT8_C(188), UINT8_C( 65), UINT8_C(169) } }, { { UINT8_C(171), UINT8_C(116), UINT8_C(103), UINT8_C( 36), UINT8_C( 64), UINT8_C( 17), UINT8_C( 32), UINT8_C( 2) }, { { UINT8_C( 57), UINT8_C( 29), UINT8_C(171), UINT8_C(225), UINT8_C(249), UINT8_C(145), UINT8_C(117), UINT8_C(235) }, { UINT8_C(131), UINT8_C(195), UINT8_C(239), UINT8_C( 50), UINT8_C(136), UINT8_C(191), UINT8_C(200), UINT8_C(107) }, { UINT8_C( 74), UINT8_C(253), UINT8_C(142), UINT8_C(171), UINT8_C(198), UINT8_C(140), UINT8_C( 77), UINT8_C(114) }, { UINT8_C( 0), UINT8_C(181), UINT8_C(150), UINT8_C( 65), UINT8_C(198), UINT8_C(182), UINT8_C( 67), UINT8_MAX } }, { UINT8_C( 20), UINT8_C( 14), UINT8_C( 1), UINT8_C( 13), UINT8_C(127), UINT8_C( 22), UINT8_C( 25), UINT8_C( 3) }, { UINT8_C(198), UINT8_C(200), UINT8_C( 29), UINT8_C(191), UINT8_C( 64), UINT8_C( 77), UINT8_C(181), UINT8_C(225) } }, }; for (size_t i = 0 ; i < (sizeof(test_vec) / sizeof(test_vec[0])) ; i++) { simde_uint8x8_t a, c, r; simde_uint8x8x4_t b; a = simde_vld1_u8(test_vec[i].a); b.val[0] = simde_vld1_u8(test_vec[i].b[0]); b.val[1] = simde_vld1_u8(test_vec[i].b[1]); b.val[2] = simde_vld1_u8(test_vec[i].b[2]); b.val[3] = simde_vld1_u8(test_vec[i].b[3]); c = simde_vld1_u8(test_vec[i].c); r = simde_vtbx4_u8(a, b, c); simde_test_arm_neon_assert_equal_u8x8(r, simde_vld1_u8(test_vec[i].r)); } return 0; #else fputc('\n', stdout); for (int i = 0 ; i < 8 ; i++) { simde_uint8x8_t a = simde_test_arm_neon_random_u8x8(); simde_uint8x8x4_t b = simde_test_arm_neon_random_u8x8x4(); simde_uint8x8_private c_ = simde_uint8x8_to_private(simde_test_arm_neon_random_u8x8()); for (size_t j = 0 ; j < (sizeof(c_.values) / sizeof(c_.values[0])) ; j++) { if (probability(PROBABILITY)) { c_.values[j] &= 31; } } simde_uint8x8_t c = simde_uint8x8_from_private(c_); simde_uint8x8_t r = simde_vtbx4_u8(a, b, c); simde_test_arm_neon_write_u8x8(2, a, SIMDE_TEST_VEC_POS_FIRST); simde_test_arm_neon_write_u8x8x4(2, b, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, c, SIMDE_TEST_VEC_POS_MIDDLE); simde_test_arm_neon_write_u8x8(2, r, SIMDE_TEST_VEC_POS_LAST); } return 1; #endif } #endif /* !defined(SIMDE_BUG_INTEL_857088) */ SIMDE_TEST_FUNC_LIST_BEGIN SIMDE_TEST_FUNC_LIST_ENTRY(vtbx1_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx1_u8) #if !defined(SIMDE_BUG_INTEL_857088) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx2_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx2_u8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx3_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx3_u8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx4_s8) SIMDE_TEST_FUNC_LIST_ENTRY(vtbx4_u8) #endif /* !defined(SIMDE_BUG_INTEL_857088) */ SIMDE_TEST_FUNC_LIST_END #include "test-neon-footer.h"
bed9cf60ae2ed3cec78c82b0ecf5eee3972f31d6
1e21f8adf6af9a27d03559a08ca12d7741ceefce
/app/src/main/cpp/m3g/src/m3g_mesh.c
fdd0146c68df2410eb5a0af203f858723b16208e
[ "Apache-2.0" ]
permissive
nikita36078/J2ME-Loader
4d2298347b12b394904c336c7ea4e06cf1b935c3
c265feb3a74496493e6f01970772331d14d3716f
refs/heads/master
2023-08-24T23:01:13.247116
2023-08-16T14:34:46
2023-08-16T14:34:46
91,971,028
1,657
281
Apache-2.0
2023-08-16T14:34:47
2017-05-21T16:23:08
Java
UTF-8
C
false
false
25,305
c
m3g_mesh.c
/* * Copyright (c) 2003 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Mesh implementation * */ /*! * \internal * \file * \brief Mesh implementation */ #ifndef M3G_CORE_INCLUDE # error included by m3g_core.c; do not compile separately. #endif #include "m3g_mesh.h" #include "m3g_memory.h" /*---------------------------------------------------------------------- * Internal functions *--------------------------------------------------------------------*/ /*! * \internal * \brief Destroys this Mesh object. * * \param obj Mesh object */ static void m3gDestroyMesh(Object *obj) { M3Gint i; Mesh *mesh = (Mesh *) obj; M3G_VALIDATE_OBJECT(mesh); for (i = 0; i < mesh->trianglePatchCount; ++i) { M3G_ASSIGN_REF(mesh->indexBuffers[i], NULL); M3G_ASSIGN_REF(mesh->appearances[i], NULL); } M3G_ASSIGN_REF(mesh->vertexBuffer, NULL); { Interface *m3g = M3G_INTERFACE(mesh); m3gFree(m3g, mesh->indexBuffers); m3gFree(m3g, mesh->appearances); } m3gIncStat(M3G_INTERFACE(obj), M3G_STAT_RENDERABLES, -1); m3gDestroyNode(obj); } /*! * \internal * \brief Insert a mesh into a rendering queue */ static M3Gbool m3gQueueMesh(Mesh *mesh, const Matrix *toCamera, RenderQueue *renderQueue) { M3Gint i; /* Fetch the cumulative alpha factor for this node */ mesh->totalAlphaFactor = (M3Gushort) m3gGetTotalAlphaFactor((Node*) mesh, renderQueue->root); /* Insert each submesh into the rendering queue */ for (i = 0; i < mesh->trianglePatchCount; i++) { if (mesh->appearances[i] != NULL) { if (!m3gInsertDrawable(M3G_INTERFACE(mesh), renderQueue, (Node*) mesh, toCamera, i, m3gGetAppearanceSortKey(((Appearance*)mesh->appearances[i])))) return M3G_FALSE; } } return M3G_TRUE; } /*! * \internal * \brief Overloaded Node method. * * Setup mesh rendering by adding all submeshes to * the render queue. * * \param self Mesh object * \param toCamera transform to camera * \param alphaFactor total alpha factor * \param caller caller node * \param renderQueue RenderQueue * * \retval M3G_TRUE continue render setup * \retval M3G_FALSE abort render setup */ static M3Gbool m3gMeshSetupRender(Node *self, const Node *caller, SetupRenderState *s, RenderQueue *renderQueue) { Mesh *mesh = (Mesh *)self; M3G_UNREF(caller); m3gIncStat(M3G_INTERFACE(self), M3G_STAT_RENDER_NODES, 1); if ((self->enableBits & NODE_RENDER_BIT) != 0 && (self->scope & renderQueue->scope) != 0) { /* Check view frustum culling */ # if defined(M3G_ENABLE_VF_CULLING) AABB bbox; m3gGetBoundingBox(mesh->vertexBuffer, &bbox); m3gUpdateCullingMask(s, renderQueue->camera, &bbox); if (s->cullMask == 0) { m3gIncStat(M3G_INTERFACE(self), M3G_STAT_RENDER_NODES_CULLED, 1); return M3G_TRUE; } # endif /* No dice, let's render... */ return m3gQueueMesh(mesh, &s->toCamera, renderQueue); } return M3G_TRUE; } /*! * \internal * \brief Overloaded Node method. * * Renders one submesh. * * \param self Mesh object * \param ctx current render context * \param patchIndex submesh index */ static void m3gMeshDoRender(Node *self, RenderContext *ctx, const Matrix *toCamera, M3Gint patchIndex) { Mesh *mesh = (Mesh *)self; m3gDrawMesh(ctx, mesh->vertexBuffer, (const IndexBuffer *) mesh->indexBuffers[patchIndex], (const Appearance *) mesh->appearances[patchIndex], toCamera, mesh->totalAlphaFactor + 1, self->scope); } /*! * \internal * \brief Internal equivalent routine called * by m3gMeshRayIntersect. * * \param mesh Mesh object * \param vertices VertexBuffer object used in calculations * \param mask pick scope mask * \param ray pick ray * \param ri RayIntersection object * \param toGroup transform to originating group * \retval M3G_TRUE continue pick * \retval M3G_FALSE abort pick */ static M3Gbool m3gMeshRayIntersectInternal( Mesh *mesh, VertexBuffer *vertices, M3Gint mask, M3Gfloat *ray, RayIntersection *ri, Matrix *toGroup) { Vec3 v0, v1, v2, tuv; Vec4 transformed, p0, p1; M3Gint indices[4] = { 0, 0, 0, 0 }; M3Gint i, j, k, cullMode; Matrix t; /* Reused as texture transform */ if (vertices == NULL || mesh->appearances == NULL || mesh->indexBuffers == NULL || (((Node *)mesh)->scope & mask) == 0) { return M3G_TRUE; } if (vertices->vertices == NULL) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_OPERATION); return M3G_FALSE; } p0.x = ray[0]; p0.y = ray[1]; p0.z = ray[2]; p0.w = 1.f; p1.x = ray[3]; p1.y = ray[4]; p1.z = ray[5]; p1.w = 1.f; m3gCopyMatrix(&t, toGroup); M3G_BEGIN_PROFILE(M3G_INTERFACE(mesh), M3G_PROFILE_TRANSFORM_INVERT); if (!m3gInvertMatrix(&t)) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_ARITHMETIC_ERROR); return M3G_FALSE; } M3G_END_PROFILE(M3G_INTERFACE(mesh), M3G_PROFILE_TRANSFORM_INVERT); m3gTransformVec4(&t, &p0); m3gTransformVec4(&t, &p1); m3gScaleVec3((Vec3*) &p0, m3gRcp(p0.w)); m3gScaleVec3((Vec3*) &p1, m3gRcp(p1.w)); m3gSubVec4(&p1, &p0); /* Quick bounding box test for Meshes */ if (m3gGetClass((Object *)mesh) == M3G_CLASS_MESH) { AABB boundingBox; m3gGetBoundingBox(vertices, &boundingBox); if (!m3gIntersectBox((Vec3*) &p0, (Vec3*) &p1, &boundingBox)) { return M3G_TRUE; } } /* Apply the inverse of the vertex scale and bias to the ray */ if (!IS_ZERO(vertices->vertexScale)) { const Vec3 *bias = (const Vec3*) vertices->vertexBias; M3Gfloat ooScale = m3gRcp(vertices->vertexScale); m3gSubVec3((Vec3*) &p0, bias); m3gScaleVec3((Vec3*) &p0, ooScale); m3gScaleVec3((Vec3*) &p1, ooScale); /* direction vector -> no bias */ } else { m3gRaiseError(M3G_INTERFACE(mesh), M3G_ARITHMETIC_ERROR); return M3G_FALSE; } /* Go through all submeshes */ for (i = 0; i < mesh->trianglePatchCount; i++) { /* Do not pick submeshes with null appearance */ if (mesh->appearances[i] == NULL || mesh->indexBuffers[i] == NULL) continue; /* Validate indices versus vertex buffer */ if (m3gGetMaxIndex((const IndexBuffer *) mesh->indexBuffers[i]) >= m3gGetNumVertices(vertices)) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_OPERATION); return M3G_FALSE; } if (((Appearance*)mesh->appearances[i])->polygonMode != NULL) { cullMode = m3gGetWinding(((Appearance*)mesh->appearances[i])->polygonMode) == M3G_WINDING_CCW ? 0 : 1; switch(m3gGetCulling(((Appearance*)mesh->appearances[i])->polygonMode)) { case M3G_CULL_FRONT: cullMode ^= 1; break; case M3G_CULL_NONE: cullMode = 2; break; } } else { cullMode = 0; } /* Go through all triangels */ for (j = 0; m3gGetIndices((const IndexBuffer *) mesh->indexBuffers[i], j, indices); j++) { /* Ignore zero area triangles */ if ( indices[0] == indices[1] || indices[0] == indices[2] || indices[1] == indices[2]) continue; m3gGetVertex(vertices, indices[0], &v0); m3gGetVertex(vertices, indices[1], &v1); m3gGetVertex(vertices, indices[2], &v2); if (m3gIntersectTriangle((Vec3*)&p0, (Vec3*)&p1, &v0, &v1, &v2, &tuv, indices[3] ^ cullMode)) { /* Check that we are going to fill this intersection */ if (tuv.x <= 0.f || tuv.x >= ri->tMin) continue; /* Fill in to RayIntersection */ ri->tMin = tuv.x; ri->distance = tuv.x; ri->submeshIndex = i; ri->intersected = (Node *)mesh; /* Fetch normal */ if (m3gGetNormal(vertices, indices[0], &v0)) { m3gGetNormal(vertices, indices[1], &v1); m3gGetNormal(vertices, indices[2], &v2); ri->normal[0] = m3gAdd( m3gMul(v0.x, m3gSub(1.f, m3gAdd(tuv.y, tuv.z))), m3gAdd( m3gMul(v1.x, tuv.y), m3gMul(v2.x, tuv.z))); ri->normal[1] = m3gAdd( m3gMul(v0.y, m3gSub(1.f, m3gAdd(tuv.y, tuv.z))), m3gAdd( m3gMul(v1.y, tuv.y), m3gMul(v2.y, tuv.z))); ri->normal[2] = m3gAdd( m3gMul(v0.z, m3gSub(1.f, m3gAdd(tuv.y, tuv.z))), m3gAdd( m3gMul(v1.z, tuv.y), m3gMul(v2.z, tuv.z))); } else { ri->normal[0] = 0.f; ri->normal[1] = 0.f; ri->normal[2] = 1.f; } /* Fetch texture coordinates for each unit */ for (k = 0; k < M3G_NUM_TEXTURE_UNITS; k++) { if (m3gGetTexCoord(vertices, indices[0], k, &v0)) { m3gGetTexCoord(vertices, indices[1], k, &v1); m3gGetTexCoord(vertices, indices[2], k, &v2); /* Calculate transformed S and T */ transformed.x = m3gAdd( m3gMul(v0.x, m3gSub(1.f, m3gAdd(tuv.y, tuv.z))), m3gAdd( m3gMul(v1.x, tuv.y), m3gMul(v2.x, tuv.z))); transformed.y = m3gAdd( m3gMul(v0.y, m3gSub(1.f, m3gAdd(tuv.y, tuv.z))), m3gAdd( m3gMul(v1.y, tuv.y), m3gMul(v2.y, tuv.z))); transformed.z = 0; transformed.w = 1; /* Transform and * 1/w */ if (((Appearance*)mesh->appearances[i])->texture[k] != NULL) { m3gGetCompositeTransform((Transformable *)((Appearance*)mesh->appearances[i])->texture[k], &t); m3gTransformVec4(&t, &transformed); m3gScaleVec4(&transformed, m3gRcp(transformed.w)); } ri->textureS[k] = transformed.x; ri->textureT[k] = transformed.y; } else { ri->textureS[k] = 0.f; ri->textureT[k] = 0.f; } } } } } return M3G_TRUE; } /*! * \internal * \brief Overloaded Node method. * * Just forward call internal ray intersect. * * \param self Mesh object * \param mask pick scope mask * \param ray pick ray * \param ri RayIntersection object * \param toGroup transform to originating group * \retval M3G_TRUE continue pick * \retval M3G_FALSE abort pick */ static M3Gbool m3gMeshRayIntersect( Node *self, M3Gint mask, M3Gfloat *ray, RayIntersection *ri, Matrix *toGroup) { Mesh *mesh = (Mesh *)self; return m3gMeshRayIntersectInternal(mesh, mesh->vertexBuffer, mask, ray, ri, toGroup); } /*! * \internal * \brief Initializes a Mesh object. See specification * for default values. * * \param m3g M3G interface * \param mesh Mesh object * \param hVertices VertexBuffer object * \param hTriangles array of IndexBuffer objects * \param hAppearances array of Appearance objects * \param trianglePatchCount number of submeshes * \param vfTable virtual function table * \retval M3G_TRUE success * \retval M3G_FALSE failed */ static M3Gbool m3gInitMesh(Interface *m3g, Mesh *mesh, M3GVertexBuffer hVertices, M3Gulong *hTriangles, M3Gulong *hAppearances, M3Gint trianglePatchCount, M3GClass classID) { M3Gint i; /* Out of memory if more than 65535 triangle patches */ if (trianglePatchCount > 65535) { m3gRaiseError(m3g, M3G_OUT_OF_MEMORY); return M3G_FALSE; } for (i = 0; i < trianglePatchCount; i++) { if (hTriangles[i] == NULL) { m3gRaiseError(m3g, M3G_NULL_POINTER); return M3G_FALSE; } } mesh->indexBuffers = m3gAllocZ(m3g, sizeof(M3Gulong) * trianglePatchCount); if (!mesh->indexBuffers) { return M3G_FALSE; } mesh->appearances = m3gAllocZ(m3g, sizeof(M3Gulong) * trianglePatchCount); if (!mesh->appearances) { m3gFree(m3g, mesh->indexBuffers); return M3G_FALSE; } /* Mesh is derived from node */ m3gInitNode(m3g, &mesh->node, classID); mesh->node.hasRenderables = M3G_TRUE; mesh->node.dirtyBits |= NODE_BBOX_BIT; for (i = 0; i < trianglePatchCount; i++) { M3G_ASSIGN_REF(mesh->indexBuffers[i], hTriangles[i]); } if (hAppearances != NULL) { for (i = 0; i < trianglePatchCount; i++) { M3G_ASSIGN_REF(mesh->appearances[i], hAppearances[i]); } } else { m3gZero(mesh->appearances, sizeof(Appearance *) * trianglePatchCount); } M3G_ASSIGN_REF(mesh->vertexBuffer, hVertices); mesh->trianglePatchCount = (M3Gushort) trianglePatchCount; m3gIncStat(M3G_INTERFACE(mesh), M3G_STAT_RENDERABLES, 1); return M3G_TRUE; } /*! * \internal * \brief Overloaded Object3D method. * * \param self Mesh object * \param references array of reference objects * \return number of references */ static M3Gint m3gMeshDoGetReferences(Object *self, M3Gulong *references) { Mesh *mesh = (Mesh *)self; M3Gint i, num = m3gObjectDoGetReferences(self, references); if (references != NULL) references[num] = (M3Gulong)mesh->vertexBuffer; num++; for (i = 0; i < mesh->trianglePatchCount; i++) { if (mesh->indexBuffers[i] != NULL) { if (references != NULL) references[num] = (M3Gulong)mesh->indexBuffers[i]; num++; } if (mesh->appearances[i] != NULL) { if (references != NULL) references[num] = (M3Gulong)mesh->appearances[i]; num++; } } return num; } /*! * \internal * \brief Overloaded Object3D method. */ static Object *m3gMeshFindID(Object *self, M3Gint userID) { int i; Mesh *mesh = (Mesh *)self; Object *found = m3gObjectFindID(self, userID); if (!found) { found = m3gFindID((Object*) mesh->vertexBuffer, userID); } for (i = 0; !found && i < mesh->trianglePatchCount; ++i) { if (mesh->indexBuffers[i] != NULL) { found = m3gFindID((Object*) mesh->indexBuffers[i], userID); } if (!found && mesh->appearances[i] != NULL) { found = m3gFindID((Object*) mesh->appearances[i], userID); } } return found; } /*! * \internal * \brief Overloaded Object3D method. * * \param originalObj original Mesh object * \param cloneObj pointer to cloned Mesh object * \param pairs array for all object-duplicate pairs * \param numPairs number of pairs */ static M3Gbool m3gMeshDuplicate(const Object *originalObj, Object **cloneObj, M3Gulong *pairs, M3Gint *numPairs) { /* Create the clone if it doesn't exist; otherwise we'll be all * set by the derived class(es) and can just call through to the * base class */ if (*cloneObj == NULL) { Mesh *original = (Mesh *)originalObj; Mesh *clone = (Mesh *)m3gCreateMesh(originalObj->interface, original->vertexBuffer, original->indexBuffers, original->appearances, original->trianglePatchCount); *cloneObj = (Object *)clone; if (*cloneObj == NULL) { return M3G_FALSE; } } return m3gNodeDuplicate(originalObj, cloneObj, pairs, numPairs); } /*! * \internal * \brief Overloaded Object3D method. * * \param self Mesh object * \param time current world time * \return minimum validity */ static M3Gint m3gMeshApplyAnimation(Object *self, M3Gint time) { M3Gint validity, minValidity; Mesh *mesh = (Mesh *)self; Object *vb; M3G_VALIDATE_OBJECT(mesh); minValidity = m3gObjectApplyAnimation(self, time); vb = (Object *) mesh->vertexBuffer; if (vb != NULL && minValidity > 0) { validity = M3G_VFUNC(Object, vb, applyAnimation)(vb, time); minValidity = M3G_MIN(validity, minValidity); } if (mesh->appearances != NULL) { Object *app; M3Gint i, n; n = mesh->trianglePatchCount; for (i = 0; i < n && minValidity > 0; ++i) { app = (Object *) mesh->appearances[i]; if (app != NULL) { validity = M3G_VFUNC(Object, app, applyAnimation)(app, time); minValidity = M3G_MIN(validity, minValidity); } } } return minValidity; } /*! * \internal * \brief Overloaded Node method */ static M3Gint m3gMeshGetBBox(Node *self, AABB *bbox) { Mesh *mesh = (Mesh *) self; VertexBuffer *vb = mesh->vertexBuffer; if (vb->vertices) { m3gGetBoundingBox(vb, bbox); return VFC_BBOX_COST + VFC_NODE_OVERHEAD; } else { return 0; } } /*! * \internal * \brief Overloaded Node method */ static M3Gbool m3gMeshValidate(Node *self, M3Gbitmask stateBits, M3Gint scope) { Mesh *mesh = (Mesh *) self; VertexBuffer *vb = mesh->vertexBuffer; int i; if ((scope & self->scope) != 0) { if (stateBits & self->enableBits) { /* Validate vertex buffer components */ for (i = 0; i < mesh->trianglePatchCount; ++i) { Appearance *app = ((Appearance*)mesh->appearances[i]); if (app) { if (!m3gValidateVertexBuffer( vb, app, m3gGetMaxIndex((const IndexBuffer *) mesh->indexBuffers[i]))) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_OPERATION); return M3G_FALSE; } } } /* Invalidate cached vertex stuff if source buffer changed */ { M3Gint vbTimestamp = m3gGetTimestamp(vb); if (mesh->vbTimestamp != vbTimestamp) { m3gInvalidateNode(self, NODE_BBOX_BIT); mesh->vbTimestamp = vbTimestamp; } } return m3gNodeValidate(self, stateBits, scope); } } return M3G_TRUE; } #if 0 /*! * \internal * \brief Computes the estimated rendering cost for this Mesh node */ static M3Gint m3gMeshRenderingCost(const Mesh *mesh) { /* Since we're using strips, just assume that each vertex * generates a new triangle... */ return mesh->vertexBuffer->vertexCount * (VFC_VERTEX_COST + VFC_TRIANGLE_COST) + mesh->trianglePatchCount * VFC_RENDERCALL_OVERHEAD + VFC_NODE_OVERHEAD; } #endif /*---------------------------------------------------------------------- * Virtual function table *--------------------------------------------------------------------*/ static const NodeVFTable m3gvf_Mesh = { { { m3gMeshApplyAnimation, m3gNodeIsCompatible, m3gNodeUpdateProperty, m3gMeshDoGetReferences, m3gMeshFindID, m3gMeshDuplicate, m3gDestroyMesh } }, m3gNodeAlign, m3gMeshDoRender, m3gMeshGetBBox, m3gMeshRayIntersect, m3gMeshSetupRender, m3gNodeUpdateDuplicateReferences, m3gMeshValidate }; /*---------------------------------------------------------------------- * Public API functions *--------------------------------------------------------------------*/ /*! * \brief Creates a Mesh object. * * \param interface M3G interface * \param hVertices VertexBuffer object * \param hTriangles array of IndexBuffer objects * \param hAppearances array of Appearance objects * \param trianglePatchCount number of submeshes * \retval Mesh new Mesh object * \retval NULL Mesh creating failed */ M3G_API M3GMesh m3gCreateMesh(M3GInterface interface, M3GVertexBuffer hVertices, M3Gulong *hTriangles, M3Gulong *hAppearances, M3Gint trianglePatchCount) { Interface *m3g = (Interface *) interface; M3G_VALIDATE_INTERFACE(m3g); { Mesh *mesh = m3gAllocZ(m3g, sizeof(Mesh)); if (mesh != NULL) { if (!m3gInitMesh(m3g, mesh, hVertices, hTriangles, hAppearances, trianglePatchCount, M3G_CLASS_MESH)) { m3gFree(m3g, mesh); return NULL; } } return (M3GMesh)mesh; } } /*! * \brief Sets submesh appearance. * * \param handle Mesh object * \param appearanceIndex submesh index * \param hAppearance Appearance object */ M3G_API void m3gSetAppearance(M3GMesh handle, M3Gint appearanceIndex, M3GAppearance hAppearance) { Mesh *mesh = (Mesh *)handle; M3G_VALIDATE_OBJECT(mesh); if (appearanceIndex < 0 || appearanceIndex >= mesh->trianglePatchCount) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_INDEX); return; } M3G_ASSIGN_REF(mesh->appearances[appearanceIndex], (Appearance *) hAppearance); } /*! * \brief Gets submesh appearance. * * \param handle Mesh object * \param idx submesh index * \return Appearance object */ M3G_API M3GAppearance m3gGetAppearance(M3GMesh handle, M3Gint idx) { Mesh *mesh = (Mesh *)handle; M3G_VALIDATE_OBJECT(mesh); if (idx < 0 || idx >= mesh->trianglePatchCount) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_INDEX); return NULL; } return (M3GAppearance) mesh->appearances[idx]; } /*! * \brief Gets submesh index buffer. * * \param handle Mesh object * \param idx submesh index * \return IndexBuffer object */ M3G_API M3GIndexBuffer m3gGetIndexBuffer(M3GMesh handle, M3Gint idx) { Mesh *mesh = (Mesh *)handle; M3G_VALIDATE_OBJECT(mesh); if (idx < 0 || idx >= mesh->trianglePatchCount) { m3gRaiseError(M3G_INTERFACE(mesh), M3G_INVALID_INDEX); return NULL; } return (M3GIndexBuffer) mesh->indexBuffers[idx]; } /*! * \brief Gets VertexBuffer. * * \param handle Mesh object * \return VertexBuffer object */ M3G_API M3GVertexBuffer m3gGetVertexBuffer(M3GMesh handle) { Mesh *mesh = (Mesh *)handle; M3G_VALIDATE_OBJECT(mesh); return mesh->vertexBuffer; } /*! * \brief Gets submesh count. * * \param handle Mesh object * \return submesh count */ M3G_API M3Gint m3gGetSubmeshCount(M3GMesh handle) { Mesh *mesh = (Mesh *)handle; M3G_VALIDATE_OBJECT(mesh); return mesh->trianglePatchCount; }
ea1567844c2c74500621dbb58f8e60abcb42c4d7
c26d7b0ed875357278e61627da2da0650da77986
/src/cmd/pforth/pf_clib.h
b7f3bc6d9338a77c02b574f06ac743eda419c60d
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
1,688
h
pf_clib.h
/* @(#) pf_clib.h 96/12/18 1.10 */ #ifndef _pf_clib_h #define _pf_clib_h /*************************************************************** ** Include file for PForth tools ** ** Author: Phil Burk ** Copyright 1994 3DO, Phil Burk, Larry Polansky, David Rosenboom ** ** The pForth software code is dedicated to the public domain, ** and any third party may reproduce, distribute and modify ** the pForth software code or any derivative works thereof ** without any compensation or license. The pForth software ** code is provided on an "as is" basis without any warranty ** of any kind, including, without limitation, the implied ** warranties of merchantability and fitness for a particular ** purpose and their equivalents under the laws of any jurisdiction. ** ***************************************************************/ #ifdef PF_NO_CLIB #ifdef __cplusplus extern "C" { #endif cell_t pfCStringLength( const char *s ); void *pfSetMemory( void *s, cell_t c, cell_t n ); void *pfCopyMemory( void *s1, const void *s2, cell_t n); #define EXIT(n) {while(1);} #ifdef __cplusplus } #endif #else /* PF_NO_CLIB */ #ifdef PF_USER_CLIB #include PF_USER_CLIB #else /* Use stdlib functions if available because they are probably faster. */ #define pfCStringLength strlen #define pfSetMemory memset #define pfCopyMemory memcpy #define EXIT(n) exit(n) #endif /* PF_USER_CLIB */ #endif /* !PF_NO_CLIB */ #ifdef __cplusplus extern "C" { #endif /* Always use my own functions to avoid macro expansion problems with tolower(*s++) */ char pfCharToUpper( char c ); char pfCharToLower( char c ); #ifdef __cplusplus } #endif #endif /* _pf_clib_h */
d20039d61e397e852135fc446b038cd8475ced4d
1efb2283837c9b70bc6449cec877799e4efa3268
/test/mpi/init/exitst3.c
aeed1d4e2aa146bed828f6ba5a00386ad13e40a1
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
587
c
exitst3.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "mpi.h" /* * This is a special test to check that mpiexec handles the death of * some processes without an Abort or clean exit */ int main(int argc, char *argv[]) { int rank, size; MPI_Init(0, 0); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Barrier(MPI_COMM_WORLD); if (rank == size - 1) { /* Cause some processes to exit */ int *p = 0; *p = rank; } MPI_Finalize(); return 0; }
66512264b34697d3d469ccb523de5fbb0f144ed7
1577e1cf4e89584a125cffb855ca50a9654c6d55
/Security/RegressionTests/codesigning_api_tests/secstaticcode.h
0cc936a802f3eb50f7fe02239bf9caf5ba695f2e
[]
no_license
apple-open-source/macos
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
2d2b15f13487673de33297e49f00ef94af743a9a
refs/heads/master
2023-08-01T11:03:26.870408
2023-03-27T00:00:00
2023-03-27T00:00:00
180,595,052
124
24
null
2022-12-27T14:54:09
2019-04-10T14:06:23
null
UTF-8
C
false
false
215
h
secstaticcode.h
// // secstaticcode.h // Security // // Copyright 2021 Apple Inc. All rights reserved. // #include <sys/cdefs.h> __BEGIN_DECLS /// Integration test hook. int run_integration_tests(const char *root); __END_DECLS
9b6dd19f49cc1f9b468a029e6fd7b2243c4316b3
5e4913b3d7b6dfd9f35d9e5f24486bb6b6145125
/src/plugins/validation/validation.c
e4b22a4f871036914df00cf2b4e981bcf510d03e
[ "BSD-3-Clause" ]
permissive
ElektraInitiative/libelektra
ff5d5cfc4bf91d704f58405b14ea694aad3a2edd
dbbe4ae4f669c322a8f95f59112d3f5fc370bbd9
refs/heads/master
2023-08-05T14:54:48.081359
2023-08-04T12:40:00
2023-08-04T12:40:00
21,063,580
215
170
BSD-3-Clause
2023-09-07T13:34:30
2014-06-21T08:01:04
C
UTF-8
C
false
false
5,260
c
validation.c
/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #ifndef HAVE_KDBCONFIG #include "kdbconfig.h" #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "validation.h" static int validateKey (Key *, Key *); int elektraValidationGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey ELEKTRA_UNUSED) { KeySet * n; ksAppend (returned, n = ksNew (30, keyNew ("system:/elektra/modules/validation", KEY_VALUE, "validation plugin waits for your orders", KEY_END), keyNew ("system:/elektra/modules/validation/exports", KEY_END), keyNew ("system:/elektra/modules/validation/exports/get", KEY_FUNC, elektraValidationGet, KEY_END), keyNew ("system:/elektra/modules/validation/exports/set", KEY_FUNC, elektraValidationSet, KEY_END), keyNew ("system:/elektra/modules/validation/exports/ksLookupRE", KEY_FUNC, ksLookupRE, KEY_END), keyNew ("system:/elektra/modules/validation/exports/validateKey", KEY_FUNC, validateKey, KEY_END), #include "readme_validation.c" keyNew ("system:/elektra/modules/validation/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END)); ksDel (n); return 1; } static int validateKey (Key * key, Key * parentKey) { const Key * regexMeta = keyGetMeta (key, "check/validation"); const Key * icaseMeta = keyGetMeta (key, "check/validation/ignorecase"); const Key * matchMeta = keyGetMeta (key, "check/validation/match"); const Key * invertMeta = keyGetMeta (key, "check/validation/invert"); const Key * typeMeta = keyGetMeta (key, "check/validation/type"); int lineValidation = 0; int wordValidation = 0; int icaseValidation = 0; int invertValidation = 0; if (icaseMeta) icaseValidation = 1; if (invertMeta) invertValidation = 1; if (matchMeta) { char * matchCopy = elektraStrDup (keyString (matchMeta)); char * ptr = matchCopy; while (*ptr) { *ptr = toupper (*ptr); ++ptr; } if (!strcmp (matchCopy, "LINE")) lineValidation = 1; if (!strcmp (matchCopy, "WORD")) wordValidation = 1; if (!strcmp (matchCopy, "ANY")) { lineValidation = 0; wordValidation = 0; } elektraFree (matchCopy); } int cflags = REG_NOSUB | REG_EXTENDED; if (icaseValidation) cflags |= REG_ICASE; if (lineValidation) cflags |= REG_NEWLINE; if (typeMeta) { char * typeCopy = elektraStrDup (keyString (typeMeta)); char * ptr = typeCopy; while (*ptr) { *ptr = toupper (*ptr); ++ptr; } if (!strcmp (typeCopy, "ERE")) cflags |= REG_EXTENDED; else if (!strcmp (typeCopy, "BRE")) cflags &= REG_EXTENDED; elektraFree (typeCopy); } char * regexString = NULL; int freeString = 0; if (lineValidation || wordValidation) { regexString = elektraMalloc (keyGetValueSize (regexMeta) + 2); freeString = 1; sprintf (regexString, "^%s$", keyString (regexMeta)); } else { regexString = (char *) keyString (regexMeta); } regex_t regex; regmatch_t offsets; int ret = regcomp (&regex, regexString, cflags); if (ret != 0) { char buffer[1000]; regerror (ret, &regex, buffer, 999); ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (parentKey, "Could not compile regex '%s' of the key '%s'. Reason: %s", keyString (regexMeta), keyName (key), buffer); regfree (&regex); if (freeString) elektraFree (regexString); return 0; } int match = 0; if (!wordValidation) { ret = regexec (&regex, keyString (key), 1, &offsets, 0); if (ret == 0) match = 1; } else { char * savePtr; char * token; char * string = (char *) keyString (key); while ((token = strtok_r (string, " \t\n", &savePtr)) != NULL) { ret = regexec (&regex, token, 1, &offsets, 0); if (ret == 0) { match = 1; break; } string = NULL; } } if (invertValidation) match = !match; if (!match) { const Key * msg = keyGetMeta (key, "check/validation/message"); if (msg) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (parentKey, "The key '%s' with value '%s' does not confirm to '%s'. Reason: %s", keyName (key), keyString (key), regexString, keyString (msg)); regfree (&regex); if (freeString) elektraFree (regexString); return 0; } else { char buffer[1000]; regerror (ret, &regex, buffer, 999); ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (parentKey, "The key '%s' with value '%s' does not confirm to '%s'. Reason: %s", keyName (key), keyString (key), regexString, buffer); regfree (&regex); if (freeString) elektraFree (regexString); return 0; } } regfree (&regex); if (freeString) elektraFree (regexString); return 1; } int elektraValidationSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { for (elektraCursor it = 0; it < ksGetSize (returned); ++it) { Key * cur = ksAtCursor (returned, it); const Key * regexMeta = keyGetMeta (cur, "check/validation"); if (!regexMeta) continue; int rc = validateKey (cur, parentKey); if (!rc) return -1; } return 1; /* success */ } Plugin * ELEKTRA_PLUGIN_EXPORT { // clang-format off return elektraPluginExport("validation", ELEKTRA_PLUGIN_GET, &elektraValidationGet, ELEKTRA_PLUGIN_SET, &elektraValidationSet, ELEKTRA_PLUGIN_END); }
33cd2634ac79d3189829fcf3cff786b601903957
487c8455b34e2b312da42bf8a43162aa5c5027df
/Target/Demo/ARMCM4_S32K14_S32K144EVB_GCC/Boot/main.c
0d5397d2f9c0aadb9dfaa17429aa26472e6d6d7a
[]
no_license
feaser/openblt
bf3a72e7beb998cb635a67db85fa68100d048bb8
57b517eabeb37d945606e18736e106bde34010bc
refs/heads/master
2023-08-31T23:54:09.030534
2023-07-07T10:29:56
2023-07-07T10:29:56
102,110,352
534
236
null
2023-09-14T11:11:56
2017-09-01T12:26:08
C
UTF-8
C
false
false
8,934
c
main.c
/************************************************************************************//** * \file Demo/ARMCM4_S32K14_S32K144EVB_GCC/Boot/main.c * \brief Bootloader application source file. * \ingroup Boot_ARMCM4_S32K14_S32K144EVB_GCC * \internal *---------------------------------------------------------------------------------------- * C O P Y R I G H T *---------------------------------------------------------------------------------------- * Copyright (c) 2020 by Feaser http://www.feaser.com All rights reserved * *---------------------------------------------------------------------------------------- * L I C E N S E *---------------------------------------------------------------------------------------- * This file is part of OpenBLT. OpenBLT 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. * * OpenBLT 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 have received a copy of the GNU General Public License along with OpenBLT. It * should be located in ".\Doc\license.html". If not, contact Feaser to obtain a copy. * * \endinternal ****************************************************************************************/ /**************************************************************************************** * Include files ****************************************************************************************/ #include "boot.h" /* bootloader generic header */ #include "device_registers.h" /* device registers */ #include "system_S32K144.h" /* device sconfiguration */ /**************************************************************************************** * Function prototypes ****************************************************************************************/ static void Init(void); static void SystemClockConfig(void); /************************************************************************************//** ** \brief This is the entry point for the bootloader application and is called ** by the reset interrupt vector after the C-startup routines executed. ** \return Program return code. ** ****************************************************************************************/ int main(void) { /* Initialize the microcontroller. */ Init(); /* Initialize the bootloader. */ BootInit(); /* Start the infinite program loop. */ while (1) { /* Run the bootloader task. */ BootTask(); } /* Program should never get here. */ return 0; } /*** end of main ***/ /************************************************************************************//** ** \brief Initializes the microcontroller. ** \return none. ** ****************************************************************************************/ static void Init(void) { /* Configure the system clock. */ SystemClockConfig(); /* Enable the peripheral clock for the ports that are used. */ PCC->PCCn[PCC_PORTC_INDEX] |= PCC_PCCn_CGC_MASK; PCC->PCCn[PCC_PORTD_INDEX] |= PCC_PCCn_CGC_MASK; PCC->PCCn[PCC_PORTE_INDEX] |= PCC_PCCn_CGC_MASK; /* Configure SW2 (PC12) GPIO pin for (optional) backdoor entry input. */ /* Input GPIO pin configuration. PC12 = GPIO, MUX = ALT1. */ PORTC->PCR[12] |= PORT_PCR_MUX(1); /* Disable pull device, as SW2 already has a pull down resistor on the board. */ PORTC->PCR[12] &= ~PORT_PCR_PE(1); /* Configure and enable Port C pin 12 GPIO as digital input */ PTC->PDDR &= ~GPIO_PDDR_PDD(1 << 12U); PTC->PIDR &= ~GPIO_PIDR_PID(1 << 12U); #if (BOOT_COM_RS232_ENABLE > 0) /* UART RX GPIO pin configuration. PC6 = UART1 RX, MUX = ALT2. */ PORTC->PCR[6] |= PORT_PCR_MUX(2); /* UART TX GPIO pin configuration. PC7 = UART1 TX, MUX = ALT2. */ PORTC->PCR[7] |= PORT_PCR_MUX(2); #endif #if (BOOT_COM_CAN_ENABLE > 0) /* CAN RX GPIO pin configuration. PE4 = CAN0 RX, MUX = ALT5. */ PORTE->PCR[4] |= PORT_PCR_MUX(5); /* CAN TX GPIO pin configuration. PE5 = CAN0 TX, MUX = ALT5. */ PORTE->PCR[5] |= PORT_PCR_MUX(5); #endif } /*** end of Init ***/ /************************************************************************************//** ** \brief System Clock Configuration. This code was derived from a S32 Design Studio ** example program. It uses the 8 MHz external crystal as a source for the ** PLL and configures the normal RUN mode for the following clock settings: ** - SPLL_CLK = 160 MHz ** - CORE_CLK = 80 MHz ** - SYS_CLK = 80 MHz ** - BUS_CLK = 40 MHz ** - FLASH_CLK = 26.67 MHz ** - SIRCDIV1_CLK = 8 MHz ** - SIRCDIV2_CLK = 8 MHz ** \return none. ** ****************************************************************************************/ static void SystemClockConfig(void) { /* --------- SOSC Initialization (8 MHz) ------------------------------------------- */ /* SOSCDIV1 & SOSCDIV2 =1: divide by 1. */ SCG->SOSCDIV = SCG_SOSCDIV_SOSCDIV1(1) | SCG_SOSCDIV_SOSCDIV2(1); /* Range=2: Medium freq (SOSC betw 1MHz-8MHz). * HGO=0: Config xtal osc for low power. * EREFS=1: Input is external XTAL. */ SCG->SOSCCFG = SCG_SOSCCFG_RANGE(2) | SCG_SOSCCFG_EREFS_MASK; /* Ensure SOSCCSR unlocked. */ while (SCG->SOSCCSR & SCG_SOSCCSR_LK_MASK) { ; } /* LK=0: SOSCCSR can be written. * SOSCCMRE=0: OSC CLK monitor IRQ if enabled. * SOSCCM=0: OSC CLK monitor disabled. * SOSCERCLKEN=0: Sys OSC 3V ERCLK output clk disabled. * SOSCLPEN=0: Sys OSC disabled in VLP modes. * SOSCSTEN=0: Sys OSC disabled in Stop modes. * SOSCEN=1: Enable oscillator. */ SCG->SOSCCSR = SCG_SOSCCSR_SOSCEN_MASK; /* Wait for system OSC clock to become valid. */ while (!(SCG->SOSCCSR & SCG_SOSCCSR_SOSCVLD_MASK)) { ; } /* --------- SPLL Initialization (160 MHz) ----------------------------------------- */ /* Ensure SPLLCSR is unlocked. */ while (SCG->SPLLCSR & SCG_SPLLCSR_LK_MASK) { ; } /* SPLLEN=0: SPLL is disabled (default). */ SCG->SPLLCSR &= ~SCG_SPLLCSR_SPLLEN_MASK; /* SPLLDIV1 divide by 2 and SPLLDIV2 divide by 4. */ SCG->SPLLDIV |= SCG_SPLLDIV_SPLLDIV1(2) | SCG_SPLLDIV_SPLLDIV2(3); /* PREDIV=0: Divide SOSC_CLK by 0+1=1. * MULT=24: Multiply sys pll by 4+24=40. * SPLL_CLK = 8MHz / 1 * 40 / 2 = 160 MHz. */ SCG->SPLLCFG = SCG_SPLLCFG_MULT(24); /* Ensure SPLLCSR is unlocked. */ while (SCG->SPLLCSR & SCG_SPLLCSR_LK_MASK) { ; } /* LK=0: SPLLCSR can be written. * SPLLCMRE=0: SPLL CLK monitor IRQ if enabled. * SPLLCM=0: SPLL CLK monitor disabled. * SPLLSTEN=0: SPLL disabled in Stop modes. * SPLLEN=1: Enable SPLL. */ SCG->SPLLCSR |= SCG_SPLLCSR_SPLLEN_MASK; /* Wait for SPLL to become valid. */ while (!(SCG->SPLLCSR & SCG_SPLLCSR_SPLLVLD_MASK)) { ; } /* --------- SIRC Initialization --------------------------------------------------- */ /* Slow IRC is enabled with high range (8 MHz) in reset. Enable SIRCDIV2_CLK and * SIRCDIV1_CLK, divide by 1 = 8MHz asynchronous clock source. */ SCG->SIRCDIV = SCG_SIRCDIV_SIRCDIV1(1) | SCG_SIRCDIV_SIRCDIV2(1); /* --------- Change to normal RUN mode with 8MHz SOSC, 80 MHz PLL ------------------ */ /* Note that flash memory should not be programmed or erased when the microcontroller * is operating in VLPr or HSRUN mode. Therefore normal RUN mode is configured. */ /* Select PLL as clock source. * DIVCORE=1, div. by 2: Core clock = 160/2 MHz = 80 MHz. * DIVBUS=1, div. by 2: bus clock = 40 MHz. * DIVSLOW=2, div. by 2: SCG slow, flash clock= 26 2/3 MHz. */ SCG->RCCR= SCG_RCCR_SCS(6) | SCG_RCCR_DIVCORE(1) | SCG_RCCR_DIVBUS(1) | SCG_RCCR_DIVSLOW(2); /* Wait until system clock source is SPLL. */ while (((SCG->CSR & SCG_CSR_SCS_MASK) >> SCG_CSR_SCS_SHIFT ) != 6U) { ; } /* Evaluate the clock register settings and calculates the current core clock. This * function must be called when the clock manager component is not used. */ SystemCoreClockUpdate(); } /*** end of SystemClockConfig ***/ /*********************************** end of main.c *************************************/
b35c03dfd1083b508ae41af1d9fcf34ae87549d8
8838eb997879add5759b6dfb23f9a646464e53ca
/src/compat/linux/include/linux/rbtree.h
374866835a596587bcc4cc1f8c38c4586e3415c6
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
1,376
h
rbtree.h
/** * @file * @brief * * @date 01.08.2013 * @author Andrey Gazukin */ #ifndef _LINUX_RBTREE_H #define _LINUX_RBTREE_H struct rb_node { struct rb_node *rb_left; /* left element */ struct rb_node *rb_right; /* right element */ struct rb_node *rb_parent; /* parent element */ int rb_color; /* node color */ }; struct rb_root { struct rb_node *rb_node; /* root of the tree */ }; #define NULL ((void *)0) #define RB_ROOT ((struct rb_root){NULL}) #define rb_entry(p, container, field) \ ((container *) ((char *)p - ((char *)&(((container *)0)->field)))) #define RB_BLACK 0 #define RB_RED 1 extern void rb_insert_color(struct rb_node *, struct rb_root *); extern void rb_erase(struct rb_node *, struct rb_root *); /* Find logical next and previous nodes in a tree */ extern struct rb_node *rb_next(struct rb_node *); extern struct rb_node *rb_prev(struct rb_node *); extern struct rb_node *rb_first(struct rb_root *); /* Fast replacement of a single node without remove/rebalance/add/rebalance */ extern void rb_replace_node(struct rb_node *victim, struct rb_node *new, struct rb_root *root); static inline void rb_link_node(struct rb_node * node, struct rb_node * parent, struct rb_node ** rb_link) { node->rb_parent = parent; node->rb_color = RB_RED; node->rb_left = node->rb_right = NULL; *rb_link = node; } #endif /* _LINUX_RBTREE_H */
dec0b7225bebe7c1ce01652860ff64a4f6aa6c61
675d31c0346323f7e2b0ac2438d4b7cb352d414a
/kernel/tkernel/eventflag.c
584e92b007979135ae0916910ec414c6ccd0a7b5
[]
no_license
tron-forum/mtkernel_3
04688868b7c20605407ee65e1204c177abd4fb39
308092c361b6f91621874083fad637ebcac7466a
refs/heads/master
2023-04-07T13:01:44.475830
2022-10-17T08:40:05
2022-10-17T08:40:05
227,035,186
145
30
null
2023-03-14T05:28:39
2019-12-10T05:20:05
C
UTF-8
C
false
false
8,163
c
eventflag.c
/* *---------------------------------------------------------------------- * micro T-Kernel 3.00.00 * * Copyright (C) 2006-2019 by Ken Sakamura. * This software is distributed under the T-License 2.1. *---------------------------------------------------------------------- * * Released by TRON Forum(http://www.tron.org) at 2019/12/11. * *---------------------------------------------------------------------- */ /* * eventflag.c * Event Flag */ #include "kernel.h" #include "wait.h" #include "check.h" #include "eventflag.h" #if USE_EVENTFLAG == 1 Noinit(EXPORT FLGCB knl_flgcb_table[NUM_FLGID]); /* Event flag control block */ Noinit(EXPORT QUEUE knl_free_flgcb); /* FreeQue */ /* * Initialization of event flag control block */ EXPORT ER knl_eventflag_initialize( void ) { FLGCB *flgcb, *end; /* Get system information */ if ( NUM_FLGID < 1 ) { return E_SYS; } /* Register all control blocks onto FreeQue */ QueInit(&knl_free_flgcb); end = knl_flgcb_table + NUM_FLGID; for ( flgcb = knl_flgcb_table; flgcb < end; flgcb++ ) { flgcb->flgid = 0; QueInsert(&flgcb->wait_queue, &knl_free_flgcb); } return E_OK; } /* * Create event flag */ SYSCALL ID tk_cre_flg( CONST T_CFLG *pk_cflg ) { #if CHK_RSATR const ATR VALID_FLGATR = { TA_TPRI |TA_WMUL #if USE_OBJECT_NAME |TA_DSNAME #endif }; #endif FLGCB *flgcb; ID flgid; ER ercd; CHECK_RSATR(pk_cflg->flgatr, VALID_FLGATR); BEGIN_CRITICAL_SECTION; /* Get control block from FreeQue */ flgcb = (FLGCB*)QueRemoveNext(&knl_free_flgcb); if ( flgcb == NULL ) { ercd = E_LIMIT; } else { flgid = ID_FLG(flgcb - knl_flgcb_table); /* Initialize control block */ QueInit(&flgcb->wait_queue); flgcb->flgid = flgid; flgcb->exinf = pk_cflg->exinf; flgcb->flgatr = pk_cflg->flgatr; flgcb->flgptn = pk_cflg->iflgptn; #if USE_OBJECT_NAME if ( (pk_cflg->flgatr & TA_DSNAME) != 0 ) { knl_strncpy((char*)flgcb->name, (char*)pk_cflg->dsname, OBJECT_NAME_LENGTH); } #endif ercd = flgid; } END_CRITICAL_SECTION; return ercd; } #ifdef USE_FUNC_TK_DEL_FLG /* * Delete event flag */ SYSCALL ER tk_del_flg( ID flgid ) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_CRITICAL_SECTION; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; } else { /* Release wait state of task (E_DLT) */ knl_wait_delete(&flgcb->wait_queue); /* Return to FreeQue */ QueInsert(&flgcb->wait_queue, &knl_free_flgcb); flgcb->flgid = 0; } END_CRITICAL_SECTION; return ercd; } #endif /* USE_FUNC_TK_DEL_FLG */ /* * Event flag set */ SYSCALL ER tk_set_flg( ID flgid, UINT setptn ) { FLGCB *flgcb; TCB *tcb; QUEUE *queue; UINT wfmode, waiptn; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_CRITICAL_SECTION; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; goto error_exit; } /* Set event flag */ flgcb->flgptn |= setptn; /* Search task which should be released */ queue = flgcb->wait_queue.next; while ( queue != &flgcb->wait_queue ) { tcb = (TCB*)queue; queue = queue->next; /* Meet condition for release wait? */ waiptn = tcb->winfo.flg.waiptn; wfmode = tcb->winfo.flg.wfmode; if ( knl_eventflag_cond(flgcb, waiptn, wfmode) ) { /* Release wait */ *tcb->winfo.flg.p_flgptn = flgcb->flgptn; knl_wait_release_ok(tcb); /* Clear event flag */ if ( (wfmode & TWF_BITCLR) != 0 ) { if ( (flgcb->flgptn &= ~waiptn) == 0 ) { break; } } if ( (wfmode & TWF_CLR) != 0 ) { flgcb->flgptn = 0; break; } } } error_exit: END_CRITICAL_SECTION; return ercd; } /* * Clear event flag */ SYSCALL ER tk_clr_flg( ID flgid, UINT clrptn ) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_CRITICAL_SECTION; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; } else { flgcb->flgptn &= clrptn; } END_CRITICAL_SECTION; return ercd; } /* * Processing if the priority of wait task changes */ LOCAL void flg_chg_pri( TCB *tcb, INT oldpri ) { FLGCB *flgcb; flgcb = get_flgcb(tcb->wid); knl_gcb_change_priority((GCB*)flgcb, tcb); } /* * Definition of event flag wait specification */ LOCAL CONST WSPEC knl_wspec_flg_tfifo = { TTW_FLG, NULL, NULL }; LOCAL CONST WSPEC knl_wspec_flg_tpri = { TTW_FLG, flg_chg_pri, NULL }; /* * Event flag wait */ SYSCALL ER tk_wai_flg( ID flgid, UINT waiptn, UINT wfmode, UINT *p_flgptn, TMO tmout ) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(flgid); CHECK_PAR(waiptn != 0); CHECK_PAR((wfmode & ~(TWF_ORW|TWF_CLR|TWF_BITCLR)) == 0); CHECK_TMOUT(tmout); CHECK_DISPATCH(); flgcb = get_flgcb(flgid); BEGIN_CRITICAL_SECTION; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; goto error_exit; } if ( (flgcb->flgatr & TA_WMUL) == 0 && !isQueEmpty(&flgcb->wait_queue) ) { /* Disable multiple tasks wait */ ercd = E_OBJ; goto error_exit; } /* Meet condition for release wait? */ if ( knl_eventflag_cond(flgcb, waiptn, wfmode) ) { *p_flgptn = flgcb->flgptn; /* Clear event flag */ if ( (wfmode & TWF_BITCLR) != 0 ) { flgcb->flgptn &= ~waiptn; } if ( (wfmode & TWF_CLR) != 0 ) { flgcb->flgptn = 0; } } else { /* Ready for wait */ knl_ctxtsk->wspec = ( (flgcb->flgatr & TA_TPRI) != 0 )? &knl_wspec_flg_tpri: &knl_wspec_flg_tfifo; knl_ctxtsk->wercd = &ercd; knl_ctxtsk->winfo.flg.waiptn = waiptn; knl_ctxtsk->winfo.flg.wfmode = wfmode; knl_ctxtsk->winfo.flg.p_flgptn = p_flgptn; knl_gcb_make_wait((GCB*)flgcb, tmout); } error_exit: END_CRITICAL_SECTION; return ercd; } #ifdef USE_FUNC_TK_REF_FLG /* * Check event flag state */ SYSCALL ER tk_ref_flg( ID flgid, T_RFLG *pk_rflg ) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_CRITICAL_SECTION; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; } else { pk_rflg->exinf = flgcb->exinf; pk_rflg->wtsk = knl_wait_tskid(&flgcb->wait_queue); pk_rflg->flgptn = flgcb->flgptn; } END_CRITICAL_SECTION; return ercd; } #endif /* USE_FUNC_TK_REF_FLG */ /* ------------------------------------------------------------------------ */ /* * Debugger support function */ #if USE_DBGSPT #if USE_OBJECT_NAME /* * Get object name from control block */ EXPORT ER knl_eventflag_getname(ID id, UB **name) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(id); BEGIN_DISABLE_INTERRUPT; flgcb = get_flgcb(id); if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; goto error_exit; } if ( (flgcb->flgatr & TA_DSNAME) == 0 ) { ercd = E_OBJ; goto error_exit; } *name = flgcb->name; error_exit: END_DISABLE_INTERRUPT; return ercd; } #endif /* USE_OBJECT_NAME */ #ifdef USE_FUNC_TD_LST_FLG /* * Refer event flag usage state */ SYSCALL INT td_lst_flg( ID list[], INT nent ) { FLGCB *flgcb, *end; INT n = 0; BEGIN_DISABLE_INTERRUPT; end = knl_flgcb_table + NUM_FLGID; for ( flgcb = knl_flgcb_table; flgcb < end; flgcb++ ) { if ( flgcb->flgid == 0 ) { continue; } if ( n++ < nent ) { *list++ = flgcb->flgid; } } END_DISABLE_INTERRUPT; return n; } #endif /* USE_FUNC_TD_LST_FLG */ #ifdef USE_FUNC_TD_REF_FLG /* * Refer event flag state */ SYSCALL ER td_ref_flg( ID flgid, TD_RFLG *pk_rflg ) { FLGCB *flgcb; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_DISABLE_INTERRUPT; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; } else { pk_rflg->exinf = flgcb->exinf; pk_rflg->wtsk = knl_wait_tskid(&flgcb->wait_queue); pk_rflg->flgptn = flgcb->flgptn; } END_DISABLE_INTERRUPT; return ercd; } #endif /* USE_FUNC_TD_REF_FLG */ #ifdef USE_FUNC_TD_FLG_QUE /* * Refer event flag wait queue */ SYSCALL INT td_flg_que( ID flgid, ID list[], INT nent ) { FLGCB *flgcb; QUEUE *q; ER ercd = E_OK; CHECK_FLGID(flgid); flgcb = get_flgcb(flgid); BEGIN_DISABLE_INTERRUPT; if ( flgcb->flgid == 0 ) { ercd = E_NOEXS; } else { INT n = 0; for ( q = flgcb->wait_queue.next; q != &flgcb->wait_queue; q = q->next ) { if ( n++ < nent ) { *list++ = ((TCB*)q)->tskid; } } ercd = n; } END_DISABLE_INTERRUPT; return ercd; } #endif /* USE_FUNC_TD_FLG_QUE */ #endif /* USE_DBGSPT */ #endif /* USE_EVENTFLAG */
763e072be9ab97f49d11f1954936178267d833b8
e9911598c43e8526da22b2773a73d9b5966f602a
/imap/dav_db.c
b17a258007b8d2579e13770e3dd0814637a3ae49
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
cyrusimap/cyrus-imapd
07236dfd887ed92c147938cf1ed2591449d7e8fd
315441d067ba85814768f840f20bc3bb7f20ea6b
refs/heads/master
2023-09-05T09:57:10.683822
2023-09-05T06:09:43
2023-09-05T06:09:43
59,071,965
508
164
NOASSERTION
2023-09-13T04:34:31
2016-05-18T01:33:49
C
UTF-8
C
false
false
26,169
c
dav_db.c
/* dav_db.c -- implementation of per-user DAV database * * Copyright (c) 1994-2012 Carnegie Mellon University. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The name "Carnegie Mellon University" must not be used to * endorse or promote products derived from this software without * prior written permission. For permission or any legal * details, please contact * Carnegie Mellon University * Center for Technology Transfer and Enterprise Creation * 4615 Forbes Avenue * Suite 302 * Pittsburgh, PA 15213 * (412) 268-7393, fax: (412) 268-7395 * innovation@andrew.cmu.edu * * 4. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Computing Services * at Carnegie Mellon University (http://www.cmu.edu/computing/)." * * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include <config.h> #include <stdlib.h> #include <syslog.h> #include <string.h> #include <errno.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include "assert.h" #include "caldav_alarm.h" #include "cyrusdb.h" #include "dav_db.h" #include "global.h" #include "sieve_db.h" #include "user.h" #include "util.h" #include "xmalloc.h" #include "xunlink.h" /* generated headers are not necessarily in current directory */ #include "imap/imap_err.h" #define CMD_CREATE_CAL \ "CREATE TABLE IF NOT EXISTS ical_objs (" \ " rowid INTEGER PRIMARY KEY," \ " creationdate INTEGER," \ " mailbox TEXT NOT NULL," \ " resource TEXT NOT NULL," \ " imap_uid INTEGER," \ " modseq INTEGER," \ " createdmodseq INTEGER," \ " lock_token TEXT," \ " lock_owner TEXT," \ " lock_ownerid TEXT," \ " lock_expire INTEGER," \ " comp_type INTEGER," \ " ical_uid TEXT," \ " organizer TEXT," \ " dtstart TEXT," \ " dtend TEXT," \ " comp_flags INTEGER," \ " sched_tag TEXT," \ " alive INTEGER," \ " UNIQUE( mailbox, imap_uid )," \ " UNIQUE( mailbox, resource ) );" \ "CREATE INDEX IF NOT EXISTS idx_ical_uid ON ical_objs ( ical_uid );" #define CMD_CREATE_JSCALOBJS \ "CREATE TABLE IF NOT EXISTS jscal_objs (" \ " rowid INTEGER NOT NULL," \ " ical_recurid TEXT NOT NULL DEFAULT ''," \ " modseq INTEGER NOT NULL," \ " createdmodseq INTEGER NOT NULL," \ " dtstart TEXT NOT NULL," \ " dtend TEXT NOT NULL," \ " alive INTEGER NOT NULL," \ " ical_guid TEXT NOT NULL," \ " PRIMARY KEY (rowid, ical_recurid)" \ " FOREIGN KEY (rowid) REFERENCES ical_objs (rowid) ON DELETE CASCADE );" #define CMD_CREATE_CARD \ "CREATE TABLE IF NOT EXISTS vcard_objs (" \ " rowid INTEGER PRIMARY KEY," \ " creationdate INTEGER," \ " mailbox TEXT NOT NULL," \ " resource TEXT NOT NULL," \ " imap_uid INTEGER," \ " modseq INTEGER," \ " createdmodseq INTEGER," \ " lock_token TEXT," \ " lock_owner TEXT," \ " lock_ownerid TEXT," \ " lock_expire INTEGER," \ " version INTEGER," \ " vcard_uid TEXT," \ " kind INTEGER," \ " fullname TEXT," \ " name TEXT," \ " nickname TEXT," \ " alive INTEGER," \ " UNIQUE( mailbox, imap_uid )," \ " UNIQUE( mailbox, resource ) );" \ "CREATE INDEX IF NOT EXISTS idx_vcard_fn ON vcard_objs ( fullname );" \ "CREATE INDEX IF NOT EXISTS idx_vcard_uid ON vcard_objs ( vcard_uid );" #define CMD_CREATE_EM \ "CREATE TABLE IF NOT EXISTS vcard_emails (" \ " rowid INTEGER PRIMARY KEY," \ " objid INTEGER," \ " pos INTEGER NOT NULL," /* for sorting */ \ " email TEXT NOT NULL COLLATE NOCASE," \ " ispref INTEGER NOT NULL DEFAULT 0," \ " ispinned INTEGER NOT NULL DEFAULT 0," \ " FOREIGN KEY (objid) REFERENCES vcard_objs (rowid) ON DELETE CASCADE );" \ "CREATE INDEX IF NOT EXISTS idx_vcard_email ON vcard_emails ( email COLLATE NOCASE );" #define CMD_CREATE_GR \ "CREATE TABLE IF NOT EXISTS vcard_groups (" \ " rowid INTEGER PRIMARY KEY," \ " objid INTEGER," \ " pos INTEGER NOT NULL," /* for sorting */ \ " member_uid TEXT NOT NULL," \ " otheruser TEXT NOT NULL DEFAULT \"\"," \ " FOREIGN KEY (objid) REFERENCES vcard_objs (rowid) ON DELETE CASCADE );" #define CMD_CREATE_OBJS \ "CREATE TABLE IF NOT EXISTS dav_objs (" \ " rowid INTEGER PRIMARY KEY," \ " creationdate INTEGER," \ " mailbox TEXT NOT NULL," \ " resource TEXT NOT NULL," \ " imap_uid INTEGER," \ " modseq INTEGER," \ " createdmodseq INTEGER," \ " lock_token TEXT," \ " lock_owner TEXT," \ " lock_ownerid TEXT," \ " lock_expire INTEGER," \ " filename TEXT," \ " type TEXT," \ " subtype TEXT," \ " res_uid TEXT," \ " ref_count INTEGER," \ " alive INTEGER," \ " UNIQUE( mailbox, imap_uid )," \ " UNIQUE( mailbox, resource ) );" \ // dropped in version 12 #define CMD_CREATE_CALCACHE \ "CREATE TABLE IF NOT EXISTS ical_jmapcache (" \ " rowid INTEGER NOT NULL," \ " userid TEXT NOT NULL," \ " jmapversion INTEGER NOT NULL," \ " jmapdata TEXT NOT NULL," \ " PRIMARY KEY (rowid, userid)" \ " FOREIGN KEY (rowid) REFERENCES ical_objs (rowid) ON DELETE CASCADE );" #define CMD_CREATE_JSCALCACHE \ "CREATE TABLE IF NOT EXISTS jscal_cache (" \ " rowid INTEGER NOT NULL," \ " ical_recurid TEXT NOT NULL," \ " userid TEXT NOT NULL," \ " version INTEGER NOT NULL," \ " data TEXT NOT NULL," \ " PRIMARY KEY (rowid, ical_recurid, userid)" \ " FOREIGN KEY (rowid, ical_recurid) REFERENCES jscal_objs (rowid, ical_recurid) ON DELETE CASCADE );" #define CMD_CREATE_CARDCACHE \ "CREATE TABLE IF NOT EXISTS vcard_jmapcache (" \ " rowid INTEGER NOT NULL PRIMARY KEY," \ " jmapversion INTEGER NOT NULL," \ " jmapdata TEXT NOT NULL," \ " FOREIGN KEY (rowid) REFERENCES vcard_objs (rowid) ON DELETE CASCADE );" #define CMD_CREATE_SIEVE \ "CREATE TABLE IF NOT EXISTS sieve_scripts (" \ " rowid INTEGER PRIMARY KEY," \ " creationdate INTEGER," \ " lastupdated INTEGER," \ " mailbox TEXT NOT NULL," \ " imap_uid INTEGER," \ " modseq INTEGER," \ " createdmodseq INTEGER," \ " id TEXT NOT NULL," \ " name TEXT NOT NULL," \ " contentid TEXT NOT NULL," \ " isactive INTEGER," \ " alive INTEGER," \ " UNIQUE( mailbox, imap_uid )," \ " UNIQUE( id ) );" \ "CREATE INDEX IF NOT EXISTS idx_sieve_name ON sieve_scripts ( name );" #define CMD_CREATE CMD_CREATE_CAL CMD_CREATE_CARD CMD_CREATE_EM CMD_CREATE_GR \ CMD_CREATE_OBJS CMD_CREATE_CALCACHE CMD_CREATE_CARDCACHE \ CMD_CREATE_SIEVE CMD_CREATE_JSCALOBJS CMD_CREATE_JSCALCACHE /* leaves these unused columns around, but that's life. A dav_reconstruct * will fix them */ #define CMD_DBUPGRADEv2 \ "ALTER TABLE ical_objs ADD COLUMN comp_flags INTEGER;" \ "UPDATE ical_objs SET comp_flags = recurring + 2 * transp;" #define CMD_DBUPGRADEv3 \ "ALTER TABLE ical_objs ADD COLUMN modseq INTEGER;" \ "UPDATE ical_objs SET modseq = 1;" \ "ALTER TABLE vcard_objs ADD COLUMN modseq INTEGER;" \ "UPDATE vcard_objs SET modseq = 1;" #define CMD_DBUPGRADEv4 \ "ALTER TABLE ical_objs ADD COLUMN alive INTEGER;" \ "UPDATE ical_objs SET alive = 1;" \ "ALTER TABLE vcard_objs ADD COLUMN alive INTEGER;" \ "UPDATE vcard_objs SET alive = 1;" #define CMD_DBUPGRADEv5 \ "ALTER TABLE vcard_emails ADD COLUMN ispref INTEGER NOT NULL DEFAULT 0;" \ "ALTER TABLE vcard_groups ADD COLUMN otheruser TEXT NOT NULL DEFAULT \"\";" #define CMD_DBUPGRADEv6 CMD_CREATE_OBJS #define CMD_DBUPGRADEv7 \ "ALTER TABLE ical_objs ADD COLUMN createdmodseq INTEGER;" \ "UPDATE ical_objs SET createdmodseq = 0;" \ "ALTER TABLE vcard_objs ADD COLUMN createdmodseq INTEGER;" \ "UPDATE vcard_objs SET createdmodseq = 0;" \ "ALTER TABLE dav_objs ADD COLUMN createdmodseq INTEGER;" \ "UPDATE dav_objs SET createdmodseq = 0;" #define CMD_DBUPGRADEv8 \ "ALTER TABLE vcard_emails ADD COLUMN ispinned INTEGER NOT NULL DEFAULT 0;" #define CMD_DBUPGRADEv9 CMD_CREATE_CALCACHE CMD_CREATE_CARDCACHE #define CMD_DBUPGRADEv10 \ "CREATE UNIQUE INDEX IF NOT EXISTS idx_ical_imapuid ON ical_objs ( mailbox, imap_uid );" \ "CREATE UNIQUE INDEX IF NOT EXISTS idx_vcard_imapuid ON vcard_objs ( mailbox, imap_uid );" \ "CREATE UNIQUE INDEX IF NOT EXISTS idx_object_imapuid ON dav_objs ( mailbox, imap_uid );" \ "DROP INDEX IF EXISTS idx_res_uid;" #define CMD_DBUPGRADEv14 CMD_CREATE_SIEVE #define CMD_DBUPGRADEv15 \ "DROP TABLE ical_jmapcache;" \ CMD_CREATE_JSCALOBJS CMD_CREATE_JSCALCACHE \ "INSERT INTO jscal_objs" \ " SELECT rowid, '', modseq, createdmodseq, dtstart, dtend, alive, '' FROM ical_objs;" static int sievedb_upgrade(sqldb_t *db); struct sqldb_upgrade davdb_upgrade[] = { { 2, CMD_DBUPGRADEv2, NULL }, { 3, CMD_DBUPGRADEv3, NULL }, { 4, CMD_DBUPGRADEv4, NULL }, { 5, CMD_DBUPGRADEv5, NULL }, { 6, CMD_DBUPGRADEv6, NULL }, { 7, CMD_DBUPGRADEv7, NULL }, { 8, CMD_DBUPGRADEv8, NULL }, { 9, CMD_DBUPGRADEv9, NULL }, { 10, CMD_DBUPGRADEv10, NULL }, /* Don't upgrade to version 11. We only jump to 11 on CREATE */ /* Don't upgrade to version 12. This was an intermediate Sieve DB version */ /* Don't upgrade to version 13. This was an intermediate Sieve DB version */ { 14, CMD_DBUPGRADEv14, &sievedb_upgrade }, { 15, CMD_DBUPGRADEv15, NULL }, { 0, NULL, NULL } }; #define DB_VERSION 15 static sqldb_t *reconstruct_db; /* Create filename corresponding to DAV DB for mailbox */ EXPORTED void dav_getpath(struct buf *fname, struct mailbox *mailbox) { char *userid = mboxname_to_userid(mailbox_name(mailbox)); if (userid) dav_getpath_byuserid(fname, userid); else buf_setcstr(fname, mailbox_meta_fname(mailbox, META_DAV)); free(userid); } /* Create filename corresponding to DAV DB for userid */ EXPORTED void dav_getpath_byuserid(struct buf *fname, const char *userid) { char *path = user_hash_meta(userid, FNAME_DAVSUFFIX); buf_setcstr(fname, path); free(path); } EXPORTED sqldb_t *dav_open_userid(const char *userid) { if (reconstruct_db) return reconstruct_db; sqldb_t *db = NULL; struct buf fname = BUF_INITIALIZER; dav_getpath_byuserid(&fname, userid); db = sqldb_open(buf_cstring(&fname), CMD_CREATE, DB_VERSION, davdb_upgrade, config_getduration(IMAPOPT_DAV_LOCK_TIMEOUT, 's') * 1000); buf_free(&fname); return db; } EXPORTED sqldb_t *dav_open_mailbox(struct mailbox *mailbox) { if (reconstruct_db) return reconstruct_db; sqldb_t *db = NULL; struct buf fname = BUF_INITIALIZER; dav_getpath(&fname, mailbox); db = sqldb_open(buf_cstring(&fname), CMD_CREATE, DB_VERSION, davdb_upgrade, config_getduration(IMAPOPT_DAV_LOCK_TIMEOUT, 's') * 1000); buf_free(&fname); return db; } EXPORTED int dav_attach_userid(sqldb_t *db, const char *userid) { assert (!reconstruct_db); struct buf fname = BUF_INITIALIZER; dav_getpath_byuserid(&fname, userid); int r = sqldb_attach(db, buf_cstring(&fname)); buf_free(&fname); return r; } EXPORTED int dav_attach_mailbox(sqldb_t *db, struct mailbox *mailbox) { assert (!reconstruct_db); struct buf fname = BUF_INITIALIZER; dav_getpath(&fname, mailbox); int r = sqldb_attach(db, buf_cstring(&fname)); buf_free(&fname); return r; } EXPORTED int dav_close(sqldb_t **dbp) { if (reconstruct_db) return 0; return sqldb_close(dbp); } /* * mboxlist_usermboxtree() callback function to create DAV DB entries for a mailbox */ static int _dav_reconstruct_mb(const mbentry_t *mbentry, void *rock #ifndef WITH_JMAP __attribute__((unused)) #endif ) { #ifdef WITH_JMAP const char *userid = (const char *) rock; struct buf attrib = BUF_INITIALIZER; #endif int (*addproc)(struct mailbox *) = NULL; int writelock = 0; int r = 0; signals_poll(); switch (mbtype_isa(mbentry->mbtype)) { #ifdef WITH_DAV case MBTYPE_CALENDAR: case MBTYPE_COLLECTION: case MBTYPE_ADDRESSBOOK: addproc = &mailbox_add_dav; writelock = 1; // write lock so we can delete stale index records break; #endif #ifdef USE_SIEVE case MBTYPE_SIEVE: addproc = &mailbox_add_sieve; break; #endif #ifdef WITH_JMAP case MBTYPE_JMAPSUBMIT: addproc = &mailbox_add_email_alarms; break; case MBTYPE_EMAIL: r = annotatemore_lookup(mbentry->name, "/specialuse", userid, &attrib); if (!r && buf_len(&attrib)) { strarray_t *specialuse = strarray_split(buf_cstring(&attrib), NULL, 0); if (strarray_find(specialuse, "\\Snoozed", 0) >= 0) { addproc = &mailbox_add_email_alarms; } strarray_free(specialuse); } buf_free(&attrib); break; #endif } if (addproc) { struct mailbox *mailbox = NULL; /* Open/lock header */ if (writelock) r = mailbox_open_iwl(mbentry->name, &mailbox); else r = mailbox_open_irl(mbentry->name, &mailbox); if (!r) r = addproc(mailbox); mailbox_close(&mailbox); } return r; } static void run_audit_tool(const char *tool, const char *userid, const char *srcdb, const char *dstdb) { pid_t pid = fork(); if (pid < 0) return; if (pid == 0) { /* child */ execl(tool, tool, "-C", config_filename, "-u", userid, srcdb, dstdb, (void *)NULL); exit(-1); } int status; while (waitpid(pid, &status, 0) < 0); } EXPORTED int dav_reconstruct_user(const char *userid, const char *audit_tool) { syslog(LOG_NOTICE, "dav_reconstruct_user: %s", userid); struct buf fname = BUF_INITIALIZER; dav_getpath_byuserid(&fname, userid); struct buf newfname = BUF_INITIALIZER; dav_getpath_byuserid(&newfname, userid); buf_printf(&newfname, ".NEW"); struct mboxlock *namespacelock = user_namespacelock(userid); int r = IMAP_IOERROR; reconstruct_db = sqldb_open(buf_cstring(&newfname), CMD_CREATE, DB_VERSION, davdb_upgrade, config_getduration(IMAPOPT_DAV_LOCK_TIMEOUT, 's') * 1000); if (reconstruct_db) { r = sqldb_begin(reconstruct_db, "reconstruct"); #ifdef WITH_DAV // make all the alarm updates to go this database too if (!r) r = caldav_alarm_set_reconstruct(reconstruct_db); #endif // reconstruct everything if (!r) r = mboxlist_usermboxtree(userid, NULL, _dav_reconstruct_mb, (void *) userid, 0); #ifdef WITH_DAV // make sure all the alarms are resolved if (!r) r = caldav_alarm_process(0, NULL, /*dryrun*/1); // commit events over to ther alarm database if we're keeping them if (!r && !audit_tool) r = caldav_alarm_commit_reconstruct(userid); else caldav_alarm_rollback_reconstruct(); #endif // and commit to this DB if (r) sqldb_rollback(reconstruct_db, "reconstruct"); else sqldb_commit(reconstruct_db, "reconstruct"); sqldb_close(&reconstruct_db); } /* this actually works before close according to the internets */ if (r) { syslog(LOG_ERR, "dav_reconstruct_user: %s FAILED %s", userid, error_message(r)); if (audit_tool) { printf("Not auditing %s, reconstruct failed %s\n", userid, error_message(r)); } xunlink(buf_cstring(&newfname)); } else { syslog(LOG_NOTICE, "dav_reconstruct_user: %s SUCCEEDED", userid); if (audit_tool) { run_audit_tool(audit_tool, userid, buf_cstring(&fname), buf_cstring(&newfname)); xunlink(buf_cstring(&newfname)); } else { rename(buf_cstring(&newfname), buf_cstring(&fname)); } } mboxname_release(&namespacelock); buf_free(&newfname); buf_free(&fname); return 0; } struct sievedb_upgrade_rock { char *mboxname; strarray_t *sha1; }; static int sievedb_upgrade_cb(sqlite3_stmt *stmt, void *rock) { struct sievedb_upgrade_rock *srock = (struct sievedb_upgrade_rock *) rock; if (!srock->mboxname) { srock->mboxname = xstrdup((const char *) sqlite3_column_text(stmt, 0)); } if (srock->sha1) { const char *content = (const char *) sqlite3_column_text(stmt, 1); unsigned rowid = sqlite3_column_int(stmt, 2); struct message_guid uuid; /* Generate SHA1 from content */ message_guid_generate(&uuid, content, strlen(content)); /* Add SHA1 to our array using rowid as the index */ strarray_set(srock->sha1, rowid, message_guid_encode(&uuid)); } return 0; } #define CMD_GET_v12_ROWS \ "SELECT mailbox, content, rowid FROM sieve_scripts;" #define CMD_ALTER_v12_TABLE \ "ALTER TABLE sieve_scripts RENAME COLUMN content TO contentid;" #define CMD_UPDATE_v13_ROW \ "UPDATE sieve_scripts SET contentid = :contentid WHERE rowid = :rowid;" #define CMD_GET_v13_ROW1 \ "SELECT mailbox FROM sieve_scripts LIMIT 1;" #define CMD_UPDATE_v13_TABLE \ "UPDATE sieve_scripts SET mailbox = :mailbox;" /* Upgrade v12/v13 sieve_script table to v14 */ static int sievedb_upgrade(sqldb_t *db) { struct sievedb_upgrade_rock srock = { NULL, NULL }; struct sqldb_bindval bval[] = { { ":rowid", SQLITE_INTEGER, { .i = 0 } }, { ":contentid", SQLITE_TEXT, { .s = NULL } }, { ":mailbox", SQLITE_TEXT, { .s = NULL } }, { NULL, SQLITE_NULL, { .s = NULL } } }; strarray_t sha1 = STRARRAY_INITIALIZER; mbentry_t *mbentry = NULL; int rowid; int r = 0; if (db->version == 12) { /* Create an array of SHA1 for the content in each record */ srock.sha1 = &sha1; r = sqldb_exec(db, CMD_GET_v12_ROWS, NULL, &sievedb_upgrade_cb, &srock); if (r) goto done; /* Rename 'content' -> 'contentid' */ r = sqldb_exec(db, CMD_ALTER_v12_TABLE, NULL, NULL, NULL); if (r) goto done; /* Rewrite 'contentid' columns with actual ids (SHA1) */ for (rowid = 1; rowid < strarray_size(&sha1); rowid++) { bval[0].val.i = rowid; bval[1].val.s = strarray_nth(&sha1, rowid); r = sqldb_exec(db, CMD_UPDATE_v13_ROW, bval, NULL, NULL); if (r) goto done; } } else if (db->version == 13) { /* Fetch mailbox name from first record */ r = sqldb_exec(db, CMD_GET_v13_ROW1, NULL, &sievedb_upgrade_cb, &srock); if (r) goto done; } /* This will only be set if we are upgrading from v12 or v13 AND there are records in the table */ if (!srock.mboxname) goto done; r = mboxlist_lookup_allow_all(srock.mboxname, &mbentry, NULL); if (r) goto done; /* Rewrite 'mailbox' columns with mboxid rather than mboxname */ bval[2].val.s = mbentry->uniqueid; r = sqldb_exec(db, CMD_UPDATE_v13_TABLE, bval, NULL, NULL); done: mboxlist_entry_free(&mbentry); strarray_fini(&sha1); free(srock.mboxname); return r; }
842faea41f8da09a7c419863a1ecdf709a530941
b732361d6b3405c3e79ac0a7d8361cf5b329b015
/ext/phalcon/encryption/security/jwt/token/parser.zep.c
8fc7c151964043e5b2b501ac8b06201c8dc144ae
[ "BSD-3-Clause" ]
permissive
phalcon/cphalcon
4a5b26f47b5c2a4107541d7fd73c595c0d90ed73
fc183e11e8b96c43daf7d893244846206dc2aa73
refs/heads/master
2023-03-07T22:09:48.814291
2023-02-28T16:45:15
2023-02-28T16:45:15
2,854,337
8,135
2,343
BSD-3-Clause
2023-09-12T12:41:13
2011-11-26T05:52:50
PHP
UTF-8
C
false
true
14,437
c
parser.zep.c
#ifdef HAVE_CONFIG_H #include "../../../../../ext_config.h" #endif #include <php.h> #include "../../../../../php_ext.h" #include "../../../../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/fcall.h" #include "kernel/memory.h" #include "kernel/array.h" #include "ext/spl/spl_exceptions.h" #include "kernel/exception.h" #include "kernel/operators.h" #include "kernel/object.h" #include "kernel/string.h" #include "kernel/concat.h" /** * This file is part of the Phalcon Framework. * * (c) Phalcon Team <team@phalcon.io> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ /** * Token Parser class. * * It parses a token by validating if it is formed properly and splits it into * three parts. The headers are decoded, then the claims and finally the * signature. It returns a token object populated with the decoded information. */ ZEPHIR_INIT_CLASS(Phalcon_Encryption_Security_JWT_Token_Parser) { ZEPHIR_REGISTER_CLASS(Phalcon\\Encryption\\Security\\JWT\\Token, Parser, phalcon, encryption_security_jwt_token_parser, phalcon_encryption_security_jwt_token_parser_method_entry, 0); return SUCCESS; } /** * Parse a token and return it * * @param string $token * * @return Token */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, parse) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *token_param = NULL, claims, encodedClaims, encodedHeaders, encodedSignature, headers, results, signature; zval token; zval *this_ptr = getThis(); ZVAL_UNDEF(&token); ZVAL_UNDEF(&claims); ZVAL_UNDEF(&encodedClaims); ZVAL_UNDEF(&encodedHeaders); ZVAL_UNDEF(&encodedSignature); ZVAL_UNDEF(&headers); ZVAL_UNDEF(&results); ZVAL_UNDEF(&signature); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(token) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &token_param); if (UNEXPECTED(Z_TYPE_P(token_param) != IS_STRING && Z_TYPE_P(token_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'token' must be of the type string")); RETURN_MM_NULL(); } if (EXPECTED(Z_TYPE_P(token_param) == IS_STRING)) { zephir_get_strval(&token, token_param); } else { ZEPHIR_INIT_VAR(&token); } ZEPHIR_CALL_METHOD(&results, this_ptr, "parsetoken", NULL, 260, &token); zephir_check_call_status(); ZEPHIR_OBS_VAR(&encodedHeaders); zephir_array_fetch_long(&encodedHeaders, &results, 0, PH_NOISY, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 37); ZEPHIR_OBS_VAR(&encodedClaims); zephir_array_fetch_long(&encodedClaims, &results, 1, PH_NOISY, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 38); ZEPHIR_OBS_VAR(&encodedSignature); zephir_array_fetch_long(&encodedSignature, &results, 2, PH_NOISY, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 39); ZEPHIR_CALL_METHOD(&headers, this_ptr, "decodeheaders", NULL, 261, &encodedHeaders); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&claims, this_ptr, "decodeclaims", NULL, 262, &encodedClaims); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&signature, this_ptr, "decodesignature", NULL, 263, &headers, &encodedSignature); zephir_check_call_status(); object_init_ex(return_value, phalcon_encryption_security_jwt_token_token_ce); ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 258, &headers, &claims, &signature); zephir_check_call_status(); RETURN_MM(); } /** * Decode the claims * * @param string $claims * * @return Item */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, decodeClaims) { zval _4$$4; zend_bool _2; zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *claims_param = NULL, decoded, _0, _1, _3, _5$$4; zval claims; zval *this_ptr = getThis(); ZVAL_UNDEF(&claims); ZVAL_UNDEF(&decoded); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_3); ZVAL_UNDEF(&_5$$4); ZVAL_UNDEF(&_4$$4); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(claims) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &claims_param); zephir_get_strval(&claims, claims_param); ZEPHIR_CALL_METHOD(&_0, this_ptr, "decodeurl", NULL, 264, &claims); zephir_check_call_status(); ZVAL_BOOL(&_1, 1); ZEPHIR_CALL_METHOD(&decoded, this_ptr, "decode", NULL, 265, &_0, &_1); zephir_check_call_status(); if (Z_TYPE_P(&decoded) != IS_ARRAY) { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(spl_ce_InvalidArgumentException, "Invalid Claims (not an array)", "phalcon/Encryption/Security/JWT/Token/Parser.zep", 63); return; } _2 = zephir_array_isset_string(&decoded, SL("aud")); if (_2) { ZEPHIR_OBS_VAR(&_3); zephir_array_fetch_string(&_3, &decoded, SL("aud"), PH_NOISY, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 69); _2 = Z_TYPE_P(&_3) != IS_ARRAY; } if (_2) { ZEPHIR_INIT_VAR(&_4$$4); zephir_create_array(&_4$$4, 1, 0); ZEPHIR_OBS_VAR(&_5$$4); zephir_array_fetch_string(&_5$$4, &decoded, SL("aud"), PH_NOISY, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 70); zephir_array_fast_append(&_4$$4, &_5$$4); zephir_array_update_string(&decoded, SL("aud"), &_4$$4, PH_COPY | PH_SEPARATE); } object_init_ex(return_value, phalcon_encryption_security_jwt_token_item_ce); ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 256, &decoded, &claims); zephir_check_call_status(); RETURN_MM(); } /** * Decodes the headers * * @param string $headers * * @return Item */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, decodeHeaders) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *headers_param = NULL, decoded, _0, _1; zval headers; zval *this_ptr = getThis(); ZVAL_UNDEF(&headers); ZVAL_UNDEF(&decoded); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(headers) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &headers_param); zephir_get_strval(&headers, headers_param); ZEPHIR_CALL_METHOD(&_0, this_ptr, "decodeurl", NULL, 264, &headers); zephir_check_call_status(); ZVAL_BOOL(&_1, 1); ZEPHIR_CALL_METHOD(&decoded, this_ptr, "decode", NULL, 265, &_0, &_1); zephir_check_call_status(); if (Z_TYPE_P(&decoded) != IS_ARRAY) { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(spl_ce_InvalidArgumentException, "Invalid Header (not an array)", "phalcon/Encryption/Security/JWT/Token/Parser.zep", 92); return; } if (!(zephir_array_isset_string(&decoded, SL("typ")))) { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(spl_ce_InvalidArgumentException, "Invalid Header (missing 'typ' element)", "phalcon/Encryption/Security/JWT/Token/Parser.zep", 98); return; } object_init_ex(return_value, phalcon_encryption_security_jwt_token_item_ce); ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 256, &decoded, &headers); zephir_check_call_status(); RETURN_MM(); } /** * Decodes the signature * * @param Item $headers * @param string $signature * * @return Signature */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, decodeSignature) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval signature; zval *headers, headers_sub, *signature_param = NULL, algo, decoded, _0, _1, _2; zval *this_ptr = getThis(); ZVAL_UNDEF(&headers_sub); ZVAL_UNDEF(&algo); ZVAL_UNDEF(&decoded); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&signature); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_OBJECT_OF_CLASS(headers, phalcon_encryption_security_jwt_token_item_ce) Z_PARAM_STR(signature) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 2, 0, &headers, &signature_param); zephir_get_strval(&signature, signature_param); ZEPHIR_INIT_VAR(&_0); ZVAL_STRING(&_0, "alg"); ZEPHIR_INIT_VAR(&_1); ZVAL_STRING(&_1, "none"); ZEPHIR_CALL_METHOD(&algo, headers, "get", NULL, 0, &_0, &_1); zephir_check_call_status(); ZEPHIR_INIT_VAR(&_2); ZVAL_STRING(&_2, "none"); if (ZEPHIR_IS_IDENTICAL(&_2, &algo)) { ZEPHIR_INIT_VAR(&decoded); ZVAL_STRING(&decoded, ""); ZEPHIR_INIT_NVAR(&signature); } else { ZEPHIR_CALL_METHOD(&decoded, this_ptr, "decodeurl", NULL, 264, &signature); zephir_check_call_status(); } object_init_ex(return_value, phalcon_encryption_security_jwt_token_signature_ce); ZEPHIR_CALL_METHOD(NULL, return_value, "__construct", NULL, 257, &decoded, &signature); zephir_check_call_status(); RETURN_MM(); } /** * Splits the token to its three parts; * * @param string $token * * @return array */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, parseToken) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zval *token_param = NULL, parts; zval token; zval *this_ptr = getThis(); ZVAL_UNDEF(&token); ZVAL_UNDEF(&parts); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(token) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &token_param); if (UNEXPECTED(Z_TYPE_P(token_param) != IS_STRING && Z_TYPE_P(token_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'token' must be of the type string")); RETURN_MM_NULL(); } if (EXPECTED(Z_TYPE_P(token_param) == IS_STRING)) { zephir_get_strval(&token, token_param); } else { ZEPHIR_INIT_VAR(&token); } ZEPHIR_INIT_VAR(&parts); zephir_fast_explode_str(&parts, SL("."), &token, LONG_MAX); if (zephir_fast_count_int(&parts) != 3) { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(spl_ce_InvalidArgumentException, "Invalid JWT string (dots misalignment)", "phalcon/Encryption/Security/JWT/Token/Parser.zep", 144); return; } RETURN_CCTOR(&parts); } /** * @todo This will be removed when traits are introduced */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, decode) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long depth, options, ZEPHIR_LAST_CALL_STATUS; zend_bool associative; zval *data_param = NULL, *associative_param = NULL, *depth_param = NULL, *options_param = NULL, decoded, _0, _1, _2, _3, _4$$3, _5$$3, _6$$3; zval data; zval *this_ptr = getThis(); ZVAL_UNDEF(&data); ZVAL_UNDEF(&decoded); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&_3); ZVAL_UNDEF(&_4$$3); ZVAL_UNDEF(&_5$$3); ZVAL_UNDEF(&_6$$3); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 4) Z_PARAM_STR(data) Z_PARAM_OPTIONAL Z_PARAM_BOOL(associative) Z_PARAM_LONG(depth) Z_PARAM_LONG(options) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 3, &data_param, &associative_param, &depth_param, &options_param); if (UNEXPECTED(Z_TYPE_P(data_param) != IS_STRING && Z_TYPE_P(data_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'data' must be of the type string")); RETURN_MM_NULL(); } if (EXPECTED(Z_TYPE_P(data_param) == IS_STRING)) { zephir_get_strval(&data, data_param); } else { ZEPHIR_INIT_VAR(&data); } if (!associative_param) { associative = 0; } else { associative = zephir_get_boolval(associative_param); } if (!depth_param) { depth = 512; } else { depth = zephir_get_intval(depth_param); } if (!options_param) { options = 0; } else { options = zephir_get_intval(options_param); } ZVAL_BOOL(&_0, (associative ? 1 : 0)); ZVAL_LONG(&_1, depth); ZVAL_LONG(&_2, options); ZEPHIR_INIT_VAR(&decoded); zephir_json_decode(&decoded, &data, zephir_get_intval(&_0) ); ZEPHIR_CALL_FUNCTION(&_3, "json_last_error", NULL, 192); zephir_check_call_status(); if (UNEXPECTED(!ZEPHIR_IS_LONG_IDENTICAL(&_3, 0))) { ZEPHIR_INIT_VAR(&_4$$3); object_init_ex(&_4$$3, spl_ce_InvalidArgumentException); ZEPHIR_CALL_FUNCTION(&_5$$3, "json_last_error_msg", NULL, 193); zephir_check_call_status(); ZEPHIR_INIT_VAR(&_6$$3); ZEPHIR_CONCAT_SV(&_6$$3, "json_decode error: ", &_5$$3); ZEPHIR_CALL_METHOD(NULL, &_4$$3, "__construct", NULL, 194, &_6$$3); zephir_check_call_status(); zephir_throw_exception_debug(&_4$$3, "phalcon/Encryption/Security/JWT/Token/Parser.zep", 167); ZEPHIR_MM_RESTORE(); return; } RETURN_CCTOR(&decoded); } /** * @todo This will be removed when traits are introduced */ PHP_METHOD(Phalcon_Encryption_Security_JWT_Token_Parser, decodeUrl) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS, remainder = 0; zval *input_param = NULL, data, _3, _4, _5, _0$$3, _1$$3, _2$$3; zval input; zval *this_ptr = getThis(); ZVAL_UNDEF(&input); ZVAL_UNDEF(&data); ZVAL_UNDEF(&_3); ZVAL_UNDEF(&_4); ZVAL_UNDEF(&_5); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$3); ZVAL_UNDEF(&_2$$3); #if PHP_VERSION_ID >= 80000 bool is_null_true = 1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(input) ZEND_PARSE_PARAMETERS_END(); #endif ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &input_param); if (UNEXPECTED(Z_TYPE_P(input_param) != IS_STRING && Z_TYPE_P(input_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'input' must be of the type string")); RETURN_MM_NULL(); } if (EXPECTED(Z_TYPE_P(input_param) == IS_STRING)) { zephir_get_strval(&input, input_param); } else { ZEPHIR_INIT_VAR(&input); } remainder = (long) (zephir_safe_mod_long_long(zephir_fast_strlen_ev(&input), 4)); if (remainder) { ZEPHIR_INIT_VAR(&_0$$3); ZVAL_STRING(&_0$$3, "="); ZVAL_LONG(&_1$$3, (4 - remainder)); ZEPHIR_CALL_FUNCTION(&_2$$3, "str_repeat", NULL, 1, &_0$$3, &_1$$3); zephir_check_call_status(); zephir_concat_self(&input, &_2$$3); } ZEPHIR_INIT_VAR(&_3); ZVAL_STRING(&_3, "-_"); ZEPHIR_INIT_VAR(&_4); ZVAL_STRING(&_4, "+/"); ZEPHIR_CALL_FUNCTION(&_5, "strtr", NULL, 5, &input, &_3, &_4); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&data, "base64_decode", NULL, 228, &_5); zephir_check_call_status(); if (ZEPHIR_IS_FALSE_IDENTICAL(&data)) { ZEPHIR_INIT_NVAR(&data); ZVAL_STRING(&data, ""); } RETURN_CCTOR(&data); }
913f3f8a747f86b923308f0533f46d026432cb51
a12b448f44beb4d521cb7e31677281f41df35f0b
/3rdParty/isl/test_inputs/codegen/stride6.c
c09e8b5441fce580a54b0c0144e03eca71774f7f
[ "MIT", "LGPL-2.0-or-later" ]
permissive
Tiramisu-Compiler/tiramisu
d45f65dd9c35f643b3531ec79df1203c7ea3371d
f13e480f0ddb142cec371b7d7431a41d8ca885ec
refs/heads/master
2023-08-25T12:21:26.889736
2023-05-09T18:40:52
2023-05-09T18:40:52
58,378,976
906
168
MIT
2023-09-08T11:47:06
2016-05-09T13:33:51
C++
UTF-8
C
false
false
337
c
stride6.c
for (int c1 = -1024; c1 <= 0; c1 += 32) for (int c2 = max(-((niter - 1) % 32) + niter - 1, -((niter - c1) % 32) + niter - c1 - 32); c2 <= min(niter + 1022, niter - c1 - 1); c2 += 32) for (int c5 = max(max(0, -c1 - 1023), niter - c1 - c2 - 32); c5 <= min(min(31, -c1), niter - c1 - c2 - 1); c5 += 1) S_4(niter - 1, -c1 - c5);
14467ce104e04146e62e7e2389516eb6f29176dd
bf76ebe02527b728313664a9f6dfdfe1411e6a81
/infer/tests/codetoanalyze/c/frontend/switchstmt/switch_with_labels.c
48f5be6b82db5b42b183509a844457bc070c2506
[ "MIT", "GPL-1.0-or-later" ]
permissive
facebook/infer
30d13fd15e1d1c333800369b9120ac14c1e0c9e5
80a888ee5c534a40d4a178e5da3eaa61a3334ad1
refs/heads/main
2023-08-31T11:34:35.419621
2023-08-31T08:56:41
2023-08-31T08:56:41
29,857,799
15,855
2,632
MIT
2023-08-24T09:51:53
2015-01-26T11:19:13
OCaml
UTF-8
C
false
false
551
c
switch_with_labels.c
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ int label_default(char x) { int ret = 0; switch (x) { case 1: ret++; goto l; case 2: ret = 2; break; l: default: ret--; } return ret; } int label_case(char x) { int ret = 0; switch (x) { case 1: ret++; goto l; l: case 2: case 3: ret++; break; } return ret; }
272ce585ec893215d75547d624550387a805dc6f
50e95229b9a1161ac294137120aaba94c9eb06bc
/sources/ippcp/ecnist/ifma_ec_dh_p384.c
9fd110d9eaff860abee1ab521c0329513f386126
[ "Apache-2.0", "Intel" ]
permissive
intel/ipp-crypto
f0f05b87203705e82603db67bed5f8def13a5ee8
36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8
refs/heads/develop
2023-09-04T08:15:06.851373
2023-07-27T12:47:12
2023-07-27T12:47:12
140,034,345
304
81
Apache-2.0
2023-08-30T17:18:36
2018-07-06T22:16:28
C
UTF-8
C
false
false
2,793
c
ifma_ec_dh_p384.c
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * 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 "owndefs.h" #if (_IPP32E >= _IPP32E_K1) #include "pcpgfpecstuff.h" #include "pcpgfpstuff.h" #include "ifma_defs.h" #include "ifma_ecpoint_p384.h" #include "ifma_arith_method.h" IPP_OWN_DEFN(int, gfec_SharedSecretDH_nistp384_avx512, (IppsGFpECPoint * pR, const IppsGFpECPoint *pP, const BNU_CHUNK_T *pScalar, int scalarLen, IppsGFpECState *pEC, Ipp8u *pScratchBuffer)) { FIX_BNU(pScalar, scalarLen); { IPP_UNREFERENCED_PARAMETER(pScratchBuffer); gsModEngine *pME = GFP_PMA(ECP_GFP(pEC)); const int orderBits = ECP_ORDBITSIZE(pEC); const int orderLen = BITS_BNU_CHUNK(orderBits); ifmaArithMethod *pmeth = (ifmaArithMethod *)GFP_METHOD_ALT(pME); ifma_export from_radix52 = pmeth->export_to64; /* Mod engine (mod p) */ ifma_decode p_from_mont = pmeth->decode; /* Copy scalar */ BNU_CHUNK_T *pExtendedScalar = cpGFpGetPool(2, pME); cpGFpElementCopyPad(pExtendedScalar, orderLen + 1, pScalar, scalarLen); __ALIGN64 P384_POINT_IFMA P52, R52; BNU_CHUNK_T *pPool = cpGFpGetPool(3, pME); /* Convert point coordinates to a new Montgomery domain */ recode_point_to_mont52(&P52, ECP_POINT_DATA(pP), pPool, pmeth, pME); ifma_ec_nistp384_mul_point(&R52, &P52, (Ipp8u *)pExtendedScalar, orderBits); /* Check if the point - point to infinity */ const mask8 is_zero_z = is_zero_i64(R52.z); int finite_point = ((mask8)0xFF != is_zero_z); /* Get X affine coordinate */ ifma_ec_nistp384_get_affine_coords(&(R52.x), NULL, &R52); R52.x = p_from_mont(R52.x); from_radix52(ECP_POINT_X(pR), R52.x); cpGFpReleasePool(5, pME); return finite_point; } } #endif // IPP32E >= _IPP32E_K1
61d0931fa2774e9542cab067e3b7c31b094fd62b
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
/Python_Scripting_for_Computational_Science_Third_Edition/py/mixed/Grid2D/C/plain/debugdemo/gridloop1.c
9c6c33426c0f3fbe6fbfe5a59912fa5ae6291cf8
[]
no_license
burakbayramli/books
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
refs/heads/master
2023-08-17T05:31:08.885134
2023-08-14T10:05:37
2023-08-14T10:05:37
72,460,321
223
174
null
2022-10-24T12:15:06
2016-10-31T17:24:00
Jupyter Notebook
UTF-8
C
false
false
5,286
c
gridloop1.c
/* NOTE: this gridloop1.c file contains errors! The purpose is to illustrate debugging. Error: missing import_array(). */ #include <Python.h> /* Python as seen from C */ #include <numpy/arrayobject.h> /* NumPy as seen from C */ #include <math.h> #include <stdio.h> /* for debug output */ double f1p(double x, double y) { return x + y; } /* test func. */ static PyObject *gridloop1(PyObject *self, PyObject *args) { PyArrayObject *a, *xcoor, *ycoor; PyObject *func1, *arglist, *result; int nx, ny, i, j; double *a_ij, *x_i, *y_j; /* arguments: a, xcoor, ycoor, func1 */ if (!PyArg_ParseTuple(args, "O!O!O!O:gridloop1", &PyArray_Type, &a, &PyArray_Type, &xcoor, &PyArray_Type, &ycoor, &func1)) { return NULL; /* PyArg_ParseTuple has raised an exception */ } /* alternative parsing without checking the pointer types: if (!PyArg_ParseTuple(args, "OOOO", &a, &xcoor, &ycoor, &func1)) { return NULL; } */ if (PyArray_NDIM(a) != 2 || PyArray_TYPE(a) != NPY_DOUBLE) { PyErr_Format(PyExc_ValueError, "a array is %d-dimensional or not of type 'Python float'", PyArray_NDIM(a)); return NULL; } nx = PyArray_DIM(a,0); ny = PyArray_DIM(a,1); if (PyArray_NDIM(xcoor) != 1 || PyArray_TYPE(xcoor) != NPY_DOUBLE || PyArray_DIM(xcoor,0) != nx) { PyErr_Format(PyExc_ValueError, "xcoor array has wrong dimension (%d), type or length (%d)", PyArray_NDIM(xcoor),PyArray_DIM(xcoor,0)); return NULL; } if (PyArray_NDIM(ycoor) != 1 || PyArray_TYPE(ycoor) != NPY_DOUBLE || PyArray_DIM(ycoor,0) != ny) { PyErr_Format(PyExc_ValueError, "ycoor array has wrong dimension (%d), type or length (%d)", PyArray_NDIM(ycoor),PyArray_DIM(ycoor,0)); return NULL; } if (!PyCallable_Check(func1)) { PyErr_Format(PyExc_TypeError, "func1 is not a callable function"); return NULL; } for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { a_ij = (double *) PyArray_GETPTR2(a, i, j); x_i = (double *) PyArray_GETPTR1(xcoor, i); y_j = (double *) PyArray_GETPTR1(xcoor, i); arglist = Py_BuildValue("(dd)", *x_i, *y_j); result = PyEval_CallObject(func1, arglist); Py_DECREF(arglist); if (result == NULL) return NULL; /* exception in func1 */ *a_ij = PyFloat_AS_DOUBLE(result); Py_DECREF(result); #ifdef DEBUG printf("a[%d,%d]=func1(%g,%g)=%g\n",i,j,*x_i,*y_j,*a_ij); #endif } } return Py_BuildValue(""); /* return None */ /* alternative (return 0 for success): return Py_BuildValue("i",0); */ } #include <NumPy_macros.h> static PyObject *gridloop2(PyObject *self, PyObject *args) { PyArrayObject *a, *xcoor, *ycoor; npy_intp a_dims[2]; PyObject *func1, *arglist, *result; int nx, ny, i, j; /* arguments: xcoor, ycoor, func1 */ if (!PyArg_ParseTuple(args, "O!O!O:gridloop2", &PyArray_Type, &xcoor, &PyArray_Type, &ycoor, &func1)) { return NULL; /* PyArg_ParseTuple has raised an exception */ } nx = PyArray_DIM(xcoor,0); ny = PyArray_DIM(ycoor,0); NDIM_CHECK(xcoor, 1); TYPE_CHECK(xcoor, NPY_DOUBLE); NDIM_CHECK(ycoor, 1); TYPE_CHECK(ycoor, NPY_DOUBLE); CALLABLE_CHECK(func1); /* create return array: */ a_dims[0] = nx; a_dims[1] = ny; a = (PyArrayObject *) PyArray_SimpleNew(2, a_dims, NPY_DOUBLE); if (a == NULL) { printf("creating a failed, dims=(%d,%d)\n", (int) a_dims[0], (int) a_dims[1]); return NULL; /* PyArray_SimpleNew raised an exception */ } for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { arglist = Py_BuildValue("(dd)", DIND1(xcoor,i), DIND1(ycoor,j)); result = PyEval_CallObject(func1, arglist); Py_DECREF(arglist); if (result == NULL) return NULL; /* exception in func1 */ DIND2(a,i,j) = PyFloat_AS_DOUBLE(result); Py_DECREF(result); #ifdef DEBUG printf("a[%d,%d]=func1(%g,%g)=%g\n",i,j, DIND1(xcoor,i),DIND1(ycoor,j),DIND2(a,i,j)); #endif } } return PyArray_Return(a); } /* doc strings: */ static char gridloop1_doc[] = \ "gridloop1(a, xcoor, ycoor, pyfunc)"; static char gridloop2_doc[] = \ "a = gridloop2(xcoor, ycoor, pyfunc)"; static char module_doc[] = \ "module ext_gridloop:\n\ gridloop1(a, xcoor, ycoor, pyfunc)\n\ a = gridloop2(xcoor, ycoor, pyfunc)"; /* The method table must always be present - it lists the functions that should be callable from Python: */ static PyMethodDef ext_gridloop_methods[] = { {"gridloop1", /* name of func when called from Python */ gridloop1, /* corresponding C function */ METH_VARARGS, /* ordinary (not keyword) arguments */ gridloop1_doc}, /* doc string for gridloop1 function */ {"gridloop2", /* name of func when called from Python */ gridloop2, /* corresponding C function */ METH_VARARGS, /* ordinary (not keyword) arguments */ gridloop2_doc}, /* doc string for gridloop1 function */ {NULL, NULL} }; PyMODINIT_FUNC initext_gridloop() { /* Assign the name of the module and the name of the method table and (optionally) a module doc string: */ Py_InitModule3("ext_gridloop", ext_gridloop_methods, module_doc); /* without module doc string: Py_InitModule ("ext_gridloop", ext_gridloop_methods); */ }
fd28f44a0811ea4daf7764e817bc5033de705606
84db8126dfb48122083521bbdeda9fe761f12271
/librhash/tiger.c
8f134ae480d60e22c14eca89b36893d259e23b2a
[ "0BSD", "LicenseRef-scancode-other-permissive" ]
permissive
rhash/RHash
b45d064f7d61631b4f716e93c74b8773191eea0c
ee1cf8ce8c1a67ca07fabfba6ba3d6c0909b5fed
refs/heads/master
2023-09-03T18:13:07.107328
2023-08-27T21:34:51
2023-08-27T21:34:51
1,882,998
514
127
0BSD
2023-07-12T23:50:04
2011-06-12T00:16:27
C
UTF-8
C
false
false
6,554
c
tiger.c
/* tiger.c - an implementation of Tiger Hash Function * based on the article by * Ross Anderson and Eli Biham "Tiger: A Fast New Hash Function". * * Copyright (c) 2007, Aleksey Kravchenko <rhash.admin@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include "byte_order.h" #include "tiger.h" #ifdef NO_TIGER2 # define TIGER2_FLAG I64(0) #else # define TIGER2_FLAG I64(0x8000000000000000) #endif /* NO_TIGER2 */ #define LENGTH_MASK (~TIGER2_FLAG) #define INITIALIZE_TIGER_STATE(state) \ state[0] = I64(0x0123456789ABCDEF); \ state[1] = I64(0xFEDCBA9876543210); \ state[2] = I64(0xF096A5B4C3B2E187); /** * Initialize Tiger context before calculating hash. * * @param ctx context to initialize */ void rhash_tiger_init(tiger_ctx* ctx) { ctx->length = 0; INITIALIZE_TIGER_STATE(ctx->hash); } #ifndef NO_TIGER2 /** * Initialize Tiger2 context before calculating hash. * * @param ctx context to initialize */ void rhash_tiger2_init(tiger_ctx* ctx) { ctx->length = TIGER2_FLAG; INITIALIZE_TIGER_STATE(ctx->hash); } #endif /* NO_TIGER2 */ /* lookup tables */ extern uint64_t rhash_tiger_sboxes[4][256]; #define t1 rhash_tiger_sboxes[0] #define t2 rhash_tiger_sboxes[1] #define t3 rhash_tiger_sboxes[2] #define t4 rhash_tiger_sboxes[3] #ifdef CPU_X64 /* for x86-64 */ #define round(a,b,c,x,mul) \ c ^= x; \ a -= t1[(uint8_t)(c)] ^ \ t2[(uint8_t)((c) >> (2 * 8))] ^ \ t3[(uint8_t)((c) >> (4 * 8))] ^ \ t4[(uint8_t)((c) >> (6 * 8))] ; \ b += t4[(uint8_t)((c) >> (1 * 8))] ^ \ t3[(uint8_t)((c) >> (3 * 8))] ^ \ t2[(uint8_t)((c) >> (5 * 8))] ^ \ t1[(uint8_t)((c) >> (7 * 8))]; \ b *= mul; #else /* for IA32 */ #define round(a,b,c,x,mul) \ c ^= x; \ a -= t1[(uint8_t)(c)] ^ \ t2[(uint8_t)(((uint32_t)(c)) >> (2 * 8))] ^ \ t3[(uint8_t)((c) >> (4 * 8))] ^ \ t4[(uint8_t)(((uint32_t)((c) >> (4 * 8))) >> (2 * 8))] ; \ b += t4[(uint8_t)(((uint32_t)(c)) >> (1 * 8))] ^ \ t3[(uint8_t)(((uint32_t)(c)) >> (3 * 8))] ^ \ t2[(uint8_t)(((uint32_t)((c) >> (4 * 8))) >> (1 * 8))] ^ \ t1[(uint8_t)(((uint32_t)((c) >> (4 * 8))) >> (3 * 8))]; \ b *= mul; #endif /* CPU_X64 */ #define pass(a,b,c,mul) \ round(a,b,c,x0,mul) \ round(b,c,a,x1,mul) \ round(c,a,b,x2,mul) \ round(a,b,c,x3,mul) \ round(b,c,a,x4,mul) \ round(c,a,b,x5,mul) \ round(a,b,c,x6,mul) \ round(b,c,a,x7,mul) #define key_schedule { \ x0 -= x7 ^ I64(0xA5A5A5A5A5A5A5A5); \ x1 ^= x0; \ x2 += x1; \ x3 -= x2 ^ ((~x1)<<19); \ x4 ^= x3; \ x5 += x4; \ x6 -= x5 ^ ((~x4)>>23); \ x7 ^= x6; \ x0 += x7; \ x1 -= x0 ^ ((~x7)<<19); \ x2 ^= x1; \ x3 += x2; \ x4 -= x3 ^ ((~x2)>>23); \ x5 ^= x4; \ x6 += x5; \ x7 -= x6 ^ I64(0x0123456789ABCDEF); \ } /** * The core transformation. Process a 512-bit block. * * @param state the algorithm state * @param block the message block to process */ static void rhash_tiger_process_block(uint64_t state[3], uint64_t* block) { /* Optimized for GCC IA32. The order of declarations is important for compiler. */ uint64_t a, b, c; uint64_t x0, x1, x2, x3, x4, x5, x6, x7; #ifndef CPU_X64 uint64_t tmp; char i; #endif x0 = le2me_64(block[0]); x1 = le2me_64(block[1]); x2 = le2me_64(block[2]); x3 = le2me_64(block[3]); x4 = le2me_64(block[4]); x5 = le2me_64(block[5]); x6 = le2me_64(block[6]); x7 = le2me_64(block[7]); a = state[0]; b = state[1]; c = state[2]; /* passes and key shedules */ #ifndef CPU_X64 for (i = 0; i < 3; i++) { if (i != 0) key_schedule; pass(a, b, c, (i == 0 ? 5 : i == 1 ? 7 : 9)); tmp = a; a = c; c = b; b = tmp; } #else pass(a, b, c, 5); key_schedule; pass(c, a, b, 7); key_schedule; pass(b, c, a, 9); #endif /* feedforward operation */ state[0] = a ^ state[0]; state[1] = b - state[1]; state[2] = c + state[2]; } /** * Calculate message hash. * Can be called repeatedly with chunks of the message to be hashed. * * @param ctx the algorithm context containing current hashing state * @param msg message chunk * @param size length of the message chunk */ void rhash_tiger_update(tiger_ctx* ctx, const unsigned char* msg, size_t size) { size_t index = (size_t)ctx->length & 63; ctx->length += size; /* fill partial block */ if (index) { size_t left = tiger_block_size - index; if (size < left) { if (size > 0) memcpy(ctx->message + index, msg, size); return; } else { memcpy(ctx->message + index, msg, left); rhash_tiger_process_block(ctx->hash, (uint64_t*)ctx->message); msg += left; size -= left; } } while (size >= tiger_block_size) { if (IS_ALIGNED_64(msg)) { /* the most common case is processing of an already aligned message without copying it */ rhash_tiger_process_block(ctx->hash, (uint64_t*)msg); } else { memcpy(ctx->message, msg, tiger_block_size); rhash_tiger_process_block(ctx->hash, (uint64_t*)ctx->message); } msg += tiger_block_size; size -= tiger_block_size; } if (size) { /* save leftovers */ memcpy(ctx->message, msg, size); } } /** * Store calculated hash into the given array. * * @param ctx the algorithm context containing current hashing state * @param result calculated hash in binary form */ void rhash_tiger_final(tiger_ctx* ctx, unsigned char result[24]) { unsigned index = (unsigned)ctx->length & 63; uint64_t* msg64 = (uint64_t*)ctx->message; /* pad message and run for last block */ /* append the byte 0x01 to the message */ ctx->message[index++] = (ctx->length & TIGER2_FLAG ? 0x80 : 0x01); /* if no room left in the message to store 64-bit message length */ if (index > 56) { /* then fill the rest with zeros and process it */ while (index < 64) { ctx->message[index++] = 0; } rhash_tiger_process_block(ctx->hash, msg64); index = 0; } while (index < 56) { ctx->message[index++] = 0; } msg64[7] = le2me_64((ctx->length & LENGTH_MASK) << 3); rhash_tiger_process_block(ctx->hash, msg64); /* save result hash */ le64_copy(result, 0, &ctx->hash, 24); }
c2a3173bb5f1a9810e0a8512e292459bebb80490
32e910f5440c10b384bb26b5555ac7adb77540ee
/src/3rd_party/apr-util-1.5.3/test/testldap.c
4f4fef907bcdd4708ffb503e47789bc54e4dbf2f
[ "LicenseRef-scancode-generic-export-compliance", "Apache-2.0", "LicenseRef-scancode-rsa-md4", "OLDAP-2.8", "MIT", "NTP", "RSA-MD", "BSD-4.3RENO", "Beerware", "LicenseRef-scancode-rsa-1990" ]
permissive
smartdevicelink/sdl_core
76658282fd85b16ed6d91d8d4087d8cd1353db76
7343fc72c12edc8ac42a62556c9e4b29c9408bc3
refs/heads/master
2022-11-04T12:17:58.725371
2022-10-26T15:34:13
2022-10-26T15:34:13
24,724,170
269
306
BSD-3-Clause
2022-10-26T15:34:15
2014-10-02T15:16:26
C++
UTF-8
C
false
false
7,092
c
testldap.c
/* 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. */ /* Setup: * - Create or edit the file data/host.data and add an * ldap server DN. Multiple DNs may be listed on * a single line. * - Copy the server certificates to the data/ directory. * All DER type certificates must have the .der extention. * All BASE64 or PEM certificates must have the .b64 * extension. All certificate files copied to the /data * directory will be added to the ldap certificate store. */ /* This test covers the following three types of connections: * - Unsecure ldap:// * - Secure ldaps:// * - Secure ldap://+Start_TLS * * - (TBD) Mutual authentication * * There are other variations that should be tested: * - All of the above with multiple redundant LDAP servers * This can be done by listing more than one server DN * in the host.data file. The DNs should all be listed * on one line separated by a space. * - All of the above with multiple certificates * If more than one certificate is found in the data/ * directory, each certificate found will be added * to the certificate store. * - All of the above on alternate ports * An alternate port can be specified as part of the * host in the host.data file. The ":port" should * follow each DN listed. Default is 389 and 636. * - Secure connections with mutual authentication */ #include "testutil.h" #include "apr.h" #include "apr_general.h" #include "apr_ldap.h" #include "apr_file_io.h" #include "apr_file_info.h" #include "apr_strings.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #define APR_WANT_STDIO #define APR_WANT_STRFUNC #include "apr_want.h" #define DIRNAME "data" #define FILENAME DIRNAME "/host.data" #define CERTFILEDER DIRNAME "/*.der" #define CERTFILEB64 DIRNAME "/*.b64" #if APR_HAS_LDAP static char ldap_host[256]; static int get_ldap_host(void) { apr_status_t rv; apr_file_t *thefile = NULL; char *ptr; ldap_host[0] = '\0'; rv = apr_file_open(&thefile, FILENAME, APR_FOPEN_READ, APR_UREAD | APR_UWRITE | APR_GREAD, p); if (rv != APR_SUCCESS) { return 0; } rv = apr_file_gets(ldap_host, sizeof(ldap_host), thefile); if (rv != APR_SUCCESS) { return 0; } ptr = strstr (ldap_host, "\r\n"); if (ptr) { *ptr = '\0'; } apr_file_close(thefile); return 1; } static int add_ldap_certs(abts_case *tc) { apr_status_t status; apr_dir_t *thedir; apr_finfo_t dirent; apr_ldap_err_t *result = NULL; if ((status = apr_dir_open(&thedir, DIRNAME, p)) == APR_SUCCESS) { apr_ldap_opt_tls_cert_t *cert = (apr_ldap_opt_tls_cert_t *)apr_pcalloc(p, sizeof(apr_ldap_opt_tls_cert_t)); do { status = apr_dir_read(&dirent, APR_FINFO_MIN | APR_FINFO_NAME, thedir); if (APR_STATUS_IS_INCOMPLETE(status)) { continue; /* ignore un-stat()able files */ } else if (status != APR_SUCCESS) { break; } if (strstr(dirent.name, ".der")) { cert->type = APR_LDAP_CA_TYPE_DER; cert->path = apr_pstrcat (p, DIRNAME, "/", dirent.name, NULL); apr_ldap_set_option(p, NULL, APR_LDAP_OPT_TLS_CERT, (void *)cert, &result); ABTS_TRUE(tc, result->rc == LDAP_SUCCESS); } if (strstr(dirent.name, ".b64")) { cert->type = APR_LDAP_CA_TYPE_BASE64; cert->path = apr_pstrcat (p, DIRNAME, "/", dirent.name, NULL); apr_ldap_set_option(p, NULL, APR_LDAP_OPT_TLS_CERT, (void *)cert, &result); ABTS_TRUE(tc, result->rc == LDAP_SUCCESS); } } while (1); apr_dir_close(thedir); } return 0; } static void test_ldap_connection(abts_case *tc, LDAP *ldap) { int version = LDAP_VERSION3; int failures, result; /* always default to LDAP V3 */ ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &version); for (failures=0; failures<10; failures++) { result = ldap_simple_bind_s(ldap, (char *)NULL, (char *)NULL); if (LDAP_SERVER_DOWN != result) break; } ABTS_TRUE(tc, result == LDAP_SUCCESS); if (result != LDAP_SUCCESS) { abts_log_message("%s\n", ldap_err2string(result)); } ldap_unbind_s(ldap); return; } static void test_ldap(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; ABTS_ASSERT(tc, "failed to get host", ldap_host[0] != '\0'); apr_ldap_init(pool, &ldap, ldap_host, LDAP_PORT, APR_LDAP_NONE, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { test_ldap_connection(tc, ldap); } } static void test_ldaps(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; apr_ldap_init(pool, &ldap, ldap_host, LDAPS_PORT, APR_LDAP_SSL, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { add_ldap_certs(tc); test_ldap_connection(tc, ldap); } } static void test_ldap_tls(abts_case *tc, void *data) { apr_pool_t *pool = p; LDAP *ldap; apr_ldap_err_t *result = NULL; apr_ldap_init(pool, &ldap, ldap_host, LDAP_PORT, APR_LDAP_STARTTLS, &(result)); ABTS_TRUE(tc, ldap != NULL); ABTS_PTR_NOTNULL(tc, result); if (result->rc == LDAP_SUCCESS) { add_ldap_certs(tc); test_ldap_connection(tc, ldap); } } #endif /* APR_HAS_LDAP */ abts_suite *testldap(abts_suite *suite) { #if APR_HAS_LDAP apr_ldap_err_t *result = NULL; suite = ADD_SUITE(suite); apr_ldap_ssl_init(p, NULL, 0, &result); if (get_ldap_host()) { abts_run_test(suite, test_ldap, NULL); abts_run_test(suite, test_ldaps, NULL); abts_run_test(suite, test_ldap_tls, NULL); } #endif /* APR_HAS_LDAP */ return suite; }
ed9e1cb411332fab25e559164179bb462c5c8805
057a475216e9beed41983481aafcaf109bbf58da
/utils/memcpy-bench/glibc/sysdep.h
82b1e747fbefc4f0d6e9119af04b7f53b5da29c3
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C
false
false
4,200
h
sysdep.h
#pragma once /* Assembler macros for x86-64. Copyright (C) 2001-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #ifndef _X86_64_SYSDEP_H #define _X86_64_SYSDEP_H 1 #include "sysdep_x86.h" #ifdef __ASSEMBLER__ /* Syntactic details of assembler. */ /* This macro is for setting proper CFI with DW_CFA_expression describing the register as saved relative to %rsp instead of relative to the CFA. Expression is DW_OP_drop, DW_OP_breg7 (%rsp is register 7), sleb128 offset from %rsp. */ #define cfi_offset_rel_rsp(regn, off) .cfi_escape 0x10, regn, 0x4, 0x13, \ 0x77, off & 0x7F | 0x80, off >> 7 /* If compiled for profiling, call `mcount' at the start of each function. */ #ifdef PROF /* The mcount code relies on a normal frame pointer being on the stack to locate our caller, so push one just for its benefit. */ #define CALL_MCOUNT \ pushq %rbp; \ cfi_adjust_cfa_offset(8); \ movq %rsp, %rbp; \ cfi_def_cfa_register(%rbp); \ call JUMPTARGET(mcount); \ popq %rbp; \ cfi_def_cfa(rsp,8); #else #define CALL_MCOUNT /* Do nothing. */ #endif #define PSEUDO(name, syscall_name, args) \ lose: \ jmp JUMPTARGET(syscall_error) \ .globl syscall_error; \ ENTRY (name) \ DO_CALL (syscall_name, args); \ jb lose #undef JUMPTARGET #ifdef SHARED # ifdef BIND_NOW # define JUMPTARGET(name) *name##@GOTPCREL(%rip) # else # define JUMPTARGET(name) name##@PLT # endif #else /* For static archives, branch to target directly. */ # define JUMPTARGET(name) name #endif /* Long and pointer size in bytes. */ #define LP_SIZE 8 /* Instruction to operate on long and pointer. */ #define LP_OP(insn) insn##q /* Assembler address directive. */ #define ASM_ADDR .quad /* Registers to hold long and pointer. */ #define RAX_LP rax #define RBP_LP rbp #define RBX_LP rbx #define RCX_LP rcx #define RDI_LP rdi #define RDX_LP rdx #define RSI_LP rsi #define RSP_LP rsp #define R8_LP r8 #define R9_LP r9 #define R10_LP r10 #define R11_LP r11 #define R12_LP r12 #define R13_LP r13 #define R14_LP r14 #define R15_LP r15 #else /* __ASSEMBLER__ */ /* Long and pointer size in bytes. */ #define LP_SIZE "8" /* Instruction to operate on long and pointer. */ #define LP_OP(insn) #insn "q" /* Assembler address directive. */ #define ASM_ADDR ".quad" /* Registers to hold long and pointer. */ #define RAX_LP "rax" #define RBP_LP "rbp" #define RBX_LP "rbx" #define RCX_LP "rcx" #define RDI_LP "rdi" #define RDX_LP "rdx" #define RSI_LP "rsi" #define RSP_LP "rsp" #define R8_LP "r8" #define R9_LP "r9" #define R10_LP "r10" #define R11_LP "r11" #define R12_LP "r12" #define R13_LP "r13" #define R14_LP "r14" #define R15_LP "r15" #endif /* __ASSEMBLER__ */ #endif /* _X86_64_SYSDEP_H */
935027b49264a247ff49a5a1b36f2dece656d355
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/calls/execvpe.c
80382d4056a19ec678dee0f2457bade6d15264d7
[ "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
3,421
c
execvpe.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/mem/alloca.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" /** * Executes program, with path environment search. * * This function is a wrapper of the execve() system call that does path * resolution. The `PATH` environment variable is taken from your global * `environ` rather than the `envp` argument. * * @param prog is the program to launch * @param argv is [file,argv₁..argvₙ₋₁,NULL] * @param envp is ["key=val",...,NULL] * @return doesn't return on success, otherwise -1 w/ errno * @asyncsignalsafe * @vforksafe */ int execvpe(const char *prog, char *const argv[], char *const *envp) { size_t i; char *exe, **argv2; char pathbuf[PATH_MAX]; // validate memory if (IsAsan() && (!__asan_is_valid_str(prog) || !__asan_is_valid_strlist(argv))) { return efault(); } if (strchr(prog, '/')) { return execve(prog, argv, envp); } // resolve path of executable if (!(exe = commandv(prog, pathbuf, sizeof(pathbuf)))) { return -1; } // change argv[0] to resolved path if it's ambiguous // otherwise the program won't have much luck finding itself if (argv[0] && *prog != '/' && *exe == '/' && !strcmp(prog, argv[0])) { for (i = 0; argv[i++];) (void)0; argv2 = alloca(i * sizeof(*argv)); memcpy(argv2, argv, i * sizeof(*argv)); argv2[0] = exe; argv = argv2; } // execute program // tail call shouldn't be possible return execve(exe, argv, envp); }
2ecb238b7771b004f5d80cea7814e45dfb890388
67801a1568b81ea5e45ed534301cd35949066e6d
/src/main.c
3f63b142bb131f05b1411cc826ce0b27b761fe04
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fossasia/pslab-firmware
dcb8e570d162c0ef24cdedf43483c706bc736259
c93ac629442315c1430120b7ab3c0026d03e3503
refs/heads/main
2023-07-22T18:22:30.827478
2023-07-05T05:32:15
2023-07-05T05:38:34
86,472,725
2,212
89
Apache-2.0
2023-09-14T20:36:23
2017-03-28T14:53:27
C
UTF-8
C
false
false
245
c
main.c
#include "registers/system/system.h" #include "states.h" int main(void) { SYSTEM_Initialize(); state_t current_state = STATE_STANDBY; while (1) { current_state = STATES_RunState(current_state); } return 1; }
658e54176b6d5c2bd9d73d223159d5ee12ee1671
9e1943efc1a9fa1e3d476c54168639bdb7901c17
/server/teleserver/httpd/httpd.c
fae04cdd589fa4b3709c7c89a27faf2501d56ecd
[]
no_license
stanleyhuangyc/Freematics
b9e7b0eb8a08f85a0595da4ad346544ba1280431
383665fd0f5efa418064d078fe92ab1a8379f76a
refs/heads/master
2023-08-30T21:53:50.551964
2023-08-30T13:42:47
2023-08-30T13:42:47
16,797,653
383
422
null
2023-02-22T17:58:29
2014-02-13T09:14:22
C++
UTF-8
C
false
false
55,659
c
httpd.c
/****************************************************************************** * MiniWeb - a mini and high efficiency HTTP server implementation * Developed by Stanley Huang <stanley@freematics.com.au> * Based on the original MiniWeb developed and hosted at * https://sourceforge.net/projects/miniweb/ * Distributed under BSD license * * 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 <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "httpd.h" #include "httpint.h" //////////////////////////////////////////////////////////////////////////// // global variables //////////////////////////////////////////////////////////////////////////// const char* status200[] = { "OK", /* 200 */ "Created", /* 201 */ "Accepted", /* 202 */ "Non-Authoritative Information", /* 203 */ "No Content", /* 204 */ "Reset Content", /* 205 */ "Partial Content", /* 206 */ }; const char* status300[] = { "Multiple Choices", /* 300 */ "Moved Permanently", /* 301 */ "Found", /* 302 */ "See Other", /* 303 */ "Not Modified", /* 304 */ "Use Proxy", /* 305 */ "", /* 306 */ "Temporary Redirect", /* 307 */ }; const char* status400[] = { "Bad Request", /* 400 */ "Unauthorized", /* 401 */ "", /* 402 */ "Forbidden", /* 403 */ "Not Found", /* 404 */ "Method Not Allowed", /* 405 */ "Not Acceptable", /* 406 */ "Proxy Authentication Required", /* 407 */ "Request Timeout", /* 408 */ "Conflict", /* 409 */ "Gone", /* 410 */ "Length Required", /* 411 */ "Precondition Failed", /* 412 */ "Request Entity Too Large", /* 413 */ "Request-URI Too Long", /* 414 */ }; const char* status500[] = { "Internal Server Error", /* 500 */ "Not Implemented", /* 501 */ "Bad Gateway", /* 502 */ "Service Unavailable", /* 503 */ "Gateway Timeout", /* 504 */ }; const char* contentTypeTable[]={ "application/octet-stream", "text/html", "text/xml", "text/plain", "application/vnd.mozilla.xul+xml", "text/css", "application/x-javascript", "image/png", "image/jpeg", "image/gif", "application/x-shockwave-flash", "audio/mpeg", "video/mpeg", "video/avi", "video/mp4", "video/quicktime", "video/x-mpeg-avc", "video/flv", "video/MP2T", "video/3gpp", "video/x-ms-asf", "application/octet-stream", "application/x-datastream", "application/x-mpegURL", "application/sdp", "application/binhex", "application/json", }; char* defaultPages[]={"index.htm","index.html","default.htm","main.xul"}; //////////////////////////////////////////////////////////////////////////// // API callsc //////////////////////////////////////////////////////////////////////////// const char *dayNames="Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat"; const char *monthNames="Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec"; const char *httpDateTimeFormat="%s, %02d %s %d %02d:%02d:%02d GMT"; char* mwGetVarValue(HttpVariables* vars, const char *varname, const char *defval) { if (vars && varname) { int i; for (i=0; (vars+i)->name; i++) { if (!strcmp((vars+i)->name,varname)) { return (vars+i)->value; } } } return (char*)defval; } int mwGetVarValueInt(HttpVariables* vars, const char *varname, int defval) { if (vars && varname) { int i; for (i=0; (vars+i)->name; i++) { if (!strcmp((vars+i)->name,varname)) { char *p = (vars+i)->value; return *p ? atoi(p) : defval; } } } return defval; } int64_t mwGetVarValueInt64(HttpVariables* vars, const char *varname) { if (vars && varname) { int i; for (i = 0; (vars + i)->name; i++) { if (!strcmp((vars + i)->name, varname)) { char *p = (vars + i)->value; return *p ? atoll(p) : 0; } } } return 0; } float mwGetVarValueFloat(HttpVariables* vars, const char *varname) { if (vars && varname) { int i; for (i = 0; (vars + i)->name; i++) { if (!strcmp((vars + i)->name, varname)) { char *p = (vars + i)->value; return *p ? (float)atof(p) : 0; } } } return 0; } static unsigned int hex2uint32(const char *p) { register char c; register unsigned int i = 0; for(c=*p;;){ if (c>='A' && c<='F') c-=7; else if (c>='a' && c<='f') c-=39; else if (c<'0' || c>'9') break; i=(i<<4)|(c&0xF); c=*(++p); } return i; } unsigned int mwGetVarValueHex(HttpVariables* vars, const char *varname, unsigned int defval) { int i; if (vars && varname) { for (i=0; (vars+i)->name; i++) { if (!strcmp((vars+i)->name,varname)) { char *p = (vars+i)->value; return p ? hex2uint32(p) : defval; } } } return defval; } int mwGetHttpDateTime(time_t timer, char *buf, int bufsize) { struct tm *btm; btm=gmtime(&timer); return snprintf(buf, bufsize, httpDateTimeFormat, dayNames+(btm->tm_wday<<2), btm->tm_mday, monthNames+(btm->tm_mon<<2), 1900+btm->tm_year, btm->tm_hour, btm->tm_min, btm->tm_sec); } void mwInitParam(HttpParam* hp, int port, const char* webPath, unsigned int flags, const char* proxyHost, int proxyPort) { #ifdef WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 1), &wsaData) && WSAStartup(MAKEWORD(1, 1), &wsaData)) { return; } #endif memset(hp, 0, sizeof(HttpParam)); hp->httpPort = port; hp->maxClients = HTTP_MAX_CLIENTS_DEFAULT; hp->pchWebPath = webPath; hp->flags = flags; if (proxyHost) { struct hostent *target_host = gethostbyname(proxyHost); if (target_host) { memset(&hp->proxy_addr, 0, sizeof(hp->proxy_addr)); hp->proxy_addr.sin_family = AF_INET; memcpy(&hp->proxy_addr.sin_addr.s_addr, (void*)target_host->h_addr, target_host->h_length); hp->proxy_addr.sin_port = htons(proxyPort); hp->flags |= FLAG_ENABLE_PROXY; hp->proxyBuffer = malloc(PROXY_TX_BUF_SIZE); SYSLOG(LOG_INFO, "Proxy server: %s:%u\n", proxyHost, proxyPort); } } } //////////////////////////////////////////////////////////////////////////// // mwServerStart // Start the webserver //////////////////////////////////////////////////////////////////////////// int mwServerStart(HttpParam* hp) { if (hp->bWebserverRunning) { return -1; } if (hp->maxClients == 0) { SYSLOG(LOG_INFO,"Maximum clients not set\n"); return -1; } if (!(hp->listenSocket=_mwStartListening(hp))) { return -1; } hp->hsSocketQueue = calloc(hp->maxClients, sizeof(HttpSocket)); hp->bKillWebserver=FALSE; hp->bWebserverRunning=TRUE; return 0; } //////////////////////////////////////////////////////////////////////////// // mwServerShutdown // Shutdown the webserver //////////////////////////////////////////////////////////////////////////// int mwServerShutdown(HttpParam* hp) { int i; if (hp->bKillWebserver || !hp->bWebserverRunning) return -1; _mwCloseAllConnections(hp); // signal webserver thread to quit hp->bKillWebserver=TRUE; // and wait for thread to exit for (i=0;hp->bWebserverRunning && i<30;i++) msleep(100); return 0; } int mwGetLocalFileName(HttpFilePath* hfp) { char ch; char *p = (char*)hfp->cFilePath; char *s = (char*)hfp->pchHttpPath; char *upLevel = NULL; hfp->pchExt=NULL; hfp->fTailSlash=0; if (*s == '~') { s++; } else if (hfp->pchRootPath) { p+=_mwStrCopy(hfp->cFilePath,hfp->pchRootPath); if (*(p-1)!=SLASH) { *p=SLASH; *(++p)=0; } } while ((ch=*s) && ch!='?' && (int)(p-hfp->cFilePath)<sizeof(hfp->cFilePath)-1) { if (ch=='%') { *(p++) = _mwDecodeCharacter(++s); s += 2; } else if (ch=='/') { *p=SLASH; upLevel=(++p); while (*(++s)=='/'); continue; } else if (ch=='+') { *(p++)=' '; s++; } else if (ch=='.') { if (upLevel && !memcmp(s+1, "./", 2)) { s+=2; p=upLevel; } else { *(p++)='.'; hfp->pchExt=p; while (*(++s)=='.'); //avoid '..' appearing in filename for security issue } } else { *(p++)=*(s++); } } if (*(p-1)==SLASH) { p--; hfp->fTailSlash=1; } *p=0; return (int)(p - hfp->cFilePath); } //////////////////////////////////////////////////////////////////////////// // Internal (private) helper functions //////////////////////////////////////////////////////////////////////////// SOCKET _mwStartListening(HttpParam* hp) { SOCKET listenSocket; struct sockaddr_in sinAddress; int iRc; // create a new socket listenSocket=socket(AF_INET,SOCK_STREAM,0); if (listenSocket <= 0) { return 0; } #ifndef ARDUINO // allow reuse of port number { int iOptVal=1; iRc=setsockopt(listenSocket,SOL_SOCKET,SO_REUSEADDR, (char*)&iOptVal,sizeof(iOptVal)); if (iRc<0) return 0; } #endif // bind it to the http port memset(&sinAddress,0,sizeof(struct sockaddr_in)); sinAddress.sin_family=AF_INET; // INADDR_ANY is 0 //sinAddress.sin_addr.s_addr=htonl(hp->dwBindIP); sinAddress.sin_addr.s_addr = hp->hlBindIP; sinAddress.sin_port = htons(hp->httpPort); // http port iRc=bind(listenSocket,(struct sockaddr*)&sinAddress, sizeof(struct sockaddr_in)); if (iRc<0) { return 0; } _mwSetSocketOpts(listenSocket); // listen on the socket for incoming calls if (listen(listenSocket, hp->maxClients)) { return 0; } // create UDP socket if (hp->udpPort) { hp->udpSocket = socket(AF_INET, SOCK_DGRAM, 0); _mwSetSocketOpts(hp->udpSocket); memset(&sinAddress, 0, sizeof(struct sockaddr_in)); sinAddress.sin_family = AF_INET; sinAddress.sin_addr.s_addr = hp->hlBindIP; sinAddress.sin_port = htons(hp->udpPort); // UDP port bind(hp->udpSocket, (struct sockaddr*)&sinAddress, sizeof(struct sockaddr_in)); } if (hp->flags & FLAG_ENABLE_PROXY) { hp->proxySocket = socket(AF_INET, SOCK_STREAM, 0); if (connect(hp->proxySocket, (struct sockaddr*)&hp->proxy_addr, sizeof(hp->proxy_addr)) < 0) { SYSLOG(LOG_INFO, "Unable to connect to proxy server. Disable proxying.\n"); closesocket(hp->proxySocket); hp->proxySocket = 0; hp->flags &= ~FLAG_ENABLE_PROXY; } else { SYSLOG(LOG_INFO, "[%d] Proxy server connected\n", hp->proxySocket); _mwSetSocketOpts(hp->proxySocket); hp->flags |= FLAG_PROXY_CONNECTED; } } return listenSocket; } void _mwInitSocketData(HttpSocket *phsSocket) { memset(&phsSocket->response,0,sizeof(HttpResponse)); if (!phsSocket->buffer) phsSocket->buffer = malloc(HTTP_BUFFER_SIZE); phsSocket->request.startByte = 0; phsSocket->request.pucHost = 0; phsSocket->request.pucReferer = 0; phsSocket->request.pucTransport = 0; phsSocket->request.pucPath = 0; phsSocket->request.headerSize = 0; phsSocket->request.payloadSize = 0; phsSocket->request.iCSeq = 0; phsSocket->request.pucAuthInfo = NULL; phsSocket->response.statusCode = 200; phsSocket->fp = 0; phsSocket->flags = 0; phsSocket->pucData = phsSocket->buffer; phsSocket->contentLength = 0; phsSocket->bufferSize = HTTP_BUFFER_SIZE; phsSocket->handler = NULL; phsSocket->mimeType = NULL; } static int _mwGetConnFromIP(HttpParam* hp, IPADDR ip) { int i; int connThisIP = 0; for (i = 0; i < hp->maxClients; i++) { if (!hp->hsSocketQueue[i].socket) continue; if (hp->hsSocketQueue[i].ipAddr.laddr == ip.laddr) { connThisIP++; } } return connThisIP; } void _mwCloseAllConnections(HttpParam* hp) { int i; if (hp->listenSocket) { closesocket(hp->listenSocket); hp->listenSocket = 0; } if (hp->udpSocket) { closesocket(hp->udpSocket); hp->udpSocket = 0; } if (hp->proxySocket) { closesocket(hp->proxySocket); hp->proxySocket = 0; } for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].socket) { closesocket(hp->hsSocketQueue[i].socket); hp->hsSocketQueue[i].socket = 0; } } } //////////////////////////////////////////////////////////////////////////// // _mwHttpThread // Webserver independant processing thread. Handles all connections //////////////////////////////////////////////////////////////////////////// void mwHttpLoop(HttpParam *hp, uint32_t timeout) { HttpSocket *phsSocketCur; SOCKET sock; struct sockaddr_in sinaddr; int iRc; int i; time_t tmCurrentTime; SOCKET iSelectMaxFds; fd_set fdsSelectRead; fd_set fdsSelectWrite; // clear descriptor sets FD_ZERO(&fdsSelectRead); FD_ZERO(&fdsSelectWrite); FD_SET(hp->listenSocket,&fdsSelectRead); iSelectMaxFds=hp->listenSocket; if (hp->udpSocket) { FD_SET(hp->udpSocket, &fdsSelectRead); if (hp->udpSocket > iSelectMaxFds) iSelectMaxFds = hp->udpSocket; } if (hp->flags & FLAG_ENABLE_PROXY) { int iError = 0; socklen_t iOptSize = sizeof(int); if (getsockopt(hp->proxySocket, SOL_SOCKET, SO_ERROR, (char*)&iError, &iOptSize)) { // if a socket contains a error, close it SYSLOG(LOG_INFO, "[%d] Proxy socket no longer vaild.\n", hp->proxySocket); hp->flags &= ~FLAG_PROXY_CONNECTED; } // proxy enabled if (!(hp->flags & FLAG_PROXY_CONNECTED)) { closesocket(hp->proxySocket); hp->proxySocket = socket(AF_INET, SOCK_STREAM, 0); if (connect(hp->proxySocket, (struct sockaddr*)&hp->proxy_addr, sizeof(hp->proxy_addr)) >= 0) { hp->flags |= FLAG_PROXY_CONNECTED; SYSLOG(LOG_INFO, "[%d] Proxy server reconnected\n", hp->proxySocket); } } if (hp->flags & FLAG_PROXY_CONNECTED) { if (hp->proxyBufferBytes <= 0) { hp->proxyBufferBytes = (*hp->pfnProxyData)(hp, PROXY_DATA_REQUESTED, hp->proxyBuffer, PROXY_TX_BUF_SIZE); if (hp->proxyBufferBytes < 0) { hp->flags &= ~FLAG_PROXY_CONNECTED; } } if (hp->proxyBufferBytes > 0) { FD_SET(hp->proxySocket, &fdsSelectWrite); } else { FD_SET(hp->proxySocket, &fdsSelectRead); } if (hp->proxySocket > iSelectMaxFds) iSelectMaxFds = hp->proxySocket; } } // get current time tmCurrentTime=time(NULL); // build descriptor sets and close timed out sockets for (i = 0; i < hp->maxClients; i++) { phsSocketCur = hp->hsSocketQueue + i; // get socket fd sock = phsSocketCur->socket; if (!sock) continue; { int iError=0; socklen_t iOptSize = sizeof(int); if (getsockopt(sock,SOL_SOCKET,SO_ERROR,(char*)&iError,&iOptSize)) { // if a socket contains a error, close it SYSLOG(LOG_INFO,"[%d] Socket no longer vaild.\n",sock); phsSocketCur->flags=FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); continue; } } // check expiration timer (for non-listening, in-use sockets) if (tmCurrentTime > phsSocketCur->tmExpirationTime) { // close connection phsSocketCur->flags=FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); } else { if (ISFLAGSET(phsSocketCur,FLAG_SENDING)) { // add to write descriptor set FD_SET(sock,&fdsSelectWrite); } else { // add to read descriptor set FD_SET(sock,&fdsSelectRead); } // check if new max socket if (sock>iSelectMaxFds) { iSelectMaxFds=sock; } } } { struct timeval tvSelectWait; // initialize select delay tvSelectWait.tv_sec = timeout / 1000; tvSelectWait.tv_usec = (timeout % 1000) * 1000; // note: using timeval here -> usec not nsec // and check sockets (may take a while!) iRc=select(iSelectMaxFds+1, &fdsSelectRead, &fdsSelectWrite, NULL, &tvSelectWait); } if (iRc <= 0) { return; } // check if any udp socket to read if (hp->udpSocket && FD_ISSET(hp->udpSocket, &fdsSelectRead)) { hp->pfnIncomingUDP(hp); } // check proxy server if ((hp->flags & FLAG_ENABLE_PROXY) && hp->pfnProxyData) { if (FD_ISSET(hp->proxySocket, &fdsSelectRead)) { char data[PROXY_RX_BUF_SIZE]; int len = recv(hp->proxySocket, data, sizeof(data) - 1, 0); if (len > 0) { data[len] = 0; (*hp->pfnProxyData)(hp, PROXY_DATA_RECEIVED, data, len); } } if (FD_ISSET(hp->proxySocket, &fdsSelectWrite)) { if (hp->proxyBufferBytes > 0) { if (send(hp->proxySocket, hp->proxyBuffer, hp->proxyBufferBytes, 0) == hp->proxyBufferBytes) { // sent SYSLOG(LOG_INFO, "[%d] %d bytes sent to proxy server\n", hp->proxySocket, hp->proxyBufferBytes); hp->proxyBufferBytes = 0; } else { hp->flags &= ~FLAG_PROXY_CONNECTED; } } } } // check which sockets are read/write able for (i = 0; i < hp->maxClients; i++) { BOOL bRead; BOOL bWrite; phsSocketCur = hp->hsSocketQueue + i; // get socket fd sock = phsSocketCur->socket; if (!sock) continue; // get read/write status for socket bRead = FD_ISSET(sock, &fdsSelectRead); bWrite = FD_ISSET(sock, &fdsSelectWrite); if (bRead || bWrite) { iRc = -1; if (ISFLAGSET(phsSocketCur,FLAG_SENDING) && bWrite) { iRc=_mwProcessWriteSocket(hp, phsSocketCur); } else if (bRead) { SETFLAG(phsSocketCur, FLAG_RECEIVING); iRc=_mwProcessReadSocket(hp,phsSocketCur); } if (iRc == 0) { // reset expiration timer phsSocketCur->tmExpirationTime = time(NULL) + HTTP_EXPIRATION_TIME; } else { if (iRc == -1) { SETFLAG(phsSocketCur, FLAG_CONN_CLOSE); } _mwCloseSocket(hp, phsSocketCur); } } } // check if any socket to accept and accept the socket if (FD_ISSET(hp->listenSocket, &fdsSelectRead)) do { // find empty slot phsSocketCur = 0; for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].socket == 0) { phsSocketCur = hp->hsSocketQueue + i; break; } } if (!phsSocketCur) { // all slots occupied // find longest waiting idle socket and close it time_t earliest = 0; for (i = 0; i < hp->maxClients; i++) { if (!ISFLAGSET((hp->hsSocketQueue + i), FLAG_RECEIVING | FLAG_SENDING) && (earliest == 0 || hp->hsSocketQueue[i].tmExpirationTime < earliest)) { phsSocketCur = hp->hsSocketQueue + i; earliest = hp->hsSocketQueue[i].tmExpirationTime; } } if (!phsSocketCur) { SYSLOG(LOG_INFO,"Connection denied\n"); break; } else { SETFLAG(phsSocketCur, FLAG_CONN_CLOSE); _mwCloseSocket(hp, phsSocketCur); } } phsSocketCur->socket = _mwAcceptSocket(hp,&sinaddr); if (phsSocketCur->socket == 0) break; phsSocketCur->ipAddr.laddr=ntohl(sinaddr.sin_addr.s_addr); SYSLOG(LOG_INFO,"[%d] Client: %d.%d.%d.%d\n", phsSocketCur->socket, phsSocketCur->ipAddr.caddr[3], phsSocketCur->ipAddr.caddr[2], phsSocketCur->ipAddr.caddr[1], phsSocketCur->ipAddr.caddr[0]); hp->stats.clientCount++; //fill structure with data _mwInitSocketData(phsSocketCur); phsSocketCur->tmExpirationTime = time(NULL) + HTTP_EXPIRATION_TIME; //update max client count if (hp->stats.clientCount>hp->stats.clientCountMax) hp->stats.clientCountMax=hp->stats.clientCount; } while(0); } // end of _mwHttpThread void mwServerExit(HttpParam* hp) { int i; // cleanup _mwCloseAllConnections(hp); for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].buffer) free(hp->hsSocketQueue[i].buffer); } if (hp->hsSocketQueue) { free(hp->hsSocketQueue); hp->hsSocketQueue = 0; } if (hp->proxyBuffer) { free(hp->proxyBuffer); hp->proxyBuffer = 0; } // clear state vars hp->bKillWebserver = FALSE; hp->bWebserverRunning = FALSE; #ifdef WIN32 WSACleanup(); #endif } //////////////////////////////////////////////////////////////////////////// // _mwAcceptSocket // Accept an incoming connection //////////////////////////////////////////////////////////////////////////// SOCKET _mwAcceptSocket(HttpParam* hp, struct sockaddr_in *sinaddr) { socklen_t namelen = sizeof(struct sockaddr); SOCKET socket = accept(hp->listenSocket, (struct sockaddr*)sinaddr, &namelen); _mwSetSocketOpts(socket); return socket; } // end of _mwAcceptSocket int _mwBuildHttpHeader(HttpParam* hp, HttpSocket *phsSocket, time_t contentDateTime, char* buffer) { char *p = buffer; char *end = buffer + 512; const char *status; BOOL keepalive = !ISFLAGSET(phsSocket,FLAG_CONN_CLOSE); if (phsSocket->response.statusCode >= 200 && phsSocket->response.statusCode < 200 + sizeof(status200) / sizeof(status200[0])) { status = status200[phsSocket->response.statusCode - 200]; } else if (phsSocket->response.statusCode >= 300 && phsSocket->response.statusCode < 300 + sizeof(status300) / sizeof(status300[0])) { status = status300[phsSocket->response.statusCode - 300]; } else if (phsSocket->response.statusCode >= 400 && phsSocket->response.statusCode < 400 + sizeof(status400) / sizeof(status400[0])) { status = status400[phsSocket->response.statusCode - 400]; } else if (phsSocket->response.statusCode >= 500 && phsSocket->response.statusCode < 500 + sizeof(status500) / sizeof(status500[0])) { status = status500[phsSocket->response.statusCode - 500]; } else { status = ""; } p += snprintf(p, end - p, HTTP200_HEADER, #ifdef ENABLE_RTSP (phsSocket->flags & (FLAG_REQUEST_DESCRIBE | FLAG_REQUEST_SETUP)) ? "RTSP/1.0" : "HTTP/1.1", #else "HTTP/1.1", #endif phsSocket->response.statusCode, status, HTTP_SERVER_NAME, keepalive ? "keep-alive" : "close"); if (keepalive) { p += snprintf(p, end - p, "Keep-Alive: timeout=%u, max=1000\r\n", HTTP_KEEPALIVE_TIME); } if (!(hp->flags & FLAG_DISABLE_RANGE)) { p += snprintf(p, end - p, "Accept-Ranges: bytes\r\n"); } if ((int)contentDateTime > 0) { p += snprintf(p, end - p, "Last-Modified: "); p += mwGetHttpDateTime(contentDateTime, p, end - p); strcpy(p, "\r\n"); p+=2; } if (phsSocket->request.iCSeq) { p += snprintf(p, end - p, "CSeq: %d\r\n", phsSocket->request.iCSeq); } if (phsSocket->response.contentLength > 0) { p += snprintf(p, end - p, "Content-Type: %s\r\n", phsSocket->mimeType ? phsSocket->mimeType : contentTypeTable[phsSocket->response.fileType]); if (phsSocket->request.startByte) { p += snprintf(p, end - p, "Content-Range: bytes %u-%u/*\r\n", phsSocket->request.startByte, phsSocket->response.contentLength); } } if (!(phsSocket->flags & FLAG_CHUNK)) { p+=snprintf(p, end - p,"Content-Length: %u\r\n", phsSocket->response.contentLength); } else { p += sprintf(p, "Transfer-Encoding: chunked\r\n"); } if (phsSocket->response.statusCode == 301 || phsSocket->response.statusCode == 307) { p += sprintf(p, "Location: %s\r\n", phsSocket->pucData); } strcpy(p, "\r\n"); return (int)(p- buffer + 2); } int mwParseQueryString(UrlHandlerParam* up) { if (up->iVarCount==-1) { //parsing variables from query string char *p,*s; // get start of query string s = strchr(up->pucRequest, '?'); if (s) { *(s++) = 0; } else if (ISFLAGSET(up->hs,FLAG_REQUEST_POST)){ s = up->hs->request.pucPayload; if (s && s[0] == '<') s = 0; } if (s && *s) { int i; int n = 1; //get number of variables for (p = s; *p ; p++) { if (*p < 32 || *p > 127) return 0; if (*p == '&') n++; } up->pxVars = calloc(n + 1, sizeof(HttpVariables)); up->iVarCount = n; //store variable name and value for (i = 0, p = s; i < n; p++) { switch (*p) { case '=': if (!(up->pxVars + i)->name) { *p = 0; (up->pxVars + i)->name = s; s=p+1; } break; case 0: case '&': *p = 0; if ((up->pxVars + i)->name) { (up->pxVars + i)->value = s; mwDecodeString(s); } else { (up->pxVars + i)->name = s; (up->pxVars + i)->value = p; } s = p + 1; i++; break; } } (up->pxVars + n)->name = NULL; } } return up->iVarCount; } //////////////////////////////////////////////////////////////////////////// // _mwBase64Encode // buffer size of out_str is (in_len * 4 / 3 + 1) //////////////////////////////////////////////////////////////////////////// void _mwBase64Encode(const char *in_str, int in_len, char *out_str) { const char base64[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int curr_out_len = 0; int i = 0; char a, b, c; out_str[0] = '\0'; if (in_len <= 0) return; while (i < in_len) { a = in_str[i]; b = (i + 1 >= in_len) ? 0 : in_str[i + 1]; c = (i + 2 >= in_len) ? 0 : in_str[i + 2]; if (i + 2 < in_len) { out_str[curr_out_len++] = (base64[(a >> 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a << 4) & 0x30) + ((b >> 4) & 0xf)]); out_str[curr_out_len++] = (base64[((b << 2) & 0x3c) + ((c >> 6) & 0x3)]); out_str[curr_out_len++] = (base64[c & 0x3F]); } else if (i + 1 < in_len) { out_str[curr_out_len++] = (base64[(a >> 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a << 4) & 0x30) + ((b >> 4) & 0xf)]); out_str[curr_out_len++] = (base64[((b << 2) & 0x3c) + ((c >> 6) & 0x3)]); out_str[curr_out_len++] = '='; } else { out_str[curr_out_len++] = (base64[(a >> 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a << 4) & 0x30) + ((b >> 4) & 0xf)]); out_str[curr_out_len++] = '='; out_str[curr_out_len++] = '='; } i += 3; } out_str[curr_out_len] = '\0'; } //////////////////////////////////////////////////////////////////////////// // _mwGetBaisAuthorization // RETURN VALUE: Authorization string, need to free by caller //////////////////////////////////////////////////////////////////////////// int _mwGetBaisAuthorization(const char* username, const char* password, char* out /*OUT*/) { const char prefix[] = "Basic "; int len = (int)(strlen(username) + 1 + strlen(password)); int out_len = sizeof(prefix) + (len * 4 / 3 + 1) + 2; char *tmp, *p; if (out_len >= MAX_AUTH_INFO_LEN) return -1; tmp = (char*)malloc(len + 1); sprintf(tmp, "%s:%s", username, password); strcpy(out, prefix); p = out + sizeof(prefix) - 1; _mwBase64Encode(tmp, len, p); p += strlen(p); p[0] = '\r'; p[1] = '\n'; p[2] = '\0'; free(tmp); return 0; } //////////////////////////////////////////////////////////////////////////// // _mwSend401AuthorizationRequired //////////////////////////////////////////////////////////////////////////// void _mwSend401AuthorizationRequired(HttpParam* hp, HttpSocket* phsSocket, int reason) { char hdr[128]; const char *body = NULL; int hdrsize = 0; int bodylen; if (reason == AUTH_REQUIRED) { body = "Authentication required"; } else { body = "Authentication failed"; } bodylen = strlen(body); hdrsize = snprintf(hdr, sizeof(hdr), HTTP401_HEADER, "Login", bodylen); SYSLOG(LOG_INFO,"[%d] Authorization Required\n",phsSocket->socket); // send Authorization Required send(phsSocket->socket, hdr, hdrsize, 0); send(phsSocket->socket, body, bodylen, 0); //Below is the work around SETFLAG(phsSocket, FLAG_CONN_CLOSE); _mwCloseSocket(hp, phsSocket); } //////////////////////////////////////////////////////////////////////////// // _mwBasicAuthorizationHandlers // Basic Authorization implement // RETURN VALUE: // -1 (failed) // 0 (no need to authorization) // 1 (successed) // 2 (Authorization needed) //////////////////////////////////////////////////////////////////////////// int _mwBasicAuthorizationHandlers(HttpParam* hp, HttpSocket* phsSocket) { AuthHandler* pah; char* path = phsSocket->request.pucPath; int ret = AUTH_NO_NEED; if (phsSocket->ipAddr.laddr == INADDR_LOOPBACK) { return ret; } for (pah = hp->pxAuthHandler; pah && pah->pchUrlPrefix; pah++) { //printf("\req path:%s prefix:0x%x, username:0x%x, password:0x%x\n", path, pah->pchUrlPrefix, pah->pchUsername, pah->pchPassword); if (*pah->pchUrlPrefix && strncmp(path, pah->pchUrlPrefix, strlen(pah->pchUrlPrefix)) != 0) continue; if (pah->pchUsername == NULL || *pah->pchUsername == '\0' || pah->pchPassword == NULL || *pah->pchPassword == '\0') continue; if (*pah->pchAuthString == '\0') { if (_mwGetBaisAuthorization(pah->pchUsername, pah->pchPassword, pah->pchAuthString) != 0) continue; } if (phsSocket->request.pucAuthInfo == NULL) { ret = AUTH_REQUIRED; //Need to auth break; } else if (strncmp(phsSocket->request.pucAuthInfo, pah->pchAuthString, strlen(pah->pchAuthString)) == 0) { //FIXME: phsSocket->request.pucAuthInfo = pah->pchOtherInfo ? pah->pchOtherInfo : "group=admin"; ret = AUTH_SUCCESSED; //successed break; } else { ret = AUTH_FAILED; //Failed, try next } } return ret; } int _mwCheckUrlHandlers(HttpParam* hp, HttpSocket* phsSocket) { UrlHandler* puh; UrlHandlerParam up; int ret=0; char* path = phsSocket->request.pucPath; while (*path && *path == '/') path++; up.pxVars=NULL; for (puh=hp->pxUrlHandler; puh && puh->pchUrlPrefix; puh++) { size_t prefixLen=strlen(puh->pchUrlPrefix); if (puh->pfnUrlHandler && ((prefixLen == 0 && *path == 0) || (prefixLen && !strncmp(path,puh->pchUrlPrefix,prefixLen)))) { //URL prefix matches memset(&up, 0, sizeof(up)); up.hp=hp; up.hs = phsSocket; up.bufSize=(int)phsSocket->bufferSize; up.pucRequest=path+prefixLen; up.pucHeader=phsSocket->buffer; up.pucBuffer=phsSocket->pucData; up.pucBuffer[0]=0; up.pucPayload = phsSocket->request.pucPayload; up.payloadSize = phsSocket->request.payloadSize; up.iVarCount=-1; phsSocket->handler = puh; if (strchr(up.pucRequest, '?')) mwParseQueryString(&up); ret=(*puh->pfnUrlHandler)(&up); if (!ret) continue; if (phsSocket->response.statusCode >= 500) phsSocket->flags |= FLAG_CONN_CLOSE; phsSocket->flags|=ret; phsSocket->response.fileType = up.contentType; if (ret & FLAG_DATA_RAW) { SETFLAG(phsSocket, FLAG_DATA_RAW); phsSocket->pucData=up.pucBuffer; phsSocket->contentLength=up.contentLength; phsSocket->response.contentLength=up.contentLength; if (ret & FLAG_TO_FREE) { phsSocket->ptr=up.pucBuffer; //keep the pointer which will be used to free memory later } } else if (ret & FLAG_DATA_STREAM) { SETFLAG(phsSocket, FLAG_DATA_STREAM); phsSocket->pucData = up.pucBuffer; phsSocket->contentLength = up.contentLength; phsSocket->response.contentLength = 0; } else if (ret & FLAG_DATA_FILE) { SETFLAG(phsSocket, ret & (FLAG_DATA_FILE | FLAG_ABSOLUTE_PATH)); if (up.pucBuffer[0]) { free(phsSocket->request.pucPath); phsSocket->request.pucPath=strdup(up.pucBuffer); } } else if (ret & FLAG_DATA_REDIRECT) { phsSocket->pucData = up.pucBuffer; } break; } } if (up.pxVars) free(up.pxVars); return ret; } //////////////////////////////////////////////////////////////////////////// // _mwProcessReadSocket // Process a socket (read) //////////////////////////////////////////////////////////////////////////// int _mwProcessReadSocket(HttpParam* hp, HttpSocket* phsSocket) { int iLength = recv(phsSocket->socket, phsSocket->pucData+phsSocket->contentLength, (int)(phsSocket->bufferSize - phsSocket->contentLength - 1), 0); if (iLength <= 0) { return -1; } // add in new data received phsSocket->contentLength += iLength; phsSocket->pucData[phsSocket->contentLength] = 0; // check if end of request if (phsSocket->request.headerSize==0) { int i=0; char *path = 0; char *headerEnd = strstr(phsSocket->buffer, HTTP_HEADER_END); if (!headerEnd) return 0; // reach the end of the header //check request type if (!memcmp(phsSocket->buffer, "GET", 3)) { SETFLAG(phsSocket,FLAG_REQUEST_GET); path = phsSocket->pucData + 5; } else if (!memcmp(phsSocket->buffer, "POST", 4)) { SETFLAG(phsSocket,FLAG_REQUEST_POST); path = phsSocket->pucData + 6; } else { SYSLOG(LOG_INFO,"[%d] Unsupported method\n",phsSocket->socket); phsSocket->request.pucPath = 0; return -1; } // count connections from this IP and duplicated connection if (hp->maxClientsPerIP && _mwGetConnFromIP(hp, phsSocket->ipAddr) > hp->maxClientsPerIP) { // too many connection from the same IP SYSLOG(LOG_INFO,"[%d] Too many connections from same IP\n", phsSocket->socket); send(phsSocket->socket, HTTP403_HEADER, sizeof(HTTP403_HEADER) - 1, 0); return -1; } phsSocket->request.headerSize = (int)(headerEnd - phsSocket->buffer + 4); if (_mwParseHttpHeader(phsSocket)) { SYSLOG(LOG_INFO,"Error parsing request\n"); return -1; } else { int pathLen; if ((hp->flags & FLAG_DISABLE_RANGE) && phsSocket->request.startByte > 0) { send(phsSocket->socket, HTTP403_HEADER, sizeof(HTTP403_HEADER) - 1, 0); return -1; } // keep request path for (i = 0; i < MAX_REQUEST_PATH_LEN; i++) { if ((path[i] == ' ' && (!strncmp(path + i + 1, "HTTP/", 5) || !strncmp(path + i + 1, "RTSP/", 5))) || path[i] == '\r') { break; } } pathLen = i; if (pathLen >= MAX_REQUEST_PATH_LEN) { return -1; } phsSocket->request.pucPath = malloc(pathLen + 1); memcpy(phsSocket->request.pucPath, path, pathLen); phsSocket->request.pucPath[pathLen] = 0; //SYSLOG(LOG_INFO, "[%d] Request path: %s\n", phsSocket->socket, phsSocket->request.pucPath); if (ISFLAGSET(phsSocket,FLAG_REQUEST_POST)) { if (!phsSocket->request.pucPayload) { // first receive of payload, prepare for next receive if (phsSocket->request.payloadSize > MAX_POST_PAYLOAD_SIZE) phsSocket->request.payloadSize = MAX_POST_PAYLOAD_SIZE; phsSocket->bufferSize = phsSocket->request.payloadSize + 1; phsSocket->request.pucPayload = malloc(phsSocket->bufferSize); phsSocket->pucData = phsSocket->request.pucPayload; // payload length already received phsSocket->contentLength -= phsSocket->request.headerSize; // copy already received payload to payload buffer if (phsSocket->contentLength > phsSocket->request.payloadSize) { phsSocket->contentLength = phsSocket->request.payloadSize; } memcpy(phsSocket->request.pucPayload, phsSocket->buffer + phsSocket->request.headerSize, phsSocket->contentLength); phsSocket->request.pucPayload[phsSocket->contentLength]=0; } } } } if (phsSocket->request.payloadSize > 0 && phsSocket->contentLength < (int)phsSocket->request.payloadSize) { // there is more data return 0; } // add header zero terminator phsSocket->buffer[phsSocket->request.headerSize]=0; if (phsSocket->request.headerSize) { phsSocket->pucData = phsSocket->buffer + phsSocket->request.headerSize + 4; phsSocket->bufferSize = HTTP_BUFFER_SIZE - phsSocket->request.headerSize - 4; } else { phsSocket->pucData = phsSocket->buffer; phsSocket->bufferSize = HTTP_BUFFER_SIZE; } hp->stats.reqCount++; phsSocket->reqCount++; if (hp->pxAuthHandler != NULL) { int ret = _mwBasicAuthorizationHandlers(hp, phsSocket); switch (ret) { case AUTH_NO_NEED: //No need to auth case AUTH_SUCCESSED: //Successed break; case AUTH_REQUIRED: //Authorization needed case AUTH_FAILED: default://Failed _mwSend401AuthorizationRequired(hp, phsSocket, ret); return 0; } } if (!hp->pxUrlHandler || !_mwCheckUrlHandlers(hp,phsSocket)) SETFLAG(phsSocket,FLAG_DATA_FILE); // set state to SENDING (actual sending will occur on next select) CLRFLAG(phsSocket,FLAG_RECEIVING) if (phsSocket->request.iHttpVer == 0) { CLRFLAG(phsSocket, FLAG_CHUNK); } if (ISFLAGSET(phsSocket,FLAG_DATA_RAW | FLAG_DATA_STREAM)) { SETFLAG(phsSocket,FLAG_SENDING); return _mwStartSendRawData(hp, phsSocket); } else if (ISFLAGSET(phsSocket,FLAG_DATA_FILE)) { SETFLAG(phsSocket,FLAG_SENDING); return _mwStartSendFile(hp,phsSocket); } else if (ISFLAGSET(phsSocket,FLAG_DATA_REDIRECT)) { _mwRedirect(phsSocket, phsSocket->pucData); return 0; } SYSLOG(LOG_INFO,"Invalid data flag specified\n"); return -1; } // end of _mwProcessReadSocket //////////////////////////////////////////////////////////////////////////// // _mwProcessWriteSocket // Process a socket (write) //////////////////////////////////////////////////////////////////////////// int _mwProcessWriteSocket(HttpParam *hp, HttpSocket* phsSocket) { if (phsSocket->contentLength<=0 && !ISFLAGSET(phsSocket,FLAG_DATA_STREAM)) { return 1; } //SYSLOG(LOG_INFO,"[%d] sending data\n",phsSocket->socket); if (ISFLAGSET(phsSocket,FLAG_DATA_RAW|FLAG_DATA_STREAM)) { return _mwSendRawDataChunk(hp, phsSocket); } else if (ISFLAGSET(phsSocket,FLAG_DATA_FILE)) { return _mwSendFileChunk(hp, phsSocket); } else { SYSLOG(LOG_INFO,"Invalid content source\n"); return -1; } } // end of _mwProcessWriteSocket //////////////////////////////////////////////////////////////////////////// // _mwCloseSocket // Close an open connection //////////////////////////////////////////////////////////////////////////// void _mwCloseSocket(HttpParam* hp, HttpSocket* phsSocket) { if (phsSocket->socket == 0) return; if (phsSocket->fp) { fclose(phsSocket->fp); phsSocket->fp = 0; hp->stats.openedFileCount--; } if (phsSocket->request.pucPayload) { free(phsSocket->request.pucPayload); phsSocket->request.pucPayload = 0; } if (phsSocket->handler && (ISFLAGSET(phsSocket,FLAG_DATA_STREAM) || ISFLAGSET(phsSocket,FLAG_CLOSE_CALLBACK | FLAG_CONN_CLOSE) == (FLAG_CLOSE_CALLBACK | FLAG_CONN_CLOSE))) { UrlHandlerParam up; UrlHandler* pfnHandler = (UrlHandler*)phsSocket->handler; memset(&up, 0, sizeof(up)); up.hs = phsSocket; up.hp = hp; //notify the handler of closed connection (pfnHandler->pfnUrlHandler)(&up); //unbind handler phsSocket->handler = 0; } if (ISFLAGSET(phsSocket,FLAG_TO_FREE) && phsSocket->ptr) { free(phsSocket->ptr); phsSocket->ptr=NULL; CLRFLAG(phsSocket, FLAG_TO_FREE); } if (phsSocket->request.pucPath) { free(phsSocket->request.pucPath); phsSocket->request.pucPath = 0; } if (!ISFLAGSET(phsSocket,FLAG_CONN_CLOSE) && phsSocket->reqCount < HTTP_KEEPALIVE_MAX) { _mwInitSocketData(phsSocket); //reset flag bits phsSocket->tmExpirationTime=time(NULL)+HTTP_KEEPALIVE_TIME; return; } closesocket(phsSocket->socket); phsSocket->reqCount = 0; hp->stats.clientCount--; SYSLOG(LOG_INFO,"[%d] Socket closed, %u connections\n",phsSocket->socket, hp->stats.clientCount); phsSocket->socket = 0; phsSocket->reqCount=0; } // end of _mwCloseSocket void _mwSetSocketOpts(SOCKET socket) { #ifndef WIN32 // set to non-blocking to stop sends from locking up thread int iSockFlags; iSockFlags = fcntl(socket, F_GETFL, 0); iSockFlags |= O_NONBLOCK; fcntl(socket, F_SETFL, iSockFlags); #else u_long iMode = 1; // non-blocking mode ioctlsocket(socket, FIONBIO, &iMode); #endif } int _mwStrCopy(char *dest, const char *src) { int i; for (i=0; src[i]; i++) { dest[i]=src[i]; } dest[i]=0; return i; } int _mwStrHeadMatch(char** pbuf1, const char* buf2) { unsigned int i; char* buf1 = *pbuf1; int x; for(i=0;buf2[i];i++) { if ((x=toupper((int)buf1[i])-toupper((int)buf2[i]))) return 0; } *pbuf1 = buf1 + i; return i; } void _mwSendErrorPage(SOCKET socket, const char* header, const char* body) { char hdr[128]; int len = (int)strlen(body); int hdrsize = snprintf(hdr, sizeof(hdr), header, HTTP_SERVER_NAME, len); send(socket, hdr, hdrsize, 0); send(socket, body, len, 0); } #ifdef WIN32 #define OPEN_FLAG O_RDONLY|0x8000 #else #define OPEN_FLAG O_RDONLY #endif //////////////////////////////////////////////////////////////////////////// // _mwStartSendFile // Setup for sending of a file //////////////////////////////////////////////////////////////////////////// int _mwStartSendFile2(HttpParam* hp, HttpSocket* phsSocket, const char* filePath) { struct stat st = { 0 }; HttpFilePath hfp; BOOL isDirPath = FALSE; if (filePath == NULL) return -1; if (!ISFLAGSET(phsSocket, FLAG_ABSOLUTE_PATH)) { hfp.pchRootPath = hp->pchWebPath; hfp.pchHttpPath = filePath; mwGetLocalFileName(&hfp); } else { strncpy(hfp.cFilePath, filePath, sizeof(hfp.cFilePath)); } if (stat(hfp.cFilePath, &st) == 0) { isDirPath = S_ISDIR(st.st_mode); } if (!*filePath) isDirPath = TRUE; // open file if (!isDirPath) { phsSocket->fp = fopen(hfp.cFilePath, "rb"); } if (!phsSocket->fp) { char *p; if (!isDirPath) { // file/dir not found return -1; } //requesting for directory, first try opening default pages for (p = hfp.cFilePath; *p; p++); *(p++)=SLASH; for (int i = 0; i<sizeof(defaultPages)/sizeof(defaultPages[0]); i++) { stat(hfp.cFilePath, &st); strcpy(p,defaultPages[i]); phsSocket->fp = fopen(hfp.cFilePath, "rb"); if (phsSocket->fp) { hfp.pchExt = strchr(defaultPages[i], '.') + 1; break; } } if (!phsSocket->fp && (hp->flags & FLAG_DIR_LISTING)) { SETFLAG(phsSocket,FLAG_DATA_RAW); if (!hfp.fTailSlash) { p=phsSocket->request.pucPath; while(*p) p++; //seek to the end of the string strcpy(p, "/"); //add a tailing slash while(--p>(char*)phsSocket->request.pucPath) { if (*p=='/') { p++; break; } } _mwRedirect(phsSocket,p); return _mwStartSendRawData(hp, phsSocket); } } } if (phsSocket->fp) { hp->stats.openedFileCount++; fseek(phsSocket->fp, 0, SEEK_END); long fileSize = ftell(phsSocket->fp); phsSocket->response.contentLength = fileSize - phsSocket->request.startByte; if (phsSocket->response.contentLength <= 0) { phsSocket->request.startByte = 0; phsSocket->response.contentLength = fileSize; } if (phsSocket->request.startByte) { fseek(phsSocket->fp, (long)phsSocket->request.startByte, SEEK_SET); phsSocket->response.statusCode = 206; } else { fseek(phsSocket->fp, 0, SEEK_SET); } if (!phsSocket->response.fileType && hfp.pchExt) { phsSocket->response.fileType=mwGetContentType(hfp.pchExt); } } else { return -1; } //SYSLOG(LOG_INFO,"File/requested size: %d/%d\n",st.st_size,phsSocket->response.contentLength); // build http header phsSocket->contentLength=_mwBuildHttpHeader( hp, phsSocket, st.st_mtime, phsSocket->pucData); phsSocket->response.headerBytes = phsSocket->contentLength; phsSocket->response.sentBytes = 0; return 0; } // end of _mwStartSendFile2 //////////////////////////////////////////////////////////////////////////// // _mwStartSendFile // Setup for sending of a file //////////////////////////////////////////////////////////////////////////// int _mwStartSendFile(HttpParam* hp, HttpSocket* phsSocket) { int ret; #if MAX_OPEN_FILES if (hp->stats.openedFileCount >= MAX_OPEN_FILES) return 0; #endif ret = _mwStartSendFile2(hp, phsSocket, phsSocket->request.pucPath); if (ret != 0) { SYSLOG(LOG_INFO,"[%d] Not found - %s\n",phsSocket->socket, phsSocket->request.pucPath); _mwSendErrorPage(phsSocket->socket, HTTP404_HEADER, HTTP404_BODY); } return ret; } //end of _mwStartSendFile //////////////////////////////////////////////////////////////////////////// // _mwSendFileChunk // Send a chunk of a file //////////////////////////////////////////////////////////////////////////// int _mwSendFileChunk(HttpParam *hp, HttpSocket* phsSocket) { int iBytesWritten; int iBytesRead; if (phsSocket->contentLength > 0) { if ((phsSocket->flags & FLAG_CHUNK) && ISFLAGSET(phsSocket, FLAG_HEADER_SENT)) { char buf[16]; iBytesRead = snprintf(buf, sizeof(buf), "%X\r\n", phsSocket->contentLength); iBytesWritten = send(phsSocket->socket, buf, iBytesRead, 0); } // send a chunk of data iBytesWritten=send(phsSocket->socket, phsSocket->pucData,(int)phsSocket->contentLength, 0); if (iBytesWritten<=0) { // close connection SETFLAG(phsSocket,FLAG_CONN_CLOSE); fclose(phsSocket->fp); hp->stats.openedFileCount--; phsSocket->fp = 0; return -1; } SETFLAG(phsSocket, FLAG_HEADER_SENT); hp->stats.totalSentBytes+=iBytesWritten; phsSocket->response.sentBytes+=iBytesWritten; phsSocket->pucData+=iBytesWritten; phsSocket->contentLength-=iBytesWritten; // if only partial data sent just return wait the remaining data to be sent next time if (phsSocket->contentLength>0) return 0; } // used all buffered data - load next chunk of file phsSocket->pucData=phsSocket->buffer; iBytesRead = fread(phsSocket->buffer, 1, HTTP_BUFFER_SIZE, phsSocket->fp); if (iBytesRead == -1 && errno == 8) return 0; // try reading again next time if (iBytesRead<=0) { // finished with a file int remainBytes = (int)(phsSocket->response.contentLength + phsSocket->response.headerBytes - phsSocket->response.sentBytes); if (remainBytes > 0) { if (remainBytes>HTTP_BUFFER_SIZE) remainBytes=HTTP_BUFFER_SIZE; memset(phsSocket->buffer,0,remainBytes); phsSocket->contentLength=remainBytes; return 0; } else { if (phsSocket->flags & FLAG_CHUNK) { send(phsSocket->socket, "0\r\n\r\n", 5, 0); } if (phsSocket->fp) { fclose(phsSocket->fp); phsSocket->fp = 0; hp->stats.openedFileCount--; } return 1; } } phsSocket->contentLength=iBytesRead; return 0; } // end of _mwSendFileChunk //////////////////////////////////////////////////////////////////////////// // _mwStartSendRawData // Start sending raw data blocks //////////////////////////////////////////////////////////////////////////// int _mwStartSendRawData(HttpParam *hp, HttpSocket* phsSocket) { if (ISFLAGSET(phsSocket, FLAG_CUSTOM_HEADER)) { return _mwSendRawDataChunk(hp, phsSocket); } else { char header[HTTP200_HDR_EST_SIZE]; int offset=0,hdrsize,bytes; hdrsize=_mwBuildHttpHeader(hp, phsSocket, 0, header); // send http header do { bytes=send(phsSocket->socket, header+offset, hdrsize-offset, 0); if (bytes<=0) break; offset+=bytes; hp->stats.totalSentBytes+=bytes; } while (offset<hdrsize); if (bytes<=0) { // failed to send header (socket may have been closed by peer) SYSLOG(LOG_INFO,"Failed to send header\n"); return -1; } } return 0; } //////////////////////////////////////////////////////////////////////////// // _mwSendRawDataChunk // Send a chunk of a raw data block //////////////////////////////////////////////////////////////////////////// int _mwSendRawDataChunk(HttpParam *hp, HttpSocket* phsSocket) { int iBytesWritten = 0; if (phsSocket->flags & FLAG_CHUNK) { char buf[16]; int bytes = snprintf(buf, sizeof(buf), "%x\r\n", phsSocket->contentLength); iBytesWritten = send(phsSocket->socket, buf, bytes, 0); if (iBytesWritten<=0) return -1; hp->stats.totalSentBytes+=iBytesWritten; } // send a chunk of data if (phsSocket->contentLength > 0) { iBytesWritten=(int)send(phsSocket->socket, phsSocket->pucData, phsSocket->contentLength, 0); if (iBytesWritten<=0) { // failure - close connection return -1; } else { hp->stats.totalSentBytes+=iBytesWritten; phsSocket->response.sentBytes+=iBytesWritten; phsSocket->pucData+=iBytesWritten; phsSocket->contentLength-=iBytesWritten; } } else { if (ISFLAGSET(phsSocket,FLAG_DATA_STREAM) && phsSocket->handler) { //load next chuck of raw data UrlHandlerParam up; UrlHandler* pfnHandler = (UrlHandler*)phsSocket->handler; memset(&up, 0, sizeof(up)); up.hs = phsSocket; up.hp = hp; up.pucBuffer=phsSocket->buffer; up.bufSize=HTTP_BUFFER_SIZE; if ((pfnHandler->pfnUrlHandler)(&up) == 0) { if (phsSocket->flags & FLAG_CHUNK) { iBytesWritten = send(phsSocket->socket, "0\r\n\r\n", 5, 0); if (iBytesWritten<=0) return -1; } hp->stats.totalSentBytes+=iBytesWritten; SETFLAG(phsSocket, FLAG_CONN_CLOSE); return 1; // EOF } phsSocket->contentLength = up.contentLength; phsSocket->pucData = up.pucBuffer; } else { if (phsSocket->flags & FLAG_CHUNK) { iBytesWritten = send(phsSocket->socket, "0\r\n\r\n", 5, 0); if (iBytesWritten<=0) return -1; hp->stats.totalSentBytes+=iBytesWritten; } return 1; } } return 0; } // end of _mwSendRawDataChunk //////////////////////////////////////////////////////////////////////////// // _mwRedirect // Setup for redirect to another file //////////////////////////////////////////////////////////////////////////// void _mwRedirect(HttpSocket* phsSocket, char* pchPath) { /* char* path; // raw (not file) data send mode SETFLAG(phsSocket,FLAG_DATA_RAW); // messages is HTML phsSocket->response.fileType=HTTPFILETYPE_HTML; // build redirect message SYSLOG(LOG_INFO,"[%d] Http redirection to %s\n",phsSocket->socket,pchPath); path = (pchPath == (char*)phsSocket->pucData) ? strdup(pchPath) : (char*)pchPath; phsSocket->contentLength=snprintf(phsSocket->pucData, 512, HTTPBODY_REDIRECT,path); phsSocket->response.contentLength=phsSocket->contentLength; if (path != pchPath) free(path); */ char* url = strdup(pchPath); int n = snprintf(phsSocket->pucData, phsSocket->contentLength, HTTP301_HEADER, HTTP_SERVER_NAME, url); free(url); send(phsSocket->socket, phsSocket->pucData, n, 0); } // end of _mwRedirect //////////////////////////////////////////////////////////////////////////// // _mwStrStrNoCase // Case insensitive version of ststr //////////////////////////////////////////////////////////////////////////// char* _mwStrStrNoCase(char* pchHaystack, char* pchNeedle) { char* pchReturn=NULL; while(*pchHaystack!='\0' && pchReturn==NULL) { if (toupper((int)*pchHaystack)==toupper((int)pchNeedle[0])) { char* pchTempHay=pchHaystack; char* pchTempNeedle=pchNeedle; // start of match while(*pchTempHay!='\0') { if(toupper((int)*pchTempHay)!=toupper((int)*pchTempNeedle)) { // failed to match break; } pchTempNeedle++; pchTempHay++; if (*pchTempNeedle=='\0') { // completed match pchReturn=pchHaystack; break; } } } pchHaystack++; } return pchReturn; } // end of _mwStrStrNoCase //////////////////////////////////////////////////////////////////////////// // _mwDecodeCharacter // Convert and individual character //////////////////////////////////////////////////////////////////////////// char _mwDecodeCharacter(char* s) { register unsigned char v; if (!*s) return 0; if (*s>='a' && *s<='f') v = *s-('a'-'A'+7); else if (*s>='A' && *s<='F') v = *s-7; else v = *s; if (*(++s)==0) return v; v <<= 4; if (*s>='a' && *s<='f') v |= (*s-('a'-'A'+7)) & 0xf; else if (*s>='A' && *s<='F') v |= (*s-7) & 0xf; else v |= *s & 0xf; return v; } // end of _mwDecodeCharacter //////////////////////////////////////////////////////////////////////////// // _mwDecodeString // This function converts URLd characters back to ascii. For example // %3A is '.' //////////////////////////////////////////////////////////////////////////// void mwDecodeString(char* pchString) { int bEnd=FALSE; char* pchInput=pchString; char* pchOutput=pchString; do { switch (*pchInput) { case '%': if (*(pchInput+1)=='\0' || *(pchInput+2)=='\0') { // something not right - terminate the string and abort *pchOutput='\0'; bEnd=TRUE; } else { *pchOutput=_mwDecodeCharacter(pchInput+1); pchInput+=3; } break; case '+': *pchOutput=' '; pchInput++; break; case '\0': bEnd=TRUE; // drop through default: // copy character *pchOutput=*pchInput; pchInput++; } pchOutput++; } while (!bEnd); } // end of mwDecodeString int mwGetContentType(const char *pchExtname) { DWORD dwExt = 0; // check type of file requested if (pchExtname[1]=='\0') { return HTTPFILETYPE_OCTET; } else if (pchExtname[2]=='\0') { memcpy(&dwExt, pchExtname, 2); switch (GETDWORD(pchExtname) & 0xffdfdf) { case FILEEXT_JS: return HTTPFILETYPE_JS; case FILEEXT_TS: return HTTPFILETYPE_TS; } } else if (pchExtname[3]=='\0' || pchExtname[3]=='?') { //identify 3-char file extensions memcpy(&dwExt, pchExtname, sizeof(dwExt)); switch (dwExt & 0xffdfdfdf) { case FILEEXT_HTM: return HTTPFILETYPE_HTML; case FILEEXT_XML: return HTTPFILETYPE_XML; case FILEEXT_XSL: return HTTPFILETYPE_XML; case FILEEXT_TEXT: return HTTPFILETYPE_TEXT; case FILEEXT_XUL: return HTTPFILETYPE_XUL; case FILEEXT_CSS: return HTTPFILETYPE_CSS; case FILEEXT_PNG: return HTTPFILETYPE_PNG; case FILEEXT_JPG: return HTTPFILETYPE_JPEG; case FILEEXT_GIF: return HTTPFILETYPE_GIF; case FILEEXT_SWF: return HTTPFILETYPE_SWF; case FILEEXT_MPA: return HTTPFILETYPE_MPA; case FILEEXT_MPG: return HTTPFILETYPE_MPEG; case FILEEXT_AVI: return HTTPFILETYPE_AVI; case FILEEXT_MP4: return HTTPFILETYPE_MP4; case FILEEXT_MOV: return HTTPFILETYPE_MOV; case FILEEXT_264: return HTTPFILETYPE_264; case FILEEXT_FLV: return HTTPFILETYPE_FLV; case FILEEXT_3GP: return HTTPFILETYPE_3GP; case FILEEXT_ASF: return HTTPFILETYPE_ASF; case FILEEXT_SDP: return HTTPFILETYPE_SDP; } } else if (pchExtname[4]=='\0' || pchExtname[4]=='?') { memcpy(&dwExt, pchExtname, sizeof(dwExt)); //logic-and with 0xdfdfdfdf gets the uppercase of 4 chars switch (dwExt & 0xdfdfdfdf) { case FILEEXT_HTML: return HTTPFILETYPE_HTML; case FILEEXT_MPEG: return HTTPFILETYPE_MPEG; case FILEEXT_M3U8: return HTTPFILETYPE_M3U8; } } return HTTPFILETYPE_OCTET; } int _mwGrabToken(char *pchToken, char chDelimiter, char *pchBuffer, int iMaxTokenSize) { char *p=pchToken; int iCharCopied=0; while (*p && *p!=chDelimiter && iCharCopied < iMaxTokenSize - 1) { *(pchBuffer++)=*(p++); iCharCopied++; } *pchBuffer='\0'; return (*p==chDelimiter)?iCharCopied:0; } int _mwParseHttpHeader(HttpSocket* phsSocket) { int iLen; char *p=phsSocket->buffer; //pointer to header data HttpRequest *req=&phsSocket->request; CLRFLAG(phsSocket, FLAG_MULTIPART); p = strstr(phsSocket->buffer, "HTTP/1."); if (!p) return -1; p += 7; req->iHttpVer = (*p - '0'); //parse the rest of header for(;;) { //look for a valid field name while (*p && *p!='\r') p++; //travel to '\r' if (!*p || !memcmp(p, HTTP_HEADER_END, sizeof(HTTP_HEADER_END))) break; p+=2; //skip "\r\n" if (_mwStrHeadMatch(&p,"Connection: ")) { if (_mwStrHeadMatch(&p,"close")) { SETFLAG(phsSocket,FLAG_CONN_CLOSE); } else if (_mwStrHeadMatch(&p,"Keep-Alive")) { CLRFLAG(phsSocket,FLAG_CONN_CLOSE); //FIXME!! } } else if (_mwStrHeadMatch(&p, "Content-Length: ")) { char buf[32]; p+=_mwGrabToken(p,'\r',buf,sizeof(buf)); phsSocket->request.payloadSize = atoi(buf); } else if (_mwStrHeadMatch(&p, "CSeq: ")) { phsSocket->request.iCSeq = atoi(p); } else if (_mwStrHeadMatch(&p,"Referer: ")) { phsSocket->request.pucReferer= p; } else if (_mwStrHeadMatch(&p,"Range: bytes=")) { char buf[32]; int iEndByte; iLen=_mwGrabToken(p,'-',buf,sizeof(buf)); if (iLen==0) continue; p+=iLen; phsSocket->request.startByte=atoi(buf); iLen=_mwGrabToken(p,'/',buf,sizeof(buf)); if (iLen==0) continue; p+=iLen; iEndByte = atoi(buf); if (iEndByte > 0) phsSocket->response.contentLength = (int)(iEndByte-phsSocket->request.startByte+1); } else if (_mwStrHeadMatch(&p,"Host: ")) { phsSocket->request.pucHost = p; } else if (_mwStrHeadMatch(&p,"Transport: ")) { phsSocket->request.pucTransport = p; } else if (_mwStrHeadMatch(&p,"Authorization: ")) { phsSocket->request.pucAuthInfo = p; } else if (_mwStrHeadMatch(&p,"X-Forwarded-For: ")) { int i; for (i = 3; i >= 0 && *p; i--) { phsSocket->ipAddr.caddr[i] = atoi(p); while (*p && *p != '\r' && *(p++) != '.'); } } } return 0; //end of header } //////////////////////////////////////////////////////////////////////////// // _mwCheckAuthentication // Check if a connected peer is authenticated //////////////////////////////////////////////////////////////////////////// BOOL _mwCheckAuthentication(HttpParam *hp, HttpSocket* phsSocket) { if (!ISFLAGSET(phsSocket,FLAG_AUTHENTICATION)) return TRUE; if (hp->dwAuthenticatedNode != phsSocket->ipAddr.laddr) { // Not authenticated hp->stats.authFailCount++; return FALSE; } // Extend authentication period hp->tmAuthExpireTime = time(NULL) + HTTPAUTHTIMEOUT; return TRUE; } //////////////////////////// END OF FILE ///////////////////////////////////
2c2a1270540bb62f0e9abbf9f0a67f59ffa1c823
7711ed7355631f410d054be99432db85a27df6cb
/examples/WatchFaces/Mario/mario.h
2355b09c1cdd9032d2902bc35e67566bf7836ae9
[ "MIT" ]
permissive
sqfmi/Watchy
f88b71df87f6564a876fd97499ba63afe28d58c7
342eb48a497eb3dcb1ec03c5c156937fdec07ba9
refs/heads/master
2023-08-21T20:21:02.779533
2023-04-25T18:37:44
2023-04-25T18:37:44
220,497,210
1,708
310
MIT
2023-06-16T04:24:44
2019-11-08T15:41:00
C
UTF-8
C
false
false
54,638
h
mario.h
// '0', 44x44px const unsigned char mario0 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '1', 44x44px const unsigned char mario1 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x00, 0xff, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xff, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x03, 0x00, 0xc0, 0x01, 0x70, 0xe0, 0x03, 0x00, 0xc0, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0xc0, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0xc0, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0xc0, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0xc0, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0xc0, 0x01, 0x70, 0xe0, 0x0f, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x0f, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x00, 0xc0, 0xc0, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0xc0, 0x01, 0x70, 0xe0, 0x0f, 0xc0, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xc0, 0xfc, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '2', 44x44px const unsigned char mario2 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xff, 0xe1, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xe1, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x01, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x07, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x07, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x38, 0x0f, 0xc2, 0xb0, 0xd0, 0x00, 0x38, 0x0f, 0xc1, 0x70, 0xe0, 0x00, 0xc0, 0x0c, 0x02, 0xb0, 0xd0, 0x00, 0xc0, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0x00, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0x00, 0xfc, 0x01, 0x70, 0xe0, 0x30, 0x00, 0xc0, 0x02, 0xb0, 0xd0, 0x30, 0x00, 0xc0, 0x01, 0x70, 0xe0, 0xc0, 0x00, 0xff, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0xff, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xff, 0xff, 0xff, 0xc2, 0xb0, 0xd0, 0xff, 0xff, 0xff, 0xc1, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '3', 44x44px const unsigned char mario3 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xff, 0xe1, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xe1, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x07, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x07, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x18, 0x03, 0xc1, 0x70, 0xe0, 0x00, 0x18, 0x03, 0xc2, 0xb0, 0xd0, 0x00, 0x18, 0x03, 0xc1, 0x70, 0xe0, 0x00, 0x07, 0x83, 0xc2, 0xb0, 0xd0, 0x00, 0x07, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xe1, 0x80, 0xc2, 0xb0, 0xd0, 0xff, 0xe1, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '4', 44x44px const unsigned char mario4 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x00, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x00, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x03, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x03, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x30, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x30, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x30, 0x1e, 0x0c, 0x01, 0x70, 0xe0, 0x30, 0x1e, 0x0c, 0x02, 0xb0, 0xd0, 0x30, 0x66, 0x0c, 0x01, 0x70, 0xe0, 0x30, 0x66, 0x0c, 0x02, 0xb0, 0xd0, 0x30, 0x7e, 0x0f, 0xc1, 0x70, 0xe0, 0x30, 0x7e, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xff, 0xfc, 0x0f, 0xc2, 0xb0, 0xd0, 0xff, 0xfc, 0x0f, 0xc1, 0x70, 0xe0, 0x00, 0x0c, 0x0c, 0x02, 0xb0, 0xd0, 0x00, 0x0c, 0x0c, 0x01, 0x70, 0xe0, 0x00, 0x0c, 0x0c, 0x02, 0xb0, 0xd0, 0x00, 0x0c, 0x0c, 0x01, 0x70, 0xe0, 0x00, 0x0c, 0x0c, 0x02, 0xb0, 0xd0, 0x00, 0x0c, 0x0c, 0x01, 0x70, 0xe0, 0x00, 0x0f, 0xfc, 0x02, 0xb0, 0xd0, 0x00, 0x0f, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '5', 44x44px const unsigned char mario5 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0xff, 0xff, 0xff, 0xc1, 0x70, 0xe0, 0xff, 0xff, 0xff, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0xff, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0xff, 0xc2, 0xb0, 0xd0, 0xc0, 0x60, 0x00, 0x01, 0x70, 0xe0, 0xc0, 0x60, 0x00, 0x02, 0xb0, 0xd0, 0xc0, 0x7f, 0xfc, 0x01, 0x70, 0xe0, 0xc0, 0x7f, 0xfc, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0xc0, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xff, 0xfe, 0x0f, 0xc2, 0xb0, 0xd0, 0x3f, 0xff, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x01, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x01, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xe1, 0x80, 0xc2, 0xb0, 0xd0, 0xff, 0xe1, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '6', 44x44px const unsigned char mario6 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x03, 0xff, 0xff, 0xc1, 0x70, 0xe0, 0x03, 0xff, 0xff, 0xc2, 0xb0, 0xd0, 0x0c, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0x30, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0x30, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0xff, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0xff, 0xc2, 0xb0, 0xd0, 0xc0, 0x60, 0x00, 0x01, 0x70, 0xe0, 0xc0, 0x60, 0x00, 0x02, 0xb0, 0xd0, 0xc0, 0x7f, 0xfc, 0x01, 0x70, 0xe0, 0xc0, 0x7f, 0xfc, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0xc0, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '7', 44x44px const unsigned char mario7 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0xff, 0xff, 0xff, 0xc1, 0x70, 0xe0, 0xff, 0xff, 0xff, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xc0, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xff, 0xff, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xff, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x01, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x01, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x06, 0x03, 0x01, 0x70, 0xe0, 0x00, 0x06, 0x03, 0x02, 0xb0, 0xd0, 0x00, 0x18, 0x0c, 0x01, 0x70, 0xe0, 0x00, 0x18, 0x0c, 0x02, 0xb0, 0xd0, 0x00, 0x60, 0x30, 0x01, 0x70, 0xe0, 0x00, 0x60, 0x30, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0x80, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0x80, 0xc0, 0x01, 0x70, 0xe0, 0x01, 0xff, 0xc0, 0x02, 0xb0, 0xd0, 0x01, 0xff, 0xc0, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '8', 44x44px const unsigned char mario8 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xf0, 0x00, 0x03, 0xc1, 0x70, 0xe0, 0xf0, 0x00, 0x03, 0xc2, 0xb0, 0xd0, 0xf0, 0x00, 0x03, 0xc1, 0x70, 0xe0, 0xf0, 0x7f, 0x83, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // '9', 44x44px const unsigned char mario9 [] PROGMEM = { 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x38, 0x00, 0x00, 0x00, 0x0a, 0xc0, 0xd0, 0x00, 0x00, 0x00, 0x05, 0x70, 0xe0, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd0, 0x0f, 0xff, 0xfc, 0x01, 0x70, 0xe0, 0x0f, 0xff, 0xfc, 0x02, 0xb0, 0xd0, 0x0c, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0x0c, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xfc, 0x00, 0x0f, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x0f, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x61, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x61, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x7f, 0x80, 0xc2, 0xb0, 0xd0, 0xc0, 0x7f, 0x80, 0xc1, 0x70, 0xe0, 0xfc, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0xfc, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0x0c, 0x00, 0x00, 0xc2, 0xb0, 0xd0, 0x0c, 0x00, 0x00, 0xc1, 0x70, 0xe0, 0x0f, 0xff, 0x80, 0xc2, 0xb0, 0xd0, 0x0f, 0xff, 0x80, 0xc1, 0x70, 0xe0, 0x00, 0x01, 0x80, 0xc2, 0xb0, 0xd0, 0x00, 0x01, 0x80, 0xc1, 0x70, 0xe0, 0xff, 0xff, 0x80, 0xc2, 0xb0, 0xd0, 0xff, 0xff, 0x80, 0xc1, 0x70, 0xe0, 0xc0, 0x00, 0x03, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x03, 0x01, 0x70, 0xe0, 0xc0, 0x00, 0x0c, 0x02, 0xb0, 0xd0, 0xc0, 0x00, 0x0c, 0x01, 0x70, 0xe0, 0xff, 0xff, 0xf0, 0x02, 0xb0, 0xd0, 0xff, 0xff, 0xf0, 0x01, 0x70, 0xe8, 0x00, 0x00, 0x00, 0x02, 0xb0, 0xd4, 0x00, 0x00, 0x00, 0x05, 0x70, 0xea, 0x00, 0x00, 0x00, 0x0a, 0xb0, 0x35, 0x55, 0x55, 0x55, 0x55, 0xc0, 0x3a, 0xaa, 0xaa, 0xaa, 0xaa, 0xc0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00 }; // 'bg', 200x200px const unsigned char mariobg [] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xfe, 0xff, 0xfe, 0xbf, 0xff, 0xaf, 0xff, 0xeb, 0xff, 0xfb, 0xff, 0xfa, 0xff, 0xfe, 0xbf, 0xff, 0xaf, 0xff, 0xef, 0xff, 0xeb, 0xff, 0xfa, 0xe4, 0x7f, 0xfc, 0x7f, 0xfc, 0x4f, 0xff, 0x47, 0xff, 0xc5, 0xff, 0xe4, 0xff, 0xf4, 0x7f, 0xfc, 0x5f, 0xfe, 0x47, 0xff, 0xc7, 0xff, 0xc4, 0xff, 0xf4, 0xaa, 0xaf, 0xea, 0xaf, 0xea, 0xab, 0xfa, 0xaa, 0xfe, 0xaa, 0xbf, 0xaa, 0xbf, 0xaa, 0xaf, 0xea, 0xab, 0xfa, 0xaa, 0xfe, 0xaa, 0xfe, 0xaa, 0xbf, 0xaa, 0x11, 0x17, 0x91, 0x13, 0xd1, 0x11, 0xf1, 0x11, 0x79, 0x11, 0x1f, 0x11, 0x1f, 0x11, 0x13, 0xd1, 0x11, 0xf1, 0x11, 0x79, 0x11, 0x3d, 0x11, 0x1f, 0x11, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }; // 'coin', 24x30px const unsigned char mariocoin [] PROGMEM = { 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x30, 0x00, 0x0c, 0x30, 0x00, 0x0c, 0x30, 0x14, 0x0c, 0x30, 0x28, 0x0c, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0xc0, 0x43, 0x03, 0xc0, 0x83, 0x03, 0x30, 0x3c, 0x0c, 0x30, 0x3c, 0x0c, 0x30, 0x00, 0x0c, 0x30, 0x00, 0x0c, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00 }; // 'mario', 56x54px const unsigned char mariomarior [] PROGMEM = { 0x00, 0x00, 0x03, 0xfc, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x03, 0xfc, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x03, 0x03, 0x3f, 0xf3, 0xfc, 0x00, 0x00, 0x03, 0x03, 0x3f, 0xf3, 0xfc, 0x00, 0x00, 0x03, 0x00, 0xff, 0xf3, 0x03, 0x00, 0x00, 0x03, 0x00, 0xff, 0xf3, 0x03, 0x00, 0x00, 0x03, 0x00, 0xff, 0xfc, 0x03, 0x00, 0x00, 0x03, 0x00, 0xff, 0xfc, 0x03, 0x00, 0x00, 0x03, 0x00, 0xff, 0xff, 0xcc, 0x00, 0x00, 0x03, 0x03, 0xff, 0xff, 0xcc, 0x00, 0x00, 0x03, 0x03, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x03, 0xff, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x03, 0xff, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x0f, 0xfc, 0x0c, 0xc3, 0x00, 0x00, 0x00, 0x0f, 0xfc, 0x0c, 0xc3, 0x00, 0x00, 0x00, 0x3c, 0xfc, 0x0c, 0xc3, 0x00, 0x00, 0x00, 0x3c, 0xfc, 0x0c, 0xc3, 0x00, 0x00, 0x00, 0x30, 0xff, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x30, 0xff, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x30, 0x00, 0x30, 0x00, 0xc0, 0x00, 0x00, 0x30, 0x00, 0x30, 0x00, 0xc0, 0x00, 0x00, 0x3c, 0x00, 0xff, 0x03, 0xf0, 0x00, 0x00, 0x3c, 0x00, 0xff, 0x03, 0xf0, 0x00, 0x00, 0x03, 0xc0, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0f, 0x03, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x0f, 0x03, 0xff, 0xfc, 0x00, 0x00, 0x0f, 0xfc, 0x00, 0xf0, 0xfc, 0x00, 0x00, 0x0f, 0xfc, 0x00, 0xf0, 0xfc, 0x00, 0x00, 0x3c, 0x03, 0x00, 0x3c, 0x0f, 0x00, 0x00, 0x3c, 0x03, 0x00, 0x3c, 0x0f, 0x00, 0x00, 0x3c, 0x00, 0xc0, 0x3c, 0x03, 0xc0, 0x00, 0x3c, 0x00, 0xc0, 0x3c, 0x03, 0xc0, 0x00, 0x3f, 0xf0, 0xc3, 0xff, 0xff, 0xc0, 0x3f, 0xff, 0xf0, 0xc3, 0xff, 0xff, 0xc0, 0x3f, 0xff, 0xff, 0xff, 0xf0, 0xfc, 0xf0, 0xfc, 0x3f, 0xff, 0xff, 0xf0, 0xfc, 0xf0, 0xfc, 0x3f, 0xc3, 0xff, 0xf0, 0xff, 0x0c, 0xfc, 0x3f, 0xc3, 0xff, 0xf0, 0xff, 0x0c, 0xfc, 0x3f, 0xcc, 0x0f, 0xff, 0xfc, 0x0c, 0xfc, 0x3f, 0xcc, 0x0f, 0xff, 0xfc, 0x0c, 0xfc, 0x3f, 0xfc, 0xff, 0xff, 0xfc, 0x0c, 0xfc, 0x3f, 0xfc, 0xff, 0xff, 0xfc, 0x0c, 0x3f, 0xff, 0xf0, 0xff, 0xff, 0xfc, 0x0c, 0x3f, 0xff, 0xf0, 0xff, 0xff, 0xfc, 0x0c, 0x00, 0x00, 0x30, 0xff, 0xc0, 0x06, 0x3c, 0x00, 0x00, 0x30, 0xff, 0xc0, 0x06, 0x3c, 0x00, 0x00, 0x30, 0xc0, 0x00, 0x01, 0xf8, 0x00, 0x00, 0x30, 0xc0, 0x00, 0x01, 0xf8, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00 }; // 'mariol', 56x54px const unsigned char mariomariol [] PROGMEM = { 0x00, 0xfc, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x3f, 0xcf, 0xfc, 0xc0, 0xc0, 0x00, 0x00, 0x3f, 0xcf, 0xfc, 0xc0, 0xc0, 0x00, 0x00, 0xc0, 0xcf, 0xff, 0x00, 0xc0, 0x00, 0x00, 0xc0, 0xcf, 0xff, 0x00, 0xc0, 0x00, 0x00, 0xc0, 0x3f, 0xff, 0x00, 0xc0, 0x00, 0x00, 0xc0, 0x3f, 0xff, 0x00, 0xc0, 0x00, 0x00, 0x33, 0xff, 0xff, 0x00, 0xc0, 0x00, 0x00, 0x33, 0xff, 0xff, 0xc0, 0xc0, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xc0, 0xc0, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xc0, 0x00, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xc0, 0x00, 0xff, 0xc0, 0x00, 0x00, 0x00, 0xc3, 0x30, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0xc3, 0x30, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0xc3, 0x30, 0x3f, 0x3c, 0x00, 0x00, 0x00, 0xc3, 0x30, 0x3f, 0x3c, 0x00, 0x00, 0x03, 0x00, 0x00, 0xff, 0x0c, 0x00, 0x00, 0x03, 0x00, 0x00, 0xff, 0x0c, 0x00, 0x00, 0x03, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x00, 0x03, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x00, 0x0f, 0xc0, 0xff, 0x00, 0x3c, 0x00, 0x00, 0x0f, 0xc0, 0xff, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xff, 0xf0, 0x03, 0xc0, 0x00, 0x00, 0x00, 0xff, 0xf0, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x30, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xc0, 0xf0, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xc0, 0xf0, 0x00, 0x00, 0x00, 0x3f, 0x0f, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x3f, 0x0f, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0xf0, 0x3c, 0x00, 0xc0, 0x3c, 0x00, 0x00, 0xf0, 0x3c, 0x00, 0xc0, 0x3c, 0x00, 0x03, 0xc0, 0x3c, 0x03, 0x00, 0x3c, 0x00, 0x03, 0xc0, 0x3c, 0x03, 0x00, 0x3c, 0x00, 0x03, 0xff, 0xff, 0xc3, 0x0f, 0xfc, 0x00, 0x03, 0xff, 0xff, 0xc3, 0x0f, 0xff, 0xfc, 0x0f, 0x3f, 0x0f, 0xff, 0xff, 0xff, 0xfc, 0x0f, 0x3f, 0x0f, 0xff, 0xff, 0xfc, 0x3f, 0x30, 0xff, 0x0f, 0xff, 0xc3, 0xfc, 0x3f, 0x30, 0xff, 0x0f, 0xff, 0xc3, 0xfc, 0x3f, 0x30, 0x3f, 0xff, 0xf0, 0x33, 0xfc, 0x3f, 0x30, 0x3f, 0xff, 0xf0, 0x33, 0xfc, 0x3f, 0x30, 0x3f, 0xff, 0xff, 0x3f, 0xfc, 0x3f, 0x30, 0x3f, 0xff, 0xff, 0x3f, 0xfc, 0x3f, 0x30, 0x3f, 0xff, 0xff, 0x0f, 0xff, 0xfc, 0x30, 0x3f, 0xff, 0xff, 0x0f, 0xff, 0xfc, 0x3c, 0x60, 0x03, 0xff, 0x0c, 0x00, 0x00, 0x3c, 0x60, 0x03, 0xff, 0x0c, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x03, 0x0c, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x03, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00 }; // 'pipe', 42x47px const unsigned char mariopipe [] PROGMEM = { 0x3f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x50, 0x01, 0x11, 0x15, 0x55, 0x80, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x04, 0x44, 0x45, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x01, 0x11, 0x15, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x04, 0x44, 0x45, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x01, 0x11, 0x15, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x04, 0x44, 0x45, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x01, 0x11, 0x15, 0x55, 0xc0, 0xa8, 0x02, 0xaa, 0xaa, 0xab, 0xc0, 0xd0, 0x04, 0x44, 0x45, 0x55, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x7f, 0xff, 0xff, 0xff, 0xff, 0x80, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x08, 0x88, 0x8a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00, 0x34, 0x02, 0x22, 0x2a, 0xaf, 0x00, 0x2a, 0x05, 0x55, 0x55, 0x57, 0x00 };
57c0775a7c7edb02fc2f19dac4efdca57cb1e6e9
be59d364aca6796e57118a208ee0fdc3c94ec8a6
/packages/node-libofx/OpenSP-1.5.2/intl/localcharset.c
1252f3fd8b8d1b7a8f83291b5c1ef660f1e6da54
[ "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "MIT" ]
permissive
actualbudget/actual
94e983d23df6eeb564fa8b5ff3b9cc63f06dec97
63c3d07cb9d6e71ab61f7925ffcaafff870382c6
refs/heads/master
2023-09-04T07:06:53.208119
2023-09-03T23:15:44
2023-09-03T23:15:44
486,815,039
7,738
724
MIT
2023-09-14T02:11:25
2022-04-29T02:41:34
TypeScript
UTF-8
C
false
false
10,869
c
localcharset.c
/* Determine a canonical name for the current locale's character encoding. Copyright (C) 2000-2004 Free Software Foundation, Inc. This program 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, 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 Library General Public License for more details. You should have received a copy of the GNU Library 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. */ /* Written by Bruno Haible <bruno@clisp.org>. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif /* Specification. */ #include "localcharset.h" #if HAVE_STDDEF_H # include <stddef.h> #endif #include <stdio.h> #if HAVE_STRING_H # include <string.h> #else # include <strings.h> #endif #if HAVE_STDLIB_H # include <stdlib.h> #endif #if defined _WIN32 || defined __WIN32__ # undef WIN32 /* avoid warning on mingw32 */ # define WIN32 #endif #if defined __EMX__ /* Assume EMX program runs on OS/2, even if compiled under DOS. */ # define OS2 #endif #if !defined WIN32 # if HAVE_LANGINFO_CODESET # include <langinfo.h> # else # if HAVE_SETLOCALE # include <locale.h> # endif # endif #elif defined WIN32 # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #if defined OS2 # define INCL_DOS # include <os2.h> #endif #if ENABLE_RELOCATABLE # include "relocatable.h" #else # define relocate(pathname) (pathname) #endif #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__ /* Win32, Cygwin, OS/2, DOS */ # define ISSLASH(C) ((C) == '/' || (C) == '\\') #endif #ifndef DIRECTORY_SEPARATOR # define DIRECTORY_SEPARATOR '/' #endif #ifndef ISSLASH # define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR) #endif #if HAVE_DECL_GETC_UNLOCKED # undef getc # define getc getc_unlocked #endif /* The following static variable is declared 'volatile' to avoid a possible multithread problem in the function get_charset_aliases. If we are running in a threaded environment, and if two threads initialize 'charset_aliases' simultaneously, both will produce the same value, and everything will be ok if the two assignments to 'charset_aliases' are atomic. But I don't know what will happen if the two assignments mix. */ #if __STDC__ != 1 # define volatile /* empty */ #endif /* Pointer to the contents of the charset.alias file, if it has already been read, else NULL. Its format is: ALIAS_1 '\0' CANONICAL_1 '\0' ... ALIAS_n '\0' CANONICAL_n '\0' '\0' */ static const char * volatile charset_aliases; /* Return a pointer to the contents of the charset.alias file. */ static const char * get_charset_aliases () { const char *cp; cp = charset_aliases; if (cp == NULL) { #if !(defined VMS || defined WIN32) FILE *fp; const char *dir; const char *base = "charset.alias"; char *file_name; /* Make it possible to override the charset.alias location. This is necessary for running the testsuite before "make install". */ dir = getenv ("CHARSETALIASDIR"); if (dir == NULL || dir[0] == '\0') dir = relocate (LIBDIR); /* Concatenate dir and base into freshly allocated file_name. */ { size_t dir_len = strlen (dir); size_t base_len = strlen (base); int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1])); file_name = (char *) malloc (dir_len + add_slash + base_len + 1); if (file_name != NULL) { memcpy (file_name, dir, dir_len); if (add_slash) file_name[dir_len] = DIRECTORY_SEPARATOR; memcpy (file_name + dir_len + add_slash, base, base_len + 1); } } if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL) /* Out of memory or file not found, treat it as empty. */ cp = ""; else { /* Parse the file's contents. */ char *res_ptr = NULL; size_t res_size = 0; for (;;) { int c; char buf1[50+1]; char buf2[50+1]; size_t l1, l2; char *old_res_ptr; c = getc (fp); if (c == EOF) break; if (c == '\n' || c == ' ' || c == '\t') continue; if (c == '#') { /* Skip comment, to end of line. */ do c = getc (fp); while (!(c == EOF || c == '\n')); if (c == EOF) break; continue; } ungetc (c, fp); if (fscanf (fp, "%50s %50s", buf1, buf2) < 2) break; l1 = strlen (buf1); l2 = strlen (buf2); old_res_ptr = res_ptr; if (res_size == 0) { res_size = l1 + 1 + l2 + 1; res_ptr = (char *) malloc (res_size + 1); } else { res_size += l1 + 1 + l2 + 1; res_ptr = (char *) realloc (res_ptr, res_size + 1); } if (res_ptr == NULL) { /* Out of memory. */ res_size = 0; if (old_res_ptr != NULL) free (old_res_ptr); break; } strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1); strcpy (res_ptr + res_size - (l2 + 1), buf2); } fclose (fp); if (res_size == 0) cp = ""; else { *(res_ptr + res_size) = '\0'; cp = res_ptr; } } if (file_name != NULL) free (file_name); #else # if defined VMS /* To avoid the troubles of an extra file charset.alias_vms in the sources of many GNU packages, simply inline the aliases here. */ /* The list of encodings is taken from the OpenVMS 7.3-1 documentation "Compaq C Run-Time Library Reference Manual for OpenVMS systems" section 10.7 "Handling Different Character Sets". */ cp = "ISO8859-1" "\0" "ISO-8859-1" "\0" "ISO8859-2" "\0" "ISO-8859-2" "\0" "ISO8859-5" "\0" "ISO-8859-5" "\0" "ISO8859-7" "\0" "ISO-8859-7" "\0" "ISO8859-8" "\0" "ISO-8859-8" "\0" "ISO8859-9" "\0" "ISO-8859-9" "\0" /* Japanese */ "eucJP" "\0" "EUC-JP" "\0" "SJIS" "\0" "SHIFT_JIS" "\0" "DECKANJI" "\0" "DEC-KANJI" "\0" "SDECKANJI" "\0" "EUC-JP" "\0" /* Chinese */ "eucTW" "\0" "EUC-TW" "\0" "DECHANYU" "\0" "DEC-HANYU" "\0" "DECHANZI" "\0" "GB2312" "\0" /* Korean */ "DECKOREAN" "\0" "EUC-KR" "\0"; # endif # if defined WIN32 /* To avoid the troubles of installing a separate file in the same directory as the DLL and of retrieving the DLL's directory at runtime, simply inline the aliases here. */ cp = "CP936" "\0" "GBK" "\0" "CP1361" "\0" "JOHAB" "\0" "CP20127" "\0" "ASCII" "\0" "CP20866" "\0" "KOI8-R" "\0" "CP21866" "\0" "KOI8-RU" "\0" "CP28591" "\0" "ISO-8859-1" "\0" "CP28592" "\0" "ISO-8859-2" "\0" "CP28593" "\0" "ISO-8859-3" "\0" "CP28594" "\0" "ISO-8859-4" "\0" "CP28595" "\0" "ISO-8859-5" "\0" "CP28596" "\0" "ISO-8859-6" "\0" "CP28597" "\0" "ISO-8859-7" "\0" "CP28598" "\0" "ISO-8859-8" "\0" "CP28599" "\0" "ISO-8859-9" "\0" "CP28605" "\0" "ISO-8859-15" "\0"; # endif #endif charset_aliases = cp; } return cp; } /* Determine the current locale's character encoding, and canonicalize it into one of the canonical names listed in config.charset. The result must not be freed; it is statically allocated. If the canonical name cannot be determined, the result is a non-canonical name. */ #ifdef STATIC STATIC #endif const char * locale_charset () { const char *codeset; const char *aliases; #if !(defined WIN32 || defined OS2) # if HAVE_LANGINFO_CODESET /* Most systems support nl_langinfo (CODESET) nowadays. */ codeset = nl_langinfo (CODESET); # else /* On old systems which lack it, use setlocale or getenv. */ const char *locale = NULL; /* But most old systems don't have a complete set of locales. Some (like SunOS 4 or DJGPP) have only the C locale. Therefore we don't use setlocale here; it would return "C" when it doesn't support the locale name the user has set. */ # if HAVE_SETLOCALE && 0 locale = setlocale (LC_CTYPE, NULL); # endif if (locale == NULL || locale[0] == '\0') { locale = getenv ("LC_ALL"); if (locale == NULL || locale[0] == '\0') { locale = getenv ("LC_CTYPE"); if (locale == NULL || locale[0] == '\0') locale = getenv ("LANG"); } } /* On some old systems, one used to set locale = "iso8859_1". On others, you set it to "language_COUNTRY.charset". In any case, we resolve it through the charset.alias file. */ codeset = locale; # endif #elif defined WIN32 static char buf[2 + 10 + 1]; /* Woe32 has a function returning the locale's codepage as a number. */ sprintf (buf, "CP%u", GetACP ()); codeset = buf; #elif defined OS2 const char *locale; static char buf[2 + 10 + 1]; ULONG cp[3]; ULONG cplen; /* Allow user to override the codeset, as set in the operating system, with standard language environment variables. */ locale = getenv ("LC_ALL"); if (locale == NULL || locale[0] == '\0') { locale = getenv ("LC_CTYPE"); if (locale == NULL || locale[0] == '\0') locale = getenv ("LANG"); } if (locale != NULL && locale[0] != '\0') { /* If the locale name contains an encoding after the dot, return it. */ const char *dot = strchr (locale, '.'); if (dot != NULL) { const char *modifier; dot++; /* Look for the possible @... trailer and remove it, if any. */ modifier = strchr (dot, '@'); if (modifier == NULL) return dot; if (modifier - dot < sizeof (buf)) { memcpy (buf, dot, modifier - dot); buf [modifier - dot] = '\0'; return buf; } } /* Resolve through the charset.alias file. */ codeset = locale; } else { /* OS/2 has a function returning the locale's codepage as a number. */ if (DosQueryCp (sizeof (cp), cp, &cplen)) codeset = ""; else { sprintf (buf, "CP%u", cp[0]); codeset = buf; } } #endif if (codeset == NULL) /* The canonical name cannot be determined. */ codeset = ""; /* Resolve alias. */ for (aliases = get_charset_aliases (); *aliases != '\0'; aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1) if (strcmp (codeset, aliases) == 0 || (aliases[0] == '*' && aliases[1] == '\0')) { codeset = aliases + strlen (aliases) + 1; break; } /* Don't return an empty string. GNU libc and GNU libiconv interpret the empty string as denoting "the locale's character encoding", thus GNU libiconv would call this function a second time. */ if (codeset[0] == '\0') codeset = "ASCII"; return codeset; }
cf26223c64a4b46a2da9dc6552c0aba8e88f7459
4c195550263eb39db62a95820dde869f4bfd9606
/examples/C/bufr_get_keys.c
42b26ca703cfc32ed375d5f11bc283d67e06cd34
[ "Apache-2.0" ]
permissive
ecmwf/eccodes
765584026fdc454b0f915831007c9cece28fe3a9
28ece2bbdb963a937ddd36958049f05f2110fa12
refs/heads/develop
2023-08-08T03:26:38.255559
2023-08-07T16:04:22
2023-08-07T16:04:22
161,228,639
155
87
Apache-2.0
2023-08-30T16:10:06
2018-12-10T19:52:30
C++
UTF-8
C
false
false
3,766
c
bufr_get_keys.c
/* * (C) Copyright 2005- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. */ /* * C Implementation: bufr_get_keys * * Description: how to read values of different type of keys from BUFR messages. * */ #include "eccodes.h" int main(int argc, char* argv[]) { FILE* in = NULL; /* message handle. Required in all the eccodes calls acting on a message.*/ codes_handle* h = NULL; long* descriptors = NULL; double* values = NULL; char* typicalDate = NULL; long longVal; double doubleVal; size_t values_len = 0, desc_len = 0, len = 0; int i, err = 0; int cnt = 0; const char* infile = "../../data/bufr/syno_multi.bufr"; in = fopen(infile, "rb"); if (!in) { fprintf(stderr, "Error: unable to open file %s\n", infile); return 1; } /* loop over the messages in the BUFR file */ while ((h = codes_handle_new_from_file(NULL, in, PRODUCT_BUFR, &err)) != NULL || err != CODES_SUCCESS) { if (h == NULL) { fprintf(stderr, "Error: unable to create handle for message %d\n", cnt); cnt++; continue; } printf("message: %d\n", cnt); /* we need to instruct ecCodes to expand the descriptors i.e. unpack the data values */ CODES_CHECK(codes_set_long(h, "unpack", 1), 0); /* read and print some data values */ /* long value */ CODES_CHECK(codes_get_long(h, "blockNumber", &longVal), 0); printf(" blockNumber: %ld\n", longVal); /* long value */ CODES_CHECK(codes_get_long(h, "stationNumber", &longVal), 0); printf(" stationNumber: %ld\n", longVal); /* double value */ CODES_CHECK(codes_get_double(h, "airTemperatureAt2M", &doubleVal), 0); printf(" airTemperatureAt2M: %f\n", doubleVal); /* ---- string value -----------------*/ /* get the size and allocate memory*/ CODES_CHECK(codes_get_length(h, "typicalDate", &len), 0); typicalDate = (char*)malloc(len * sizeof(char)); /* get the values*/ codes_get_string(h, "typicalDate", typicalDate, &len); printf(" typicalDate: %s\n", typicalDate); /* ---- array of long ----------------*/ /* get the size and allocate memory*/ CODES_CHECK(codes_get_size(h, "bufrdcExpandedDescriptors", &desc_len), 0); descriptors = (long*)malloc(desc_len * sizeof(long)); /* get the values */ CODES_CHECK(codes_get_long_array(h, "bufrdcExpandedDescriptors", descriptors, &desc_len), 0); printf(" bufrdcExpandedDescriptors:\n"); for (i = 0; i < desc_len; i++) { printf(" %ld\n", descriptors[i]); } /* ---- array of double ---------------*/ /* get the size and allocate memory*/ CODES_CHECK(codes_get_size(h, "numericValues", &values_len), 0); values = (double*)malloc(values_len * sizeof(double)); /* get the values*/ CODES_CHECK(codes_get_double_array(h, "numericValues", values, &values_len), 0); printf(" numericValues:\n"); for (i = 0; i < values_len; i++) { printf(" %.10e\n", values[i]); } /* free allocated arrays */ free(descriptors); free(values); free(typicalDate); /* delete handle */ codes_handle_delete(h); cnt++; } fclose(in); return 0; }
49e1ce5ad6a976a4c727f3bbbe5c5ba214c6c165
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/avr32/mach-at32ap/hsmc.h
d1d48e26e39378702eee37b4d7e148ddf76306ea
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,756
h
hsmc.h
/* * Register definitions for Atmel Static Memory Controller (SMC) * * Copyright (C) 2006 Atmel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __ASM_AVR32_HSMC_H__ #define __ASM_AVR32_HSMC_H__ /* HSMC register offsets */ #define HSMC_SETUP0 0x0000 #define HSMC_PULSE0 0x0004 #define HSMC_CYCLE0 0x0008 #define HSMC_MODE0 0x000c #define HSMC_SETUP1 0x0010 #define HSMC_PULSE1 0x0014 #define HSMC_CYCLE1 0x0018 #define HSMC_MODE1 0x001c #define HSMC_SETUP2 0x0020 #define HSMC_PULSE2 0x0024 #define HSMC_CYCLE2 0x0028 #define HSMC_MODE2 0x002c #define HSMC_SETUP3 0x0030 #define HSMC_PULSE3 0x0034 #define HSMC_CYCLE3 0x0038 #define HSMC_MODE3 0x003c #define HSMC_SETUP4 0x0040 #define HSMC_PULSE4 0x0044 #define HSMC_CYCLE4 0x0048 #define HSMC_MODE4 0x004c #define HSMC_SETUP5 0x0050 #define HSMC_PULSE5 0x0054 #define HSMC_CYCLE5 0x0058 #define HSMC_MODE5 0x005c /* Bitfields in SETUP0 */ #define HSMC_NWE_SETUP_OFFSET 0 #define HSMC_NWE_SETUP_SIZE 6 #define HSMC_NCS_WR_SETUP_OFFSET 8 #define HSMC_NCS_WR_SETUP_SIZE 6 #define HSMC_NRD_SETUP_OFFSET 16 #define HSMC_NRD_SETUP_SIZE 6 #define HSMC_NCS_RD_SETUP_OFFSET 24 #define HSMC_NCS_RD_SETUP_SIZE 6 /* Bitfields in PULSE0 */ #define HSMC_NWE_PULSE_OFFSET 0 #define HSMC_NWE_PULSE_SIZE 7 #define HSMC_NCS_WR_PULSE_OFFSET 8 #define HSMC_NCS_WR_PULSE_SIZE 7 #define HSMC_NRD_PULSE_OFFSET 16 #define HSMC_NRD_PULSE_SIZE 7 #define HSMC_NCS_RD_PULSE_OFFSET 24 #define HSMC_NCS_RD_PULSE_SIZE 7 /* Bitfields in CYCLE0 */ #define HSMC_NWE_CYCLE_OFFSET 0 #define HSMC_NWE_CYCLE_SIZE 9 #define HSMC_NRD_CYCLE_OFFSET 16 #define HSMC_NRD_CYCLE_SIZE 9 /* Bitfields in MODE0 */ #define HSMC_READ_MODE_OFFSET 0 #define HSMC_READ_MODE_SIZE 1 #define HSMC_WRITE_MODE_OFFSET 1 #define HSMC_WRITE_MODE_SIZE 1 #define HSMC_EXNW_MODE_OFFSET 4 #define HSMC_EXNW_MODE_SIZE 2 #define HSMC_BAT_OFFSET 8 #define HSMC_BAT_SIZE 1 #define HSMC_DBW_OFFSET 12 #define HSMC_DBW_SIZE 2 #define HSMC_TDF_CYCLES_OFFSET 16 #define HSMC_TDF_CYCLES_SIZE 4 #define HSMC_TDF_MODE_OFFSET 20 #define HSMC_TDF_MODE_SIZE 1 #define HSMC_PMEN_OFFSET 24 #define HSMC_PMEN_SIZE 1 #define HSMC_PS_OFFSET 28 #define HSMC_PS_SIZE 2 /* Constants for READ_MODE */ #define HSMC_READ_MODE_NCS_CONTROLLED 0 #define HSMC_READ_MODE_NRD_CONTROLLED 1 /* Constants for WRITE_MODE */ #define HSMC_WRITE_MODE_NCS_CONTROLLED 0 #define HSMC_WRITE_MODE_NWE_CONTROLLED 1 /* Constants for EXNW_MODE */ #define HSMC_EXNW_MODE_DISABLED 0 #define HSMC_EXNW_MODE_RESERVED 1 #define HSMC_EXNW_MODE_FROZEN 2 #define HSMC_EXNW_MODE_READY 3 /* Constants for BAT */ #define HSMC_BAT_BYTE_SELECT 0 #define HSMC_BAT_BYTE_WRITE 1 /* Constants for DBW */ #define HSMC_DBW_8_BITS 0 #define HSMC_DBW_16_BITS 1 #define HSMC_DBW_32_BITS 2 /* Bit manipulation macros */ #define HSMC_BIT(name) \ (1 << HSMC_##name##_OFFSET) #define HSMC_BF(name,value) \ (((value) & ((1 << HSMC_##name##_SIZE) - 1)) \ << HSMC_##name##_OFFSET) #define HSMC_BFEXT(name,value) \ (((value) >> HSMC_##name##_OFFSET) \ & ((1 << HSMC_##name##_SIZE) - 1)) #define HSMC_BFINS(name,value,old) \ (((old) & ~(((1 << HSMC_##name##_SIZE) - 1) \ << HSMC_##name##_OFFSET)) | HSMC_BF(name,value)) /* Register access macros */ #define hsmc_readl(port,reg) \ __raw_readl((port)->regs + HSMC_##reg) #define hsmc_writel(port,reg,value) \ __raw_writel((value), (port)->regs + HSMC_##reg) #endif /* __ASM_AVR32_HSMC_H__ */
1092f7aadaa27611b09f016eceb66208208d0b33
f1ee65fbe1ffc43c2aac45e41515f1987eb534a4
/src/third_party/nasm/asm/strfunc.c
236b9d2ff4cdca16f16f9831e82e2d7ce345d205
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
klzgrad/naiveproxy
6e0d206b6f065b9311d1e12b363109f2d35cc058
8ef1cecadfd4e2b5d57e7ea2fa42d05717e51c2e
refs/heads/master
2023-08-20T22:42:12.511091
2023-06-04T03:54:34
2023-08-16T23:30:19
119,178,893
5,710
976
BSD-3-Clause
2023-08-05T10:59:59
2018-01-27T16:02:33
C++
UTF-8
C
false
false
10,193
c
strfunc.c
/* ----------------------------------------------------------------------- * * * Copyright 1996-2009 The NASM Authors - All Rights Reserved * See the file AUTHORS included with the NASM distribution for * the specific copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ----------------------------------------------------------------------- */ /* * strfunc.c * * String transformation functions */ #include "nasmlib.h" #include "nasm.h" /* * Convert a string in UTF-8 format to UTF-16LE */ static size_t utf8_to_16le(uint8_t *str, size_t len, char *op) { #define EMIT(x) do { if (op) { WRITESHORT(op,x); } outlen++; } while(0) size_t outlen = 0; int expect = 0; uint8_t c; uint32_t v = 0, vmin = 0; while (len--) { c = *str++; if (expect) { if ((c & 0xc0) != 0x80) { expect = 0; return -1; } else { v = (v << 6) | (c & 0x3f); if (!--expect) { if (v < vmin || v > 0x10ffff || (v >= 0xd800 && v <= 0xdfff)) { return -1; } else if (v > 0xffff) { v -= 0x10000; EMIT(0xd800 | (v >> 10)); EMIT(0xdc00 | (v & 0x3ff)); } else { EMIT(v); } } continue; } } if (c < 0x80) { EMIT(c); } else if (c < 0xc0 || c >= 0xfe) { /* Invalid UTF-8 */ return -1; } else if (c < 0xe0) { v = c & 0x1f; expect = 1; vmin = 0x80; } else if (c < 0xf0) { v = c & 0x0f; expect = 2; vmin = 0x800; } else if (c < 0xf8) { v = c & 0x07; expect = 3; vmin = 0x10000; } else if (c < 0xfc) { v = c & 0x03; expect = 4; vmin = 0x200000; } else { v = c & 0x01; expect = 5; vmin = 0x4000000; } } return expect ? (size_t)-1 : outlen << 1; #undef EMIT } /* * Convert a string in UTF-8 format to UTF-16BE */ static size_t utf8_to_16be(uint8_t *str, size_t len, char *op) { #define EMIT(x) \ do { \ uint16_t _y = (x); \ if (op) { \ WRITECHAR(op, _y >> 8); \ WRITECHAR(op, _y); \ } \ outlen++; \ } while (0) \ size_t outlen = 0; int expect = 0; uint8_t c; uint32_t v = 0, vmin = 0; while (len--) { c = *str++; if (expect) { if ((c & 0xc0) != 0x80) { expect = 0; return -1; } else { v = (v << 6) | (c & 0x3f); if (!--expect) { if (v < vmin || v > 0x10ffff || (v >= 0xd800 && v <= 0xdfff)) { return -1; } else if (v > 0xffff) { v -= 0x10000; EMIT(0xdc00 | (v & 0x3ff)); EMIT(0xd800 | (v >> 10)); } else { EMIT(v); } } continue; } } if (c < 0x80) { EMIT(c); } else if (c < 0xc0 || c >= 0xfe) { /* Invalid UTF-8 */ return -1; } else if (c < 0xe0) { v = c & 0x1f; expect = 1; vmin = 0x80; } else if (c < 0xf0) { v = c & 0x0f; expect = 2; vmin = 0x800; } else if (c < 0xf8) { v = c & 0x07; expect = 3; vmin = 0x10000; } else if (c < 0xfc) { v = c & 0x03; expect = 4; vmin = 0x200000; } else { v = c & 0x01; expect = 5; vmin = 0x4000000; } } return expect ? (size_t)-1 : outlen << 1; #undef EMIT } /* * Convert a string in UTF-8 format to UTF-32LE */ static size_t utf8_to_32le(uint8_t *str, size_t len, char *op) { #define EMIT(x) do { if (op) { WRITELONG(op,x); } outlen++; } while(0) size_t outlen = 0; int expect = 0; uint8_t c; uint32_t v = 0, vmin = 0; while (len--) { c = *str++; if (expect) { if ((c & 0xc0) != 0x80) { return -1; } else { v = (v << 6) | (c & 0x3f); if (!--expect) { if (v < vmin || (v >= 0xd800 && v <= 0xdfff)) { return -1; } else { EMIT(v); } } continue; } } if (c < 0x80) { EMIT(c); } else if (c < 0xc0 || c >= 0xfe) { /* Invalid UTF-8 */ return -1; } else if (c < 0xe0) { v = c & 0x1f; expect = 1; vmin = 0x80; } else if (c < 0xf0) { v = c & 0x0f; expect = 2; vmin = 0x800; } else if (c < 0xf8) { v = c & 0x07; expect = 3; vmin = 0x10000; } else if (c < 0xfc) { v = c & 0x03; expect = 4; vmin = 0x200000; } else { v = c & 0x01; expect = 5; vmin = 0x4000000; } } return expect ? (size_t)-1 : outlen << 2; #undef EMIT } /* * Convert a string in UTF-8 format to UTF-32BE */ static size_t utf8_to_32be(uint8_t *str, size_t len, char *op) { #define EMIT(x) \ do { \ uint32_t _y = (x); \ if (op) { \ WRITECHAR(op,_y >> 24); \ WRITECHAR(op,_y >> 16); \ WRITECHAR(op,_y >> 8); \ WRITECHAR(op,_y); \ } \ outlen++; \ } while (0) size_t outlen = 0; int expect = 0; uint8_t c; uint32_t v = 0, vmin = 0; while (len--) { c = *str++; if (expect) { if ((c & 0xc0) != 0x80) { return -1; } else { v = (v << 6) | (c & 0x3f); if (!--expect) { if (v < vmin || (v >= 0xd800 && v <= 0xdfff)) { return -1; } else { EMIT(v); } } continue; } } if (c < 0x80) { EMIT(c); } else if (c < 0xc0 || c >= 0xfe) { /* Invalid UTF-8 */ return -1; } else if (c < 0xe0) { v = c & 0x1f; expect = 1; vmin = 0x80; } else if (c < 0xf0) { v = c & 0x0f; expect = 2; vmin = 0x800; } else if (c < 0xf8) { v = c & 0x07; expect = 3; vmin = 0x10000; } else if (c < 0xfc) { v = c & 0x03; expect = 4; vmin = 0x200000; } else { v = c & 0x01; expect = 5; vmin = 0x4000000; } } return expect ? (size_t)-1 : outlen << 2; #undef EMIT } typedef size_t (*transform_func)(uint8_t *, size_t, char *); /* * Apply a specific string transform and return it in a nasm_malloc'd * buffer, returning the length. On error, returns (size_t)-1 and no * buffer is allocated. */ size_t string_transform(char *str, size_t len, char **out, enum strfunc func) { /* This should match enum strfunc in nasm.h */ static const transform_func str_transforms[] = { utf8_to_16le, utf8_to_16le, utf8_to_16be, utf8_to_32le, utf8_to_32le, utf8_to_32be, }; transform_func transform = str_transforms[func]; size_t outlen; uint8_t *s = (uint8_t *)str; char *buf; outlen = transform(s, len, NULL); if (outlen == (size_t)-1) return -1; *out = buf = nasm_malloc(outlen+1); buf[outlen] = '\0'; /* Forcibly null-terminate the buffer */ return transform(s, len, buf); }
20220a4aa50078204205804d899cb9f9372a2395
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/fontconfig/src/src/fcformat.c
ae8c59c16abc312d2c6fd345fc529dee35b88f61
[ "HPND-sell-variant", "MIT", "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unicode", "MIT-Modern-Variant" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
24,287
c
fcformat.c
/* * Copyright © 2008,2009 Red Hat, Inc. * * Red Hat Author(s): Behdad Esfahbod * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of the author(s) not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. The authors make no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include "fcint.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> /* The language is documented in doc/fcformat.fncs * These are the features implemented: * * simple %{elt} * width %width{elt} * index %{elt[idx]} * name= %{elt=} * :name= %{:elt} * default %{elt:-word} * count %{#elt} * subexpr %{{expr}} * filter-out %{-elt1,elt2,elt3{expr}} * filter-in %{+elt1,elt2,elt3{expr}} * conditional %{?elt1,elt2,!elt3{}{}} * enumerate %{[]elt1,elt2{expr}} * langset langset enumeration using the same syntax * builtin %{=blt} * convert %{elt|conv1|conv2|conv3} * * converters: * basename FcStrBasename * dirname FcStrDirname * downcase FcStrDowncase * shescape * cescape * xmlescape * delete delete chars * escape escape chars * translate translate chars * * builtins: * unparse FcNameUnparse * fcmatch fc-match default * fclist fc-list default * fccat fc-cat default * pkgkit PackageKit package tag format * * * Some ideas for future syntax extensions: * * - verbose builtin that is like FcPatternPrint * - allow indexing subexprs using '%{[idx]elt1,elt2{subexpr}}' * - allow indexing in +, -, ? filtering? * - conditional/filtering/deletion on binding (using '(w)'/'(s)'/'(=)' notation) */ #define FCCAT_FORMAT "\"%{file|basename|cescape}\" %{index} \"%{-file{%{=unparse|cescape}}}\"" #define FCMATCH_FORMAT "%{file:-<unknown filename>|basename}: \"%{family[0]:-<unknown family>}\" \"%{style[0]:-<unknown style>}\"" #define FCLIST_FORMAT "%{?file{%{file}: }}%{-file{%{=unparse}}}" #define PKGKIT_FORMAT "%{[]family{font(%{family|downcase|delete( )})\n}}%{[]lang{font(:lang=%{lang|downcase|translate(_,-)})\n}}" static void message (const char *fmt, ...) { va_list args; va_start (args, fmt); fprintf (stderr, "Fontconfig: Pattern format error: "); vfprintf (stderr, fmt, args); fprintf (stderr, ".\n"); va_end (args); } typedef struct _FcFormatContext { const FcChar8 *format_orig; const FcChar8 *format; int format_len; FcChar8 *word; FcBool word_allocated; } FcFormatContext; static FcBool FcFormatContextInit (FcFormatContext *c, const FcChar8 *format, FcChar8 *scratch, int scratch_len) { c->format_orig = c->format = format; c->format_len = strlen ((const char *) format); if (c->format_len < scratch_len) { c->word = scratch; c->word_allocated = FcFalse; } else { c->word = malloc (c->format_len + 1); c->word_allocated = FcTrue; } return c->word != NULL; } static void FcFormatContextDone (FcFormatContext *c) { if (c && c->word_allocated) { free (c->word); } } static FcBool consume_char (FcFormatContext *c, FcChar8 term) { if (*c->format != term) return FcFalse; c->format++; return FcTrue; } static FcBool expect_char (FcFormatContext *c, FcChar8 term) { FcBool res = consume_char (c, term); if (!res) { if (c->format == c->format_orig + c->format_len) message ("format ended while expecting '%c'", term); else message ("expected '%c' at %d", term, c->format - c->format_orig + 1); } return res; } static FcBool FcCharIsPunct (const FcChar8 c) { if (c < '0') return FcTrue; if (c <= '9') return FcFalse; if (c < 'A') return FcTrue; if (c <= 'Z') return FcFalse; if (c < 'a') return FcTrue; if (c <= 'z') return FcFalse; if (c <= '~') return FcTrue; return FcFalse; } static char escaped_char(const char ch) { switch (ch) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; default: return ch; } } static FcBool read_word (FcFormatContext *c) { FcChar8 *p; p = c->word; while (*c->format) { if (*c->format == '\\') { c->format++; if (*c->format) *p++ = escaped_char (*c->format++); continue; } else if (FcCharIsPunct (*c->format)) break; *p++ = *c->format++; } *p = '\0'; if (p == c->word) { message ("expected identifier at %d", c->format - c->format_orig + 1); return FcFalse; } return FcTrue; } static FcBool read_chars (FcFormatContext *c, FcChar8 term) { FcChar8 *p; p = c->word; while (*c->format && *c->format != '}' && *c->format != term) { if (*c->format == '\\') { c->format++; if (*c->format) *p++ = escaped_char (*c->format++); continue; } *p++ = *c->format++; } *p = '\0'; if (p == c->word) { message ("expected character data at %d", c->format - c->format_orig + 1); return FcFalse; } return FcTrue; } static FcBool FcPatternFormatToBuf (FcPattern *pat, const FcChar8 *format, FcStrBuf *buf); static FcBool interpret_builtin (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcChar8 *new_str; FcBool ret; if (!expect_char (c, '=') || !read_word (c)) return FcFalse; /* try simple builtins first */ if (0) { } #define BUILTIN(name, func) \ else if (0 == strcmp ((const char *) c->word, name))\ do { new_str = func (pat); ret = FcTrue; } while (0) BUILTIN ("unparse", FcNameUnparse); /* BUILTIN ("verbose", FcPatternPrint); XXX */ #undef BUILTIN else ret = FcFalse; if (ret) { if (new_str) { FcStrBufString (buf, new_str); FcStrFree (new_str); return FcTrue; } else return FcFalse; } /* now try our custom formats */ if (0) { } #define BUILTIN(name, format) \ else if (0 == strcmp ((const char *) c->word, name))\ ret = FcPatternFormatToBuf (pat, (const FcChar8 *) format, buf) BUILTIN ("fccat", FCCAT_FORMAT); BUILTIN ("fcmatch", FCMATCH_FORMAT); BUILTIN ("fclist", FCLIST_FORMAT); BUILTIN ("pkgkit", PKGKIT_FORMAT); #undef BUILTIN else ret = FcFalse; if (!ret) message ("unknown builtin \"%s\"", c->word); return ret; } static FcBool interpret_expr (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf, FcChar8 term); static FcBool interpret_subexpr (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { return expect_char (c, '{') && interpret_expr (c, pat, buf, '}') && expect_char (c, '}'); } static FcBool maybe_interpret_subexpr (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { return (*c->format == '{') ? interpret_subexpr (c, pat, buf) : FcTrue; } static FcBool skip_subexpr (FcFormatContext *c); static FcBool skip_percent (FcFormatContext *c) { if (!expect_char (c, '%')) return FcFalse; /* skip an optional width specifier */ if (strtol ((const char *) c->format, (char **) &c->format, 10)) {/* don't care */} if (!expect_char (c, '{')) return FcFalse; while(*c->format && *c->format != '}') { switch (*c->format) { case '\\': c->format++; /* skip over '\\' */ if (*c->format) c->format++; continue; case '{': if (!skip_subexpr (c)) return FcFalse; continue; } c->format++; } return expect_char (c, '}'); } static FcBool skip_expr (FcFormatContext *c) { while(*c->format && *c->format != '}') { switch (*c->format) { case '\\': c->format++; /* skip over '\\' */ if (*c->format) c->format++; continue; case '%': if (!skip_percent (c)) return FcFalse; continue; } c->format++; } return FcTrue; } static FcBool skip_subexpr (FcFormatContext *c) { return expect_char (c, '{') && skip_expr (c) && expect_char (c, '}'); } static FcBool maybe_skip_subexpr (FcFormatContext *c) { return (*c->format == '{') ? skip_subexpr (c) : FcTrue; } static FcBool interpret_filter_in (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcObjectSet *os; FcPattern *subpat; if (!expect_char (c, '+')) return FcFalse; os = FcObjectSetCreate (); if (!os) return FcFalse; do { /* XXX binding */ if (!read_word (c) || !FcObjectSetAdd (os, (const char *) c->word)) { FcObjectSetDestroy (os); return FcFalse; } } while (consume_char (c, ',')); subpat = FcPatternFilter (pat, os); FcObjectSetDestroy (os); if (!subpat || !interpret_subexpr (c, subpat, buf)) return FcFalse; FcPatternDestroy (subpat); return FcTrue; } static FcBool interpret_filter_out (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcPattern *subpat; if (!expect_char (c, '-')) return FcFalse; subpat = FcPatternDuplicate (pat); if (!subpat) return FcFalse; do { if (!read_word (c)) { FcPatternDestroy (subpat); return FcFalse; } FcPatternDel (subpat, (const char *) c->word); } while (consume_char (c, ',')); if (!interpret_subexpr (c, subpat, buf)) return FcFalse; FcPatternDestroy (subpat); return FcTrue; } static FcBool interpret_cond (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcBool pass; if (!expect_char (c, '?')) return FcFalse; pass = FcTrue; do { FcBool negate; FcValue v; negate = consume_char (c, '!'); if (!read_word (c)) return FcFalse; pass = pass && (negate ^ (FcResultMatch == FcPatternGet (pat, (const char *) c->word, 0, &v))); } while (consume_char (c, ',')); if (pass) { if (!interpret_subexpr (c, pat, buf) || !maybe_skip_subexpr (c)) return FcFalse; } else { if (!skip_subexpr (c) || !maybe_interpret_subexpr (c, pat, buf)) return FcFalse; } return FcTrue; } static FcBool interpret_count (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { int count; FcPatternIter iter; FcChar8 buf_static[64]; if (!expect_char (c, '#')) return FcFalse; if (!read_word (c)) return FcFalse; count = 0; if (FcPatternFindIter (pat, &iter, (const char *) c->word)) { count = FcPatternIterValueCount (pat, &iter); } snprintf ((char *) buf_static, sizeof (buf_static), "%d", count); FcStrBufString (buf, buf_static); return FcTrue; } static FcBool interpret_enumerate (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcObjectSet *os; FcPattern *subpat; const FcChar8 *format_save; int idx; FcBool ret, done; FcStrList *lang_strs; if (!expect_char (c, '[') || !expect_char (c, ']')) return FcFalse; os = FcObjectSetCreate (); if (!os) return FcFalse; ret = FcTrue; do { if (!read_word (c) || !FcObjectSetAdd (os, (const char *) c->word)) { FcObjectSetDestroy (os); return FcFalse; } } while (consume_char (c, ',')); /* If we have one element and it's of type FcLangSet, we want * to enumerate the languages in it. */ lang_strs = NULL; if (os->nobject == 1) { FcLangSet *langset; if (FcResultMatch == FcPatternGetLangSet (pat, os->objects[0], 0, &langset)) { FcStrSet *ss; if (!(ss = FcLangSetGetLangs (langset)) || !(lang_strs = FcStrListCreate (ss))) goto bail0; } } subpat = FcPatternDuplicate (pat); if (!subpat) goto bail0; format_save = c->format; idx = 0; do { int i; done = FcTrue; if (lang_strs) { FcChar8 *lang; FcPatternDel (subpat, os->objects[0]); if ((lang = FcStrListNext (lang_strs))) { /* XXX binding? */ FcPatternAddString (subpat, os->objects[0], lang); done = FcFalse; } } else { for (i = 0; i < os->nobject; i++) { FcValue v; /* XXX this can be optimized by accessing valuelist linked lists * directly and remembering where we were. Most (all) value lists * in normal uses are pretty short though (language tags are * stored as a LangSet, not separate values.). */ FcPatternDel (subpat, os->objects[i]); if (FcResultMatch == FcPatternGet (pat, os->objects[i], idx, &v)) { /* XXX binding */ FcPatternAdd (subpat, os->objects[i], v, FcFalse); done = FcFalse; } } } if (!done) { c->format = format_save; ret = interpret_subexpr (c, subpat, buf); if (!ret) goto bail; } idx++; } while (!done); if (c->format == format_save) skip_subexpr (c); bail: FcPatternDestroy (subpat); bail0: if (lang_strs) FcStrListDone (lang_strs); FcObjectSetDestroy (os); return ret; } static FcBool interpret_simple (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { FcPatternIter iter; FcBool add_colon = FcFalse; FcBool add_elt_name = FcFalse; int idx; FcChar8 *else_string; if (consume_char (c, ':')) add_colon = FcTrue; if (!read_word (c)) return FcFalse; idx = -1; if (consume_char (c, '[')) { idx = strtol ((const char *) c->format, (char **) &c->format, 10); if (idx < 0) { message ("expected non-negative number at %d", c->format-1 - c->format_orig + 1); return FcFalse; } if (!expect_char (c, ']')) return FcFalse; } if (consume_char (c, '=')) add_elt_name = FcTrue; /* modifiers */ else_string = NULL; if (consume_char (c, ':')) { FcChar8 *orig; /* divert the c->word for now */ orig = c->word; c->word = c->word + strlen ((const char *) c->word) + 1; /* for now we just support 'default value' */ if (!expect_char (c, '-') || !read_chars (c, '|')) { c->word = orig; return FcFalse; } else_string = c->word; c->word = orig; } if (FcPatternFindIter (pat, &iter, (const char *) c->word) || else_string) { FcValueListPtr l = NULL; if (add_colon) FcStrBufChar (buf, ':'); if (add_elt_name) { FcStrBufString (buf, c->word); FcStrBufChar (buf, '='); } l = FcPatternIterGetValues (pat, &iter); if (idx != -1) { while (l && idx > 0) { l = FcValueListNext(l); idx--; } if (l && idx == 0) { if (!FcNameUnparseValue (buf, &l->value, NULL)) return FcFalse; } else goto notfound; } else if (l) { FcNameUnparseValueList (buf, l, NULL); } else { notfound: if (else_string) FcStrBufString (buf, else_string); } } return FcTrue; } static FcBool cescape (FcFormatContext *c FC_UNUSED, const FcChar8 *str, FcStrBuf *buf) { /* XXX escape \n etc? */ while(*str) { switch (*str) { case '\\': case '"': FcStrBufChar (buf, '\\'); break; } FcStrBufChar (buf, *str++); } return FcTrue; } static FcBool shescape (FcFormatContext *c FC_UNUSED, const FcChar8 *str, FcStrBuf *buf) { FcStrBufChar (buf, '\''); while(*str) { if (*str == '\'') FcStrBufString (buf, (const FcChar8 *) "'\\''"); else FcStrBufChar (buf, *str); str++; } FcStrBufChar (buf, '\''); return FcTrue; } static FcBool xmlescape (FcFormatContext *c FC_UNUSED, const FcChar8 *str, FcStrBuf *buf) { /* XXX escape \n etc? */ while(*str) { switch (*str) { case '&': FcStrBufString (buf, (const FcChar8 *) "&amp;"); break; case '<': FcStrBufString (buf, (const FcChar8 *) "&lt;"); break; case '>': FcStrBufString (buf, (const FcChar8 *) "&gt;"); break; default: FcStrBufChar (buf, *str); break; } str++; } return FcTrue; } static FcBool delete_chars (FcFormatContext *c, const FcChar8 *str, FcStrBuf *buf) { /* XXX not UTF-8 aware */ if (!expect_char (c, '(') || !read_chars (c, ')') || !expect_char (c, ')')) return FcFalse; while(*str) { FcChar8 *p; p = (FcChar8 *) strpbrk ((const char *) str, (const char *) c->word); if (p) { FcStrBufData (buf, str, p - str); str = p + 1; } else { FcStrBufString (buf, str); break; } } return FcTrue; } static FcBool escape_chars (FcFormatContext *c, const FcChar8 *str, FcStrBuf *buf) { /* XXX not UTF-8 aware */ if (!expect_char (c, '(') || !read_chars (c, ')') || !expect_char (c, ')')) return FcFalse; while(*str) { FcChar8 *p; p = (FcChar8 *) strpbrk ((const char *) str, (const char *) c->word); if (p) { FcStrBufData (buf, str, p - str); FcStrBufChar (buf, c->word[0]); FcStrBufChar (buf, *p); str = p + 1; } else { FcStrBufString (buf, str); break; } } return FcTrue; } static FcBool translate_chars (FcFormatContext *c, const FcChar8 *str, FcStrBuf *buf) { char *from, *to, repeat; int from_len, to_len; /* XXX not UTF-8 aware */ if (!expect_char (c, '(') || !read_chars (c, ',') || !expect_char (c, ',')) return FcFalse; from = (char *) c->word; from_len = strlen (from); to = from + from_len + 1; /* hack: we temporarily divert c->word */ c->word = (FcChar8 *) to; if (!read_chars (c, ')')) { c->word = (FcChar8 *) from; return FcFalse; } c->word = (FcChar8 *) from; to_len = strlen (to); repeat = to[to_len - 1]; if (!expect_char (c, ')')) return FcFalse; while(*str) { FcChar8 *p; p = (FcChar8 *) strpbrk ((const char *) str, (const char *) from); if (p) { int i; FcStrBufData (buf, str, p - str); i = strchr (from, *p) - from; FcStrBufChar (buf, i < to_len ? to[i] : repeat); str = p + 1; } else { FcStrBufString (buf, str); break; } } return FcTrue; } static FcBool interpret_convert (FcFormatContext *c, FcStrBuf *buf, int start) { const FcChar8 *str; FcChar8 *new_str; FcStrBuf new_buf; FcChar8 buf_static[8192]; FcBool ret; if (!expect_char (c, '|') || !read_word (c)) return FcFalse; /* prepare the buffer */ FcStrBufChar (buf, '\0'); if (buf->failed) return FcFalse; str = buf->buf + start; buf->len = start; /* try simple converters first */ if (0) { } #define CONVERTER(name, func) \ else if (0 == strcmp ((const char *) c->word, name))\ do { new_str = func (str); ret = FcTrue; } while (0) CONVERTER ("downcase", FcStrDowncase); CONVERTER ("basename", FcStrBasename); CONVERTER ("dirname", FcStrDirname); #undef CONVERTER else ret = FcFalse; if (ret) { if (new_str) { FcStrBufString (buf, new_str); FcStrFree (new_str); return FcTrue; } else return FcFalse; } FcStrBufInit (&new_buf, buf_static, sizeof (buf_static)); /* now try our custom converters */ if (0) { } #define CONVERTER(name, func) \ else if (0 == strcmp ((const char *) c->word, name))\ ret = func (c, str, &new_buf) CONVERTER ("cescape", cescape); CONVERTER ("shescape", shescape); CONVERTER ("xmlescape", xmlescape); CONVERTER ("delete", delete_chars); CONVERTER ("escape", escape_chars); CONVERTER ("translate", translate_chars); #undef CONVERTER else ret = FcFalse; if (ret) { FcStrBufChar (&new_buf, '\0'); FcStrBufString (buf, new_buf.buf); } else message ("unknown converter \"%s\"", c->word); FcStrBufDestroy (&new_buf); return ret; } static FcBool maybe_interpret_converts (FcFormatContext *c, FcStrBuf *buf, int start) { while (*c->format == '|') if (!interpret_convert (c, buf, start)) return FcFalse; return FcTrue; } static FcBool align_to_width (FcStrBuf *buf, int start, int width) { int len; if (buf->failed) return FcFalse; len = buf->len - start; if (len < -width) { /* left align */ while (len++ < -width) FcStrBufChar (buf, ' '); } else if (len < width) { int old_len; old_len = len; /* right align */ while (len++ < width) FcStrBufChar (buf, ' '); if (buf->failed) return FcFalse; len = old_len; memmove (buf->buf + buf->len - len, buf->buf + buf->len - width, len); memset (buf->buf + buf->len - width, ' ', width - len); } return !buf->failed; } static FcBool interpret_percent (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf) { int width, start; FcBool ret; if (!expect_char (c, '%')) return FcFalse; if (consume_char (c, '%')) /* "%%" */ { FcStrBufChar (buf, '%'); return FcTrue; } /* parse an optional width specifier */ width = strtol ((const char *) c->format, (char **) &c->format, 10); if (!expect_char (c, '{')) return FcFalse; start = buf->len; switch (*c->format) { case '=': ret = interpret_builtin (c, pat, buf); break; case '{': ret = interpret_subexpr (c, pat, buf); break; case '+': ret = interpret_filter_in (c, pat, buf); break; case '-': ret = interpret_filter_out (c, pat, buf); break; case '?': ret = interpret_cond (c, pat, buf); break; case '#': ret = interpret_count (c, pat, buf); break; case '[': ret = interpret_enumerate (c, pat, buf); break; default: ret = interpret_simple (c, pat, buf); break; } return ret && maybe_interpret_converts (c, buf, start) && align_to_width (buf, start, width) && expect_char (c, '}'); } static FcBool interpret_expr (FcFormatContext *c, FcPattern *pat, FcStrBuf *buf, FcChar8 term) { while (*c->format && *c->format != term) { switch (*c->format) { case '\\': c->format++; /* skip over '\\' */ if (*c->format) FcStrBufChar (buf, escaped_char (*c->format++)); continue; case '%': if (!interpret_percent (c, pat, buf)) return FcFalse; continue; } FcStrBufChar (buf, *c->format++); } return FcTrue; } static FcBool FcPatternFormatToBuf (FcPattern *pat, const FcChar8 *format, FcStrBuf *buf) { FcFormatContext c; FcChar8 word_static[1024]; FcBool ret; if (!FcFormatContextInit (&c, format, word_static, sizeof (word_static))) return FcFalse; ret = interpret_expr (&c, pat, buf, '\0'); FcFormatContextDone (&c); return ret; } FcChar8 * FcPatternFormat (FcPattern *pat, const FcChar8 *format) { FcStrBuf buf; FcChar8 buf_static[8192 - 1024]; FcPattern *alloced = NULL; FcBool ret; if (!pat) alloced = pat = FcPatternCreate (); FcStrBufInit (&buf, buf_static, sizeof (buf_static)); ret = FcPatternFormatToBuf (pat, format, &buf); if (alloced) FcPatternDestroy (alloced); if (ret) return FcStrBufDone (&buf); else { FcStrBufDestroy (&buf); return NULL; } } #define __fcformat__ #include "fcaliastail.h" #undef __fcformat__
02f5c161a4dc0752a3f032b6de9c7e0d80cd91c6
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/python/numpy/include/numpy/core/src/multiarray/textreading/rows.h
c10caf3f97db007bd4d931eef4c0c13e2081c067
[ "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C
false
false
201
h
rows.h
#ifdef USE_PYTHON3 #include <contrib/python/numpy/py3/numpy/core/src/multiarray/textreading/rows.h> #else #error #include <contrib/python/numpy/py2/numpy/core/src/multiarray/textreading/rows.h> #endif
2464f062e947641162560065d0fd4ada103fc5d1
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/openlldp/src/framehandlers/linux/lldp_linux_framer.h
69b2a774bcfaf3e10b9428d8f172933b4ea2d62e
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
332
h
lldp_linux_framer.h
#ifndef __LLDP_LINUX_FRAMER_H__ #define __LLDP_LINUX_FRAMER_H__ #include "lldp_port.h" int socketInitializeLLDP(); void socketCleanupLLDP(); static int _getmac(struct lldp_port *lldp_port); static int _getip(struct lldp_port *lldp_port); int refreshInterfaceData(struct lldp_port *lldp_port); #endif /* __LLDP_LINUX_FRAMER_H__ */
1e9ea22ecec161e223431fd3dd5fb0507b7c56e9
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/driver/xf86-video-geode/src/cim/cim_msr.c
6dd41834e7ff0e48abf42f95d64206b9c82a32dc
[ "MIT" ]
permissive
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
15,611
c
cim_msr.c
/* * Copyright (c) 2006 Advanced Micro Devices, Inc. * * 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. * * Neither the name of the Advanced Micro Devices, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. */ /* * Cimarron MSR access routines. These routines allow the user to query the * state of the GeodeLink Bus and read and write model-specfic registers. */ /*--------------------------------------------------------------*/ /* MSR GLOBALS */ /* These variables hold a local copy of the GeodeLink mapping */ /* as well as a lookup table for easy device addressing. */ /*--------------------------------------------------------------*/ GEODELINK_NODE gliu_nodes[24]; GEODELINK_NODE msr_dev_lookup[MSR_DEVICE_EMPTY]; #define GET_DEVICE_ID(macrohigh, macrolow) ((macrolow >> 12) & 0xFF) /*--------------------------------------------------------------------------- * msr_init_table * * This routine intializes the internal MSR table in Cimarron. This table is * used for any MSR device accesses. *--------------------------------------------------------------------------*/ int msr_init_table(void) { Q_WORD msr_value = { 0, 0 }; unsigned int i, j; int return_value = CIM_STATUS_OK; /* CHECK FOR VALID GEODELINK CONFIGURATION * The CPU and the three GLIUs are assumed to be at known static * addresses, so we will check the device IDs at these addresses as proof * of a valid GeodeLink configuration */ MSR_READ(MSR_GEODELINK_CAP, MSR_ADDRESS_VAIL, &msr_value); if (GET_DEVICE_ID(msr_value.high, msr_value.low) != MSR_CLASS_CODE_VAIL) return_value = CIM_STATUS_ERROR; MSR_READ(MSR_GEODELINK_CAP, MSR_ADDRESS_GLIU0, &msr_value); if (GET_DEVICE_ID(msr_value.high, msr_value.low) != MSR_CLASS_CODE_GLIU) return_value = CIM_STATUS_ERROR; MSR_READ(MSR_GEODELINK_CAP, MSR_ADDRESS_GLIU1, &msr_value); if (GET_DEVICE_ID(msr_value.high, msr_value.low) != MSR_CLASS_CODE_GLIU) return_value = CIM_STATUS_ERROR; MSR_READ(MSR_GEODELINK_CAP, MSR_ADDRESS_GLIU2, &msr_value); if (GET_DEVICE_ID(msr_value.high, msr_value.low) != MSR_CLASS_CODE_GLIU) return_value = CIM_STATUS_ERROR; if (return_value == CIM_STATUS_OK) { /* BUILD LOCAL COPY OF THE GEODELINK BUS */ msr_create_geodelink_table(gliu_nodes); /* CLEAR TABLE STATUS */ for (i = 0; i < MSR_DEVICE_EMPTY; i++) msr_dev_lookup[i].device_id = MSR_DEVICE_NOTFOUND; /* CREATE EASY LOOKUP TABLE FOR FUTURE HARDWARE ACCESS */ /* Note that MSR_DEVICE_EMPTY is the index after the last */ /* available device. Also note that we fill in known */ /* devices before filling in the rest of the table. */ msr_dev_lookup[MSR_DEVICE_GEODELX_GLIU0].address_from_cpu = MSR_ADDRESS_GLIU0; msr_dev_lookup[MSR_DEVICE_GEODELX_GLIU0].device_id = MSR_DEVICE_PRESENT; msr_dev_lookup[MSR_DEVICE_GEODELX_GLIU1].address_from_cpu = MSR_ADDRESS_GLIU1; msr_dev_lookup[MSR_DEVICE_GEODELX_GLIU1].device_id = MSR_DEVICE_PRESENT; msr_dev_lookup[MSR_DEVICE_5535_GLIU].address_from_cpu = MSR_ADDRESS_GLIU2; msr_dev_lookup[MSR_DEVICE_5535_GLIU].device_id = MSR_DEVICE_PRESENT; msr_dev_lookup[MSR_DEVICE_GEODELX_VAIL].address_from_cpu = MSR_ADDRESS_VAIL; msr_dev_lookup[MSR_DEVICE_GEODELX_VAIL].device_id = MSR_DEVICE_PRESENT; for (i = 0; i < MSR_DEVICE_EMPTY; i++) { if (msr_dev_lookup[i].device_id == MSR_DEVICE_NOTFOUND) { for (j = 0; j < 24; j++) { if (gliu_nodes[j].device_id == i) break; } if (j == 24) msr_dev_lookup[i].device_id = MSR_DEVICE_NOTFOUND; else { msr_dev_lookup[i].device_id = MSR_DEVICE_PRESENT; msr_dev_lookup[i].address_from_cpu = gliu_nodes[j].address_from_cpu; } } } } else { /* ERROR OUT THE GEODELINK TABLES */ for (i = 0; i < 24; i++) { gliu_nodes[i].address_from_cpu = 0xFFFFFFFF; gliu_nodes[i].device_id = MSR_DEVICE_EMPTY; } for (i = 0; i < MSR_DEVICE_EMPTY; i++) { msr_dev_lookup[i].address_from_cpu = 0xFFFFFFFF; msr_dev_lookup[i].device_id = MSR_DEVICE_NOTFOUND; } } return return_value; } /*--------------------------------------------------------------------------- * msr_create_geodelink_table * * This routine dumps the contents of the GeodeLink bus into an array of * 24 GEODELINK_NODE structures. Indexes 0-7 represent ports 0-7 of GLIU0, * indexes 8-15 represent ports 0-7 of GLIU1 and indexes 16-23 represent * ports 0-7 of GLIU2 (5535). *--------------------------------------------------------------------------*/ int msr_create_geodelink_table(GEODELINK_NODE * gliu_nodes) { unsigned long mbiu_port_count, reflective; unsigned long port, index; unsigned long gliu_count = 0; int glcp_count = 0; int usb_count = 0; int mpci_count = 0; Q_WORD msr_value = { 0, 0 }; /* ALL THREE GLIUS ARE IN ONE ARRAY */ /* Entries 0-7 contain the port information for GLIU0, entries */ /* 8-15 contain GLIU1 and 15-23 contain GLIU2. We perform the */ /* enumeration in two passes. The first simply fills in the */ /* addresses and class codes at each node. The second pass */ /* translates the class codes into indexes into Cimarron's device */ /* lookup table. */ /* COUNT GLIU0 PORTS */ MSR_READ(MSR_GLIU_CAP, MSR_ADDRESS_GLIU0, &msr_value); mbiu_port_count = (msr_value.high >> NUM_PORTS_SHIFT) & 7; /* FIND REFLECTIVE PORT */ /* Query the GLIU for the port through which we are communicating. */ /* We will avoid accesses to this port to avoid a self-reference. */ MSR_READ(MSR_GLIU_WHOAMI, MSR_ADDRESS_GLIU0, &msr_value); reflective = msr_value.low & WHOAMI_MASK; /* SPECIAL CASE FOR PORT 0 */ /* GLIU0 port 0 is a special case, as it points back to GLIU0. GLIU0 */ /* responds at address 0x10000xxx, which does not equal 0 << 29. */ gliu_nodes[0].address_from_cpu = MSR_ADDRESS_GLIU0; gliu_nodes[0].device_id = MSR_CLASS_CODE_GLIU; /* ENUMERATE ALL PORTS */ for (port = 1; port < 8; port++) { /* FILL IN ADDRESS */ gliu_nodes[port].address_from_cpu = port << 29; if (port == reflective) gliu_nodes[port].device_id = MSR_CLASS_CODE_REFLECTIVE; else if (port > mbiu_port_count) gliu_nodes[port].device_id = MSR_CLASS_CODE_UNPOPULATED; else { MSR_READ(MSR_GEODELINK_CAP, gliu_nodes[port].address_from_cpu, &msr_value); gliu_nodes[port].device_id = GET_DEVICE_ID(msr_value.high, msr_value.low); } } /* COUNT GLIU1 PORTS */ MSR_READ(MSR_GLIU_CAP, MSR_ADDRESS_GLIU1, &msr_value); mbiu_port_count = (msr_value.high >> NUM_PORTS_SHIFT) & 7; /* FIND REFLECTIVE PORT */ MSR_READ(MSR_GLIU_WHOAMI, MSR_ADDRESS_GLIU1, &msr_value); reflective = msr_value.low & WHOAMI_MASK; /* ENUMERATE ALL PORTS */ for (port = 0; port < 8; port++) { index = port + 8; /* FILL IN ADDRESS */ gliu_nodes[index].address_from_cpu = (0x02l << 29) + (port << 26); if (port == reflective) gliu_nodes[index].device_id = MSR_CLASS_CODE_REFLECTIVE; else if (port > mbiu_port_count) gliu_nodes[index].device_id = MSR_CLASS_CODE_UNPOPULATED; else { MSR_READ(MSR_GEODELINK_CAP, gliu_nodes[index].address_from_cpu, &msr_value); gliu_nodes[index].device_id = GET_DEVICE_ID(msr_value.high, msr_value.low); } } /* COUNT GLIU2 PORTS */ MSR_READ(MSR_GLIU_CAP, MSR_ADDRESS_GLIU2, &msr_value); mbiu_port_count = (msr_value.high >> NUM_PORTS_SHIFT) & 7; /* FIND REFLECTIVE PORT */ MSR_READ(MSR_GLIU_WHOAMI, MSR_ADDRESS_GLIU2, &msr_value); reflective = msr_value.low & WHOAMI_MASK; /* FILL IN PORT 0 AND 1 */ /* Port 0 on 5535 is MBIU2. Port 1 is MPCI, but it is referenced at */ /* a special address. */ gliu_nodes[16].address_from_cpu = MSR_ADDRESS_GLIU2; gliu_nodes[16].device_id = MSR_CLASS_CODE_GLIU; gliu_nodes[17].address_from_cpu = MSR_ADDRESS_5535MPCI; gliu_nodes[17].device_id = MSR_CLASS_CODE_MPCI; /* ENUMERATE ALL PORTS */ for (port = 2; port < 8; port++) { index = port + 16; /* FILL IN ADDRESS */ gliu_nodes[index].address_from_cpu = (0x02l << 29) + (0x04l << 26) + (0x02l << 23) + (port << 20); if (port == reflective) gliu_nodes[index].device_id = MSR_CLASS_CODE_REFLECTIVE; else if (port > mbiu_port_count) gliu_nodes[index].device_id = MSR_CLASS_CODE_UNPOPULATED; else { MSR_READ(MSR_GEODELINK_CAP, gliu_nodes[index].address_from_cpu, &msr_value); gliu_nodes[index].device_id = GET_DEVICE_ID(msr_value.high, msr_value.low); } } /* SECOND PASS - TRANSLATION */ /* Now that the class codes for each device are stored in the */ /* array, we walk through the array and translate the class */ /* codes to table indexes. For class codes that have multiple */ /* instances, the table indexes are sequential. */ for (port = 0; port < 24; port++) { /* SPECIAL CASE FOR GLIU UNITS */ /* A GLIU can be both on another port and on its own port. These */ /* end up as the same address, but are shown as duplicate nodes in */ /* the GeodeLink table. */ if ((port & 7) == 0) gliu_count = port >> 3; switch (gliu_nodes[port].device_id) { /* UNPOPULATED OR REFLECTIVE NODES */ case MSR_CLASS_CODE_UNPOPULATED: index = MSR_DEVICE_EMPTY; break; case MSR_CLASS_CODE_REFLECTIVE: index = MSR_DEVICE_REFLECTIVE; break; /* KNOWN CLASS CODES */ case MSR_CLASS_CODE_GLIU: index = MSR_DEVICE_GEODELX_GLIU0 + gliu_count++; break; case MSR_CLASS_CODE_GLCP: index = MSR_DEVICE_GEODELX_GLCP + glcp_count++; break; case MSR_CLASS_CODE_MPCI: index = MSR_DEVICE_GEODELX_MPCI + mpci_count++; break; case MSR_CLASS_CODE_USB: index = MSR_DEVICE_5535_USB2 + usb_count++; break; case MSR_CLASS_CODE_USB2: index = MSR_DEVICE_5536_USB_2_0; break; case MSR_CLASS_CODE_ATAC: index = MSR_DEVICE_5535_ATAC; break; case MSR_CLASS_CODE_MDD: index = MSR_DEVICE_5535_MDD; break; case MSR_CLASS_CODE_ACC: index = MSR_DEVICE_5535_ACC; break; case MSR_CLASS_CODE_MC: index = MSR_DEVICE_GEODELX_MC; break; case MSR_CLASS_CODE_GP: index = MSR_DEVICE_GEODELX_GP; break; case MSR_CLASS_CODE_VG: index = MSR_DEVICE_GEODELX_VG; break; case MSR_CLASS_CODE_DF: index = MSR_DEVICE_GEODELX_DF; break; case MSR_CLASS_CODE_FG: index = MSR_DEVICE_GEODELX_FG; break; case MSR_CLASS_CODE_VIP: index = MSR_DEVICE_GEODELX_VIP; break; case MSR_CLASS_CODE_AES: index = MSR_DEVICE_GEODELX_AES; break; case MSR_CLASS_CODE_VAIL: index = MSR_DEVICE_GEODELX_VAIL; break; default: index = MSR_DEVICE_EMPTY; break; } gliu_nodes[port].device_id = index; } return CIM_STATUS_OK; } /*--------------------------------------------------------------------------- * msr_create_device_list * * This routine dumps a list of all known GeodeLX/5535 devices as well as their * respective status and address. *--------------------------------------------------------------------------*/ int msr_create_device_list(GEODELINK_NODE * gliu_nodes, int max_devices) { int i, count; if (max_devices < MSR_DEVICE_EMPTY) count = max_devices; else count = MSR_DEVICE_EMPTY; for (i = 0; i < count; i++) { gliu_nodes[i].address_from_cpu = msr_dev_lookup[i].address_from_cpu; gliu_nodes[i].device_id = msr_dev_lookup[i].device_id; } return CIM_STATUS_OK; } /*-------------------------------------------------------------------- * msr_read64 * * Performs a 64-bit read from 'msr_register' in device 'device'. 'device' is * an index into Cimarron's table of known GeodeLink devices. *-------------------------------------------------------------------*/ int msr_read64(unsigned long device, unsigned long msr_register, Q_WORD * msr_value) { if (device < MSR_DEVICE_EMPTY) { if (msr_dev_lookup[device].device_id == MSR_DEVICE_PRESENT) { MSR_READ(msr_register, msr_dev_lookup[device].address_from_cpu, msr_value); return CIM_STATUS_OK; } } msr_value->low = msr_value->high = 0; return CIM_STATUS_DEVNOTFOUND; } /*-------------------------------------------------------------------- * msr_write64 * * Performs a 64-bit write to 'msr_register' in device 'device'. 'device' is * an index into Cimarron's table of known GeodeLink devices. *-------------------------------------------------------------------*/ int msr_write64(unsigned long device, unsigned long msr_register, Q_WORD * msr_value) { if (device < MSR_DEVICE_EMPTY) { if (msr_dev_lookup[device].device_id == MSR_DEVICE_PRESENT) { MSR_WRITE(msr_register, msr_dev_lookup[device].address_from_cpu, msr_value); return CIM_STATUS_OK; } } return CIM_STATUS_DEVNOTFOUND; }
544918cb356a0d67d297e4f38cfcbd75d3949773
a0838b4cd2ce8a2862a6a82dc2e75a701447c28b
/components/hmc5883l/hmc5883l.h
789c07c1d122520ae44cd8c5cf74c6a15f2e6fd6
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
UncleRus/esp-idf-lib
bfa97226f6df9313dd01f56de1b8bef1824ad642
9dd86b23aff2445b905da63d3c6481474e430a10
refs/heads/master
2023-08-31T06:04:48.102658
2023-08-30T15:57:59
2023-08-30T15:57:59
126,475,029
1,117
394
null
2023-09-01T06:25:56
2018-03-23T11:17:22
C
UTF-8
C
false
false
9,021
h
hmc5883l.h
/* * Copyright (c) 2016 Ruslan V. Uss <unclerus@gmail.com> * * 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 itscontributors * 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. */ /** * @file hmc5883l.h * @defgroup hmc5883l hmc5883l * @{ * * ESP-IDF Driver for 3-axis digital compass HMC5883L and HMC5983L * * Ported from esp-open-rtos * * Copyright (c) 2016 Ruslan V. Uss <unclerus@gmail.com> * * BSD Licensed as described in the file LICENSE */ #ifndef __HMC5883L_H__ #define __HMC5883L_H__ #include <stdint.h> #include <stdbool.h> #include <i2cdev.h> #include <esp_err.h> #ifdef __cplusplus extern "C" { #endif #define HMC5883L_ADDR 0x1e //!< I2C address #define HMC5883L_ID 0x00333448 //!< Chip ID, "H43" /** * Device operating mode */ typedef enum { HMC5883L_MODE_CONTINUOUS = 0, //!< Continuous mode HMC5883L_MODE_SINGLE //!< Single measurement mode, default } hmc5883l_opmode_t; /** * Number of samples averaged per measurement */ typedef enum { HMC5883L_SAMPLES_1 = 0, //!< 1 sample, default HMC5883L_SAMPLES_2, //!< 2 samples HMC5883L_SAMPLES_4, //!< 4 samples HMC5883L_SAMPLES_8 //!< 8 samples } hmc5883l_samples_averaged_t; /** * Data output rate in continuous measurement mode */ typedef enum { HMC5883L_DATA_RATE_00_75 = 0, //!< 0.75 Hz HMC5883L_DATA_RATE_01_50, //!< 1.5 Hz HMC5883L_DATA_RATE_03_00, //!< 3 Hz HMC5883L_DATA_RATE_07_50, //!< 7.5 Hz HMC5883L_DATA_RATE_15_00, //!< 15 Hz, default HMC5883L_DATA_RATE_30_00, //!< 30 Hz HMC5883L_DATA_RATE_75_00, //!< 75 Hz HMC5883L_DATA_RATE_220_00 //!< 220 Hz, HMC5983 only } hmc5883l_data_rate_t; /** * Measurement mode of the device (bias) */ typedef enum { HMC5883L_BIAS_NORMAL = 0, //!< Default flow, no bias HMC5883L_BIAS_POSITIVE, //!< Positive bias configuration all axes, used for self test (see datasheet) HMC5883L_BIAS_NEGATIVE //!< Negative bias configuration all axes, used for self test (see datasheet) } hmc5883l_bias_t; /** * Device gain */ typedef enum { HMC5883L_GAIN_1370 = 0, //!< 0.73 mG/LSb, range -0.88..+0.88 G HMC5883L_GAIN_1090, //!< 0.92 mG/LSb, range -1.3..+1.3 G, default HMC5883L_GAIN_820, //!< 1.22 mG/LSb, range -1.9..+1.9 G HMC5883L_GAIN_660, //!< 1.52 mG/LSb, range -2.5..+2.5 G HMC5883L_GAIN_440, //!< 2.27 mG/LSb, range -4.0..+4.0 G HMC5883L_GAIN_390, //!< 2.56 mG/LSb, range -4.7..+4.7 G HMC5883L_GAIN_330, //!< 3.03 mG/LSb, range -5.6..+5.6 G HMC5883L_GAIN_230 //!< 4.35 mG/LSb, range -8.1..+8.1 G } hmc5883l_gain_t; /** * Device descriptor */ typedef struct { i2c_dev_t i2c_dev; //!< I2C device descriptor hmc5883l_opmode_t opmode; //!< Operating mode float gain; //!< Gain } hmc5883l_dev_t; /** * Raw measurement result */ typedef struct { int16_t x; int16_t y; int16_t z; } hmc5883l_raw_data_t; /** * Measurement result, milligauss */ typedef struct { float x; float y; float z; } hmc5883l_data_t; /** * @brief Initialize device descriptor * * @param dev Device descriptor * @param port I2C port number * @param sda_gpio GPIO pin number for SDA * @param scl_gpio GPIO pin number for SCL * @return `ESP_OK` on success */ esp_err_t hmc5883l_init_desc(hmc5883l_dev_t *dev, i2c_port_t port, gpio_num_t sda_gpio, gpio_num_t scl_gpio); /** * @brief Free device descriptor * * @param dev Device descriptor * @return `ESP_OK` on success */ esp_err_t hmc5883l_free_desc(hmc5883l_dev_t *dev); /** * @brief Initialize device * * @param dev Device descriptor * @return `ESP_OK` on success */ esp_err_t hmc5883l_init(hmc5883l_dev_t *dev); /** * @brief Get operating mode * * @param dev Device descriptor * @param[out] val Operating mode * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_opmode(hmc5883l_dev_t *dev, hmc5883l_opmode_t *val); /** * @brief Set operating mode * * @param dev Device descriptor * @param mode Operating mode * @return `ESP_OK` on success */ esp_err_t hmc5883l_set_opmode(hmc5883l_dev_t *dev, hmc5883l_opmode_t mode); /** * @brief Get number of samples averaged per measurement output * * @param dev Device descriptor * @param[out] val Number of samples * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_samples_averaged(hmc5883l_dev_t *dev, hmc5883l_samples_averaged_t *val); /** * @brief Set number of samples averaged per measurement output * * @param dev Device descriptor * @param samples Number of samples * @return `ESP_OK` on success */ esp_err_t hmc5883l_set_samples_averaged(hmc5883l_dev_t *dev, hmc5883l_samples_averaged_t samples); /** * @brief Get data output rate in continuous measurement mode * * @param dev Device descriptor * @param[out] val Data output rate * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_data_rate(hmc5883l_dev_t *dev, hmc5883l_data_rate_t *val); /** * @brief Set data output rate in continuous measurement mode * * @param dev Device descriptor * @param rate Data output rate * @return `ESP_OK` on success */ esp_err_t hmc5883l_set_data_rate(hmc5883l_dev_t *dev, hmc5883l_data_rate_t rate); /** * @brief Get measurement mode (bias of the axes) * * See datasheet for self test description. * * @param dev Device descriptor * @param[out] val Bias * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_bias(hmc5883l_dev_t *dev, hmc5883l_bias_t *val); /** * @brief Set measurement mode (bias of the axes) * * See datasheet for self test description. * * @param dev Device descriptor * @param bias Bias * @return `ESP_OK` on success */ esp_err_t hmc5883l_set_bias(hmc5883l_dev_t *dev, hmc5883l_bias_t bias); /** * @brief Get device gain * * @param dev Device descriptor * @param[out] val Current gain * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_gain(hmc5883l_dev_t *dev, hmc5883l_gain_t *val); /** * @brief Set device gain * @param dev Device descriptor * @param gain Gain * @return `ESP_OK` on success */ esp_err_t hmc5883l_set_gain(hmc5883l_dev_t *dev, hmc5883l_gain_t gain); /** * @brief Get data state * * @param dev Device descriptor * @param[out] val true when data is written to all six data registers * @return `ESP_OK` on success */ esp_err_t hmc5883l_data_is_ready(hmc5883l_dev_t *dev, bool *val); /** * @brief Get lock state * * If data is locked, any new data will not be placed in data registers until * one of these conditions are met: * - data have been read, * - operating mode is changed, * - the measurement configuration (bias) is changed, * - power is reset. * * @param dev Device descriptor * @param[out] val true when data registers is locked * @return `ESP_OK` on success */ esp_err_t hmc5883l_data_is_locked(hmc5883l_dev_t *dev, bool *val); /** * @brief Get raw magnetic data * * @param dev Device descriptor * @param[out] data Raw data * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_raw_data(hmc5883l_dev_t *dev, hmc5883l_raw_data_t *data); /** * @brief Convert raw magnetic data to milligausses * * @param dev Device descriptor * @param raw Source raw data * @param[out] mg Converted data */ esp_err_t hmc5883l_raw_to_mg(const hmc5883l_dev_t *dev, const hmc5883l_raw_data_t *raw, hmc5883l_data_t *mg); /** * @brief Get magnetic data in milligausses * * @param dev Device descriptor * @param[out] data Magnetic data * @return `ESP_OK` on success */ esp_err_t hmc5883l_get_data(hmc5883l_dev_t *dev, hmc5883l_data_t *data); #ifdef __cplusplus } #endif /**@}*/ #endif /* __HMC5883L_H__ */
17c61dd5868343785431bbb350946da15f29adfa
736e760612f2b431c4b2524fe1a4a8e4083c72a1
/libflv/include/flv-parser.h
413661cf70e89cebc88669329c5349862988409e
[ "MIT" ]
permissive
ireader/media-server
7f86da8ff0c8694876a2043d50a1260f315dad8a
3d8647f50fe832856f42b03d1e5b0fe2eafe5796
refs/heads/master
2023-09-03T17:53:13.722595
2023-09-02T03:38:19
2023-09-02T03:38:19
15,598,496
2,785
1,015
MIT
2023-08-30T03:45:24
2014-01-03T01:43:35
C
UTF-8
C
false
false
1,721
h
flv-parser.h
#ifndef _flv_parser_h_ #define _flv_parser_h_ #include <stdint.h> #include <stddef.h> #include "flv-header.h" #if defined(__cplusplus) extern "C" { #endif /// Audio/Video Elementary Stream /// @param[in] param user-defined parameter /// @param[in] codec audio/video format (see more flv-proto.h) /// @param[in] data audio/video element data, AAC: AAC-Frame, H.264: MP4 Stream, MP3-Raw data /// @param[in] bytes data length in byte /// @param[in] pts audio/video presentation timestamp /// @param[in] dts audio/video decoding timestamp /// @param[in] flags 1-video keyframe, other-undefined /// @return 0-ok, other-error typedef int (*flv_parser_handler)(void* param, int codec, const void* data, size_t bytes, uint32_t pts, uint32_t dts, int flags); /// Input FLV Audio/Video Stream /// @param[in] type 8-audio, 9-video, 18-script (see more flv-proto.h) /// @param[in] data flv audio/video Stream, AudioTagHeader/VideoTagHeader + A/V Data /// @param[in] bytes data length in byte /// @param[in] timestamp milliseconds relative to the first tag(DTS) /// @return 0-ok, other-error int flv_parser_tag(int type, const void* data, size_t bytes, uint32_t timestamp, flv_parser_handler handler, void* param); struct flv_parser_t { int state; size_t bytes; size_t expect; uint8_t ptr[32]; struct flv_header_t header; struct flv_tag_header_t tag; struct flv_audio_tag_header_t audio; struct flv_video_tag_header_t video; uint8_t* body; void* (*alloc)(void* param, size_t bytes); void (*free)(void* param, void* ptr); }; int flv_parser_input(struct flv_parser_t* parser, const uint8_t* data, size_t bytes, flv_parser_handler handler, void* param); #if defined(__cplusplus) } #endif #endif /* !_flv_parser_h_ */
831e7ffb180f820ff9bc7edfe3021f677de9e6e4
321d11eaee885ceb3a74db0a062f9bbdf282148c
/crypto/bio/bio_cb.c
8e4f79ea3cd7a854839280466d7b8fd612a0801a
[ "Apache-2.0", "OpenSSL", "LicenseRef-scancode-proprietary-license" ]
permissive
openssl/openssl
75691ebaae957793f2ff0673f77545277dfb3988
5318c012885a5382eadbf95aa9c1d35664bca819
refs/heads/master
2023-09-03T15:22:52.727123
2023-09-01T07:10:49
2023-09-02T14:30:01
7,634,677
24,148
11,569
Apache-2.0
2023-09-14T19:48:11
2013-01-15T22:34:48
C
UTF-8
C
false
false
4,288
c
bio_cb.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <string.h> #include <stdlib.h> #include "bio_local.h" #include "internal/cryptlib.h" #include <openssl/err.h> long BIO_debug_callback_ex(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { BIO *b; char buf[256]; char *p; int left; size_t l = 0; BIO_MMSG_CB_ARGS *args; long ret_ = ret; if (processed != NULL) l = *processed; left = BIO_snprintf(buf, sizeof(buf), "BIO[%p]: ", (void *)bio); /* Ignore errors and continue printing the other information. */ if (left < 0) left = 0; p = buf + left; left = sizeof(buf) - left; switch (cmd) { case BIO_CB_FREE: BIO_snprintf(p, left, "Free - %s\n", bio->method->name); break; case BIO_CB_READ: if (bio->method->type & BIO_TYPE_DESCRIPTOR) BIO_snprintf(p, left, "read(%d,%zu) - %s fd=%d\n", bio->num, len, bio->method->name, bio->num); else BIO_snprintf(p, left, "read(%d,%zu) - %s\n", bio->num, len, bio->method->name); break; case BIO_CB_WRITE: if (bio->method->type & BIO_TYPE_DESCRIPTOR) BIO_snprintf(p, left, "write(%d,%zu) - %s fd=%d\n", bio->num, len, bio->method->name, bio->num); else BIO_snprintf(p, left, "write(%d,%zu) - %s\n", bio->num, len, bio->method->name); break; case BIO_CB_PUTS: BIO_snprintf(p, left, "puts() - %s\n", bio->method->name); break; case BIO_CB_GETS: BIO_snprintf(p, left, "gets(%zu) - %s\n", len, bio->method->name); break; case BIO_CB_CTRL: BIO_snprintf(p, left, "ctrl(%d) - %s\n", argi, bio->method->name); break; case BIO_CB_RECVMMSG: args = (BIO_MMSG_CB_ARGS *)argp; BIO_snprintf(p, left, "recvmmsg(%zu) - %s", args->num_msg, bio->method->name); break; case BIO_CB_SENDMMSG: args = (BIO_MMSG_CB_ARGS *)argp; BIO_snprintf(p, left, "sendmmsg(%zu) - %s", args->num_msg, bio->method->name); break; case BIO_CB_RETURN | BIO_CB_READ: BIO_snprintf(p, left, "read return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_WRITE: BIO_snprintf(p, left, "write return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_GETS: BIO_snprintf(p, left, "gets return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_PUTS: BIO_snprintf(p, left, "puts return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_CTRL: BIO_snprintf(p, left, "ctrl return %d\n", ret); break; case BIO_CB_RETURN | BIO_CB_RECVMMSG: BIO_snprintf(p, left, "recvmmsg processed: %zu\n", len); ret_ = (long)len; break; case BIO_CB_RETURN | BIO_CB_SENDMMSG: BIO_snprintf(p, left, "sendmmsg processed: %zu\n", len); ret_ = (long)len; break; default: BIO_snprintf(p, left, "bio callback - unknown type (%d)\n", cmd); break; } b = (BIO *)bio->cb_arg; if (b != NULL) BIO_write(b, buf, strlen(buf)); #if !defined(OPENSSL_NO_STDIO) else fputs(buf, stderr); #endif return ret_; } #ifndef OPENSSL_NO_DEPRECATED_3_0 long BIO_debug_callback(BIO *bio, int cmd, const char *argp, int argi, long argl, long ret) { size_t processed = 0; if (ret > 0) processed = (size_t)ret; BIO_debug_callback_ex(bio, cmd, argp, (size_t)argi, argi, argl, ret > 0 ? 1 : (int)ret, &processed); return ret; } #endif
1560da96b0724744b74be63815cb83c6a64ccb52
3fe78c7fda8265db8335de4e5b17cde1ee7990e3
/code/src/display/orxFont.c
001822e4121618b3ccb4e2490e2ef7e311cc7323
[ "Zlib" ]
permissive
orx/orx
c0628258025e63e59319c8126c5a5c2da9755420
7163f753f970b28818c7064dfd9b52a29c701967
refs/heads/master
2023-08-30T03:08:52.575944
2023-08-23T17:53:22
2023-08-23T17:53:22
39,714,458
1,358
118
Zlib
2023-07-26T00:27:33
2015-07-26T05:15:23
C
UTF-8
C
false
false
45,715
c
orxFont.c
/* Orx - Portable Game Engine * * Copyright (c) 2008-2022 Orx-Project * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ /** * @file orxFont.c * @date 08/03/2010 * @author iarwain@orx-project.org * */ #include "display/orxFont.h" #include "memory/orxBank.h" #include "core/orxConfig.h" #include "core/orxEvent.h" #include "core/orxResource.h" #include "display/orxDisplay.h" #include "object/orxStructure.h" #include "utils/orxHashTable.h" /** Module flags */ #define orxFONT_KU32_STATIC_FLAG_NONE 0x00000000 /**< No flags */ #define orxFONT_KU32_STATIC_FLAG_READY 0x00000001 /**< Ready flag */ #define orxFONT_KU32_STATIC_MASK_ALL 0xFFFFFFFF /**< All mask */ /** orxFONT flags / masks */ #define orxFONT_KU32_FLAG_NONE 0x00000000 /**< No flags */ #define orxFONT_KU32_FLAG_INTERNAL 0x10000000 /**< Internal structure handling flag */ #define orxFONT_KU32_FLAG_REFERENCED 0x20000000 /**< Referenced flag */ #define orxFONT_KU32_MASK_ALL 0xFFFFFFFF /**< All mask */ /** Misc defines */ #define orxFONT_KU32_MAP_BANK_SIZE 4 /**< Map bank size */ #define orxFONT_KU32_REFERENCE_TABLE_SIZE 4 /**< Reference table size */ #define orxFONT_KU32_CHARACTER_BANK_SIZE 256 /**< Character bank size */ #define orxFONT_KU32_CHARACTER_TABLE_SIZE 256 /**< Character table size */ #define orxFONT_KU32_BANK_SIZE 16 /**< Bank size */ #define orxFONT_KZ_CONFIG_TEXTURE_NAME "Texture" #define orxFONT_KZ_CONFIG_CHARACTER_LIST "CharacterList" #define orxFONT_KZ_CONFIG_CHARACTER_SIZE "CharacterSize" #define orxFONT_KZ_CONFIG_CHARACTER_HEIGHT "CharacterHeight" #define orxFONT_KZ_CONFIG_CHARACTER_WIDTH_LIST "CharacterWidthList" #define orxFONT_KZ_CONFIG_CHARACTER_SPACING "CharacterSpacing" #define orxFONT_KZ_CONFIG_TEXTURE_ORIGIN "TextureOrigin" #define orxFONT_KZ_CONFIG_TEXTURE_SIZE "TextureSize" #define orxFONT_KZ_CONFIG_TEXTURE_CORNER "TextureCorner" /**< Kept for retro-compatibility reason */ #define orxFONT_KZ_CONFIG_KEEP_IN_CACHE "KeepInCache" /*************************************************************************** * Structure declaration * ***************************************************************************/ /** Font structure */ struct __orxFONT_t { orxSTRUCTURE stStructure; /**< Public structure, first structure member : 32 */ orxCHARACTER_MAP *pstMap; /**< Font's map : 20 */ orxFLOAT *afCharacterWidthList; /**< Character width list : 24 */ orxFLOAT fCharacterHeight; /**< Character height : 28 */ orxVECTOR vCharacterSpacing; /**< Character spacing : 40 */ orxTEXTURE *pstTexture; /**< Texture : 44 */ orxFLOAT fTop; /**< Top coordinate : 48 */ orxFLOAT fLeft; /**< Left coordinate : 52 */ orxFLOAT fWidth; /**< Width : 56 */ orxFLOAT fHeight; /**< Height : 60 */ const orxSTRING zCharacterList; /**< Character list : 64 */ const orxSTRING zReference; /**< Config reference : 68 */ }; /** Static structure */ typedef struct __orxFONT_STATIC_t { orxBANK *pstMapBank; /**< Map bank : 4 */ orxHASHTABLE *pstReferenceTable; /**< Reference table : 8 */ orxFONT *pstDefaultFont; /**< Default font : 12 */ orxU32 u32Flags; /**< Control flags : 16 */ } orxFONT_STATIC; /*************************************************************************** * Module global variable * ***************************************************************************/ static orxFONT_STATIC sstFont; #include "../src/display/orxDefaultFont.inc" /*************************************************************************** * Private functions * ***************************************************************************/ /** Updates font's map * @param[in] _pstFont Concerned font */ static void orxFASTCALL orxFont_UpdateMap(orxFONT *_pstFont) { /* Check */ orxSTRUCTURE_ASSERT(_pstFont); /* Clears UTF-8 table */ orxHashTable_Clear(_pstFont->pstMap->pstCharacterTable); /* Clears UTF-8 bank */ orxBank_Clear(_pstFont->pstMap->pstCharacterBank); /* Has texture, texture size, character size and character list? */ if((_pstFont->pstTexture != orxNULL) && (_pstFont->fWidth > orxFLOAT_0) && (_pstFont->fHeight > orxFLOAT_0) && (_pstFont->fCharacterHeight > orxFLOAT_0) && (_pstFont->afCharacterWidthList != orxNULL) && (_pstFont->zCharacterList != orxSTRING_EMPTY)) { const orxCHAR *pc; orxU32 u32CharacterCodePoint; orxS32 s32Index; orxVECTOR vOrigin; /* For all defined characters */ for(s32Index = 0, u32CharacterCodePoint = orxString_GetFirstCharacterCodePoint(_pstFont->zCharacterList, &pc), orxVector_Set(&vOrigin, _pstFont->fLeft, _pstFont->fTop, orxFLOAT_0); (u32CharacterCodePoint != orxCHAR_NULL) && (vOrigin.fY < _pstFont->fTop + _pstFont->fHeight); s32Index++, u32CharacterCodePoint = orxString_GetFirstCharacterCodePoint(pc, &pc)) { orxCHARACTER_GLYPH **ppstBucket; orxCHARACTER_GLYPH *pstGlyph; /* Gets glyph's bucket */ ppstBucket = (orxCHARACTER_GLYPH **)orxHashTable_Retrieve(_pstFont->pstMap->pstCharacterTable, u32CharacterCodePoint); /* Checks */ orxASSERT(ppstBucket != orxNULL); /* Not already defined? */ if(*ppstBucket == orxNULL) { /* Allocates it */ pstGlyph = (orxCHARACTER_GLYPH *)orxBank_Allocate(_pstFont->pstMap->pstCharacterBank); /* Checks */ orxASSERT(pstGlyph != orxNULL); /* Adds it to table */ *ppstBucket = pstGlyph; } else { /* Gets it */ pstGlyph = *ppstBucket; } /* Stores its width */ pstGlyph->fWidth = _pstFont->afCharacterWidthList[s32Index]; /* Out of bound? */ if(vOrigin.fX + pstGlyph->fWidth > _pstFont->fLeft + _pstFont->fWidth) { /* Reinits its X value */ vOrigin.fX = _pstFont->fLeft; /* Updates its Y value */ vOrigin.fY += _pstFont->fCharacterHeight + _pstFont->vCharacterSpacing.fY; } /* Stores its origin */ pstGlyph->fX = vOrigin.fX; pstGlyph->fY = vOrigin.fY; /* Updates current origin X value */ vOrigin.fX += pstGlyph->fWidth + _pstFont->vCharacterSpacing.fX; } /* Optimizes character table */ orxHashTable_Optimize(_pstFont->pstMap->pstCharacterTable); /* Stores character height */ _pstFont->pstMap->fCharacterHeight = _pstFont->fCharacterHeight; /* Had more defined characters? */ if(u32CharacterCodePoint != orxCHAR_NULL) { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Too many characters defined for font <%s>: couldn't map characters [%s].", _pstFont->zReference, pc); } } /* Done! */ return; } /* Creates default font */ static orxINLINE void orxFont_CreateDefaultFont() { orxTEXTURE *pstTexture; /* Creates texture */ pstTexture = orxTexture_Create(); /* Success? */ if(pstTexture != orxNULL) { orxBITMAP *pstBitmap; /* Creates bitmap */ pstBitmap = orxDisplay_CreateBitmap(sstDefaultFont.u32Width, sstDefaultFont.u32Height); /* Success? */ if(pstBitmap != orxNULL) { /* Sets it data */ if(orxDisplay_SetBitmapData(pstBitmap, sstDefaultFont.au8Data, sstDefaultFont.u32Width * sstDefaultFont.u32Height * 4) != orxSTATUS_FAILURE) { /* Links it to texture and transfers its ownership */ if(orxTexture_LinkBitmap(pstTexture, pstBitmap, orxFONT_KZ_DEFAULT_FONT_NAME, orxTRUE) != orxSTATUS_FAILURE) { /* Creates default font */ sstFont.pstDefaultFont = orxFont_Create(); /* Success? */ if(sstFont.pstDefaultFont != orxNULL) { /* Sets it as its own owner */ orxStructure_SetOwner(sstFont.pstDefaultFont, sstFont.pstDefaultFont); /* Sets its texture */ if(orxFont_SetTexture(sstFont.pstDefaultFont, pstTexture) != orxSTATUS_FAILURE) { orxVECTOR vSpacing; orxFLOAT *afCharacterWidthList; orxU32 u32CharacterCount, i; /* Sets font as texture's owner */ orxStructure_SetOwner(pstTexture, sstFont.pstDefaultFont); /* Gets character count */ u32CharacterCount = orxString_GetCharacterCount(sstDefaultFont.zCharacterList); /* Allocates array for character widths */ afCharacterWidthList = (orxFLOAT *)orxMemory_Allocate(u32CharacterCount * sizeof(orxFLOAT), orxMEMORY_TYPE_MAIN); /* For all characters */ for(i = 0; i < u32CharacterCount; i++) { /* Stores its width */ afCharacterWidthList[i] = sstDefaultFont.fCharacterWidth; } /* Inits font */ orxFont_SetCharacterList(sstFont.pstDefaultFont, sstDefaultFont.zCharacterList); orxFont_SetCharacterHeight(sstFont.pstDefaultFont, sstDefaultFont.fCharacterHeight); orxFont_SetCharacterWidthList(sstFont.pstDefaultFont, u32CharacterCount, afCharacterWidthList); orxFont_SetCharacterSpacing(sstFont.pstDefaultFont, orxVector_Set(&vSpacing, sstDefaultFont.fCharacterSpacingX, sstDefaultFont.fCharacterSpacingY, orxFLOAT_0)); /* Stores its reference key */ sstFont.pstDefaultFont->zReference = orxFONT_KZ_DEFAULT_FONT_NAME; /* Adds it to reference table */ orxHashTable_Add(sstFont.pstReferenceTable, orxString_Hash(sstFont.pstDefaultFont->zReference), sstFont.pstDefaultFont); /* Updates its flags */ orxStructure_SetFlags(sstFont.pstDefaultFont, orxFONT_KU32_FLAG_REFERENCED, orxFONT_KU32_FLAG_NONE); /* Frees character widths array */ orxMemory_Free(afCharacterWidthList); } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set default font's texture."); /* Deletes font */ orxFont_Delete(sstFont.pstDefaultFont); sstFont.pstDefaultFont = orxNULL; /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't create default font."); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't link default font's bitmap to texture."); /* Deletes bitmap */ orxDisplay_DeleteBitmap(pstBitmap); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set default font's bitmap's data."); /* Deletes bitmap */ orxDisplay_DeleteBitmap(pstBitmap); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't create default font's bitmap."); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't create default font's texture."); } } static orxSTATUS orxFASTCALL orxFont_ProcessConfigData(orxFONT *_pstFont) { orxSTATUS eResult = orxSTATUS_FAILURE; /* Has reference? */ if((_pstFont->zReference != orxNULL) && (*(_pstFont->zReference) != orxCHAR_NULL) && (orxConfig_HasSection(_pstFont->zReference) != orxFALSE)) { const orxSTRING zName; /* Pushes its config section */ orxConfig_PushSection(_pstFont->zReference); /* Gets texture name */ zName = orxConfig_GetString(orxFONT_KZ_CONFIG_TEXTURE_NAME); /* Valid? */ if((zName != orxNULL) && (zName != orxSTRING_EMPTY)) { orxTEXTURE *pstTexture; /* Loads texture */ pstTexture = orxTexture_Load(zName, orxConfig_GetBool(orxFONT_KZ_CONFIG_KEEP_IN_CACHE)); /* Valid? */ if(pstTexture != orxNULL) { /* Links it */ if(orxFont_SetTexture(_pstFont, pstTexture) != orxSTATUS_FAILURE) { orxVECTOR vCharacterSize, vCharacterSpacing; const orxSTRING zCharacterList; /* Sets its owner */ orxStructure_SetOwner(pstTexture, _pstFont); /* Updates flags */ orxStructure_SetFlags(_pstFont, orxFONT_KU32_FLAG_INTERNAL, orxFONT_KU32_MASK_ALL); /* Gets character list */ zCharacterList = orxConfig_GetString(orxFONT_KZ_CONFIG_CHARACTER_LIST); /* Sets it */ if(orxFont_SetCharacterList(_pstFont, zCharacterList) != orxSTATUS_FAILURE) { orxVECTOR vValue; orxFLOAT *afCharacterWidthList = orxNULL, fCharacterHeight; orxU32 u32CharacterCount; /* Updates result */ eResult = orxSTATUS_SUCCESS; /* Gets character count */ u32CharacterCount = orxString_GetCharacterCount(zCharacterList); /* Has origin / corner? */ if((orxConfig_GetVector(orxFONT_KZ_CONFIG_TEXTURE_ORIGIN, &vValue) != orxNULL) || (orxConfig_GetVector(orxFONT_KZ_CONFIG_TEXTURE_CORNER, &vValue) != orxNULL)) { /* Applies it */ orxFont_SetOrigin(_pstFont, &vValue); /* Updates size */ vValue.fX = orxMAX(orxFLOAT_0, _pstFont->fWidth - vValue.fX); vValue.fY = orxMAX(orxFLOAT_0, _pstFont->fHeight - vValue.fY); orxFont_SetSize(_pstFont, &vValue); } /* Has size? */ if(orxConfig_GetVector(orxFONT_KZ_CONFIG_TEXTURE_SIZE, &vValue) != orxNULL) { /* Applies it */ orxFont_SetSize(_pstFont, &vValue); } /* Gets character spacing */ if(orxConfig_GetVector(orxFONT_KZ_CONFIG_CHARACTER_SPACING, &vCharacterSpacing) != orxNULL) { /* Sets it */ orxFont_SetCharacterSpacing(_pstFont, &vCharacterSpacing); } /* Gets character size */ if(orxConfig_GetVector(orxFONT_KZ_CONFIG_CHARACTER_SIZE, &vCharacterSize) != orxNULL) { orxU32 i; /* Allocates character width list */ afCharacterWidthList = (orxFLOAT *)orxMemory_Allocate(u32CharacterCount * sizeof(orxFLOAT), orxMEMORY_TYPE_MAIN); /* For all characters */ for(i = 0; i < u32CharacterCount; i++) { /* Stores its width */ afCharacterWidthList[i] = vCharacterSize.fX; } /* Stores character height */ fCharacterHeight = vCharacterSize.fY; } else { /* Has valid character height and character width list */ if(((fCharacterHeight = orxConfig_GetFloat(orxFONT_KZ_CONFIG_CHARACTER_HEIGHT)) > orxFLOAT_0) && (orxConfig_GetListCount(orxFONT_KZ_CONFIG_CHARACTER_WIDTH_LIST) == (orxS32)u32CharacterCount)) { orxU32 i; /* Allocates character width list */ afCharacterWidthList = (orxFLOAT *)orxMemory_Allocate(u32CharacterCount * sizeof(orxFLOAT), orxMEMORY_TYPE_MAIN); /* For all characters */ for(i = 0; i < u32CharacterCount; i++) { /* Stores its width */ afCharacterWidthList[i] = orxConfig_GetListFloat(orxFONT_KZ_CONFIG_CHARACTER_WIDTH_LIST, i); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't find character size / height & width list properties for font (%s).", _pstFont->zReference); /* Updates result */ eResult = orxSTATUS_FAILURE; } } /* Valid? */ if(eResult != orxSTATUS_FAILURE) { /* Sets character height & width list */ if((orxFont_SetCharacterHeight(_pstFont, fCharacterHeight) != orxSTATUS_FAILURE) && (orxFont_SetCharacterWidthList(_pstFont, u32CharacterCount, afCharacterWidthList) != orxSTATUS_FAILURE)) { /* Updates status flags */ orxStructure_SetFlags(_pstFont, orxFONT_KU32_FLAG_REFERENCED, orxFONT_KU32_FLAG_NONE); } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Invalid character size (%f, %f) for font (%s).", vCharacterSize.fX, vCharacterSize.fY, _pstFont->zReference); /* Deletes texture */ orxTexture_Delete(pstTexture); /* Updates result */ eResult = orxSTATUS_FAILURE; } } else { /* Deletes texture */ orxTexture_Delete(pstTexture); } /* Has character width list? */ if(afCharacterWidthList != orxNULL) { /* Frees it */ orxMemory_Free(afCharacterWidthList); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Invalid character list (%s) for font (%s).", zCharacterList, _pstFont->zReference); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't link texture (%s) to font (%s).", zName, _pstFont->zReference); /* Deletes texture */ orxTexture_Delete(pstTexture); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't create texture (%s) for font (%s).", zName, _pstFont->zReference); /* Removes texture */ orxFont_SetTexture(_pstFont, orxNULL); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't find texture property for font (%s).", _pstFont->zReference); } /* Pops config section */ orxConfig_PopSection(); } /* Done! */ return eResult; } /** Event handler */ static orxSTATUS orxFASTCALL orxFont_EventHandler(const orxEVENT *_pstEvent) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Add or update? */ if((_pstEvent->eID == orxRESOURCE_EVENT_ADD) || (_pstEvent->eID == orxRESOURCE_EVENT_UPDATE)) { orxRESOURCE_EVENT_PAYLOAD *pstPayload; /* Gets payload */ pstPayload = (orxRESOURCE_EVENT_PAYLOAD *)_pstEvent->pstPayload; /* Is config group? */ if(pstPayload->stGroupID == orxString_Hash(orxCONFIG_KZ_RESOURCE_GROUP)) { orxFONT *pstFont; /* For all fonts */ for(pstFont = orxFONT(orxStructure_GetFirst(orxSTRUCTURE_ID_FONT)); pstFont != orxNULL; pstFont = orxFONT(orxStructure_GetNext(pstFont))) { /* Not default one and has reference? */ if((pstFont != sstFont.pstDefaultFont) && (pstFont->zReference != orxNULL) && (pstFont->zReference != orxSTRING_EMPTY)) { /* Match origin? */ if(orxConfig_GetOriginID(pstFont->zReference) == pstPayload->stNameID) { /* Re-processes its config data */ orxFont_ProcessConfigData(pstFont); } } } } } /* Done! */ return eResult; } /** Deletes all fonts */ static orxINLINE void orxFont_DeleteAll() { orxFONT *pstFont; /* Gets first font */ pstFont = orxFONT(orxStructure_GetFirst(orxSTRUCTURE_ID_FONT)); /* Non empty? */ while(pstFont != orxNULL) { /* Deletes font */ orxFont_Delete(pstFont); /* Gets first font */ pstFont = orxFONT(orxStructure_GetFirst(orxSTRUCTURE_ID_FONT)); } /* Done! */ return; } /*************************************************************************** * Public functions * ***************************************************************************/ /** Setups the font module */ void orxFASTCALL orxFont_Setup() { /* Adds module dependencies */ orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_MEMORY); orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_BANK); orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_CONFIG); orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_EVENT); orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_STRUCTURE); orxModule_AddDependency(orxMODULE_ID_FONT, orxMODULE_ID_TEXTURE); /* Done! */ return; } /** Inits the font module * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_Init() { orxSTATUS eResult = orxSTATUS_FAILURE; /* Not already Initialized? */ if(!(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY)) { /* Cleans static controller */ orxMemory_Zero(&sstFont, sizeof(orxFONT_STATIC)); /* Creates reference table */ sstFont.pstReferenceTable = orxHashTable_Create(orxFONT_KU32_REFERENCE_TABLE_SIZE, orxHASHTABLE_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN); /* Valid? */ if(sstFont.pstReferenceTable != orxNULL) { /* Creates font map bank */ sstFont.pstMapBank = orxBank_Create(orxFONT_KU32_MAP_BANK_SIZE, sizeof(orxCHARACTER_MAP), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN); /* Valid? */ if(sstFont.pstMapBank != orxNULL) { /* Registers structure type */ eResult = orxSTRUCTURE_REGISTER(FONT, orxSTRUCTURE_STORAGE_TYPE_LINKLIST, orxMEMORY_TYPE_MAIN, orxFONT_KU32_BANK_SIZE, orxNULL); } } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Tried to initialize font module when it was already initialized."); /* Already initialized */ eResult = orxSTATUS_SUCCESS; } /* Initialized? */ if(eResult != orxSTATUS_FAILURE) { /* Inits Flags */ sstFont.u32Flags = orxFONT_KU32_STATIC_FLAG_READY; /* Creates default font */ orxFont_CreateDefaultFont(); /* Adds event handler */ orxEvent_AddHandler(orxEVENT_TYPE_RESOURCE, orxFont_EventHandler); orxEvent_SetHandlerIDFlags(orxFont_EventHandler, orxEVENT_TYPE_RESOURCE, orxNULL, orxEVENT_GET_FLAG(orxRESOURCE_EVENT_ADD) | orxEVENT_GET_FLAG(orxRESOURCE_EVENT_UPDATE), orxEVENT_KU32_MASK_ID_ALL); } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Initializing font module failed."); /* Has reference table? */ if(sstFont.pstReferenceTable != orxNULL) { /* Deletes it */ orxHashTable_Delete(sstFont.pstReferenceTable); sstFont.pstReferenceTable = orxNULL; } /* Has map bank? */ if(sstFont.pstMapBank != orxNULL) { /* Deletes it */ orxBank_Delete(sstFont.pstMapBank); sstFont.pstMapBank = orxNULL; } /* Updates Flags */ sstFont.u32Flags &= ~orxFONT_KU32_STATIC_FLAG_READY; } /* Done! */ return eResult; } /** Exits from the font module */ void orxFASTCALL orxFont_Exit() { /* Initialized? */ if(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY) { orxTEXTURE *pstTexture; /* Removes event handler */ orxEvent_RemoveHandler(orxEVENT_TYPE_RESOURCE, orxFont_EventHandler); /* Gets default font texture */ pstTexture = orxFont_GetTexture(sstFont.pstDefaultFont); /* Deletes font list */ orxFont_DeleteAll(); /* Removes texture's owner */ orxStructure_SetOwner(pstTexture, orxNULL); /* Deletes default font texture */ orxTexture_Delete(pstTexture); /* Deletes reference table */ orxHashTable_Delete(sstFont.pstReferenceTable); sstFont.pstReferenceTable = orxNULL; /* Deletes map bank */ orxBank_Delete(sstFont.pstMapBank); sstFont.pstMapBank = orxNULL; /* Unregisters structure type */ orxStructure_Unregister(orxSTRUCTURE_ID_FONT); /* Updates flags */ sstFont.u32Flags &= ~orxFONT_KU32_STATIC_FLAG_READY; } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Tried to exit font module when it wasn't initialized."); } /* Done! */ return; } /** Creates an empty font * @return orxFONT / orxNULL */ orxFONT *orxFASTCALL orxFont_Create() { orxFONT *pstResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); /* Creates font */ pstResult = orxFONT(orxStructure_Create(orxSTRUCTURE_ID_FONT)); /* Created? */ if(pstResult != orxNULL) { /* Allocates its map */ pstResult->pstMap = (orxCHARACTER_MAP *)orxBank_Allocate(sstFont.pstMapBank); /* Valid? */ if(pstResult->pstMap != orxNULL) { /* Creates its character bank */ pstResult->pstMap->pstCharacterBank = orxBank_Create(orxFONT_KU32_CHARACTER_BANK_SIZE, sizeof(orxCHARACTER_GLYPH), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN); /* Valid? */ if(pstResult->pstMap->pstCharacterBank != orxNULL) { /* Creates its character table */ pstResult->pstMap->pstCharacterTable = orxHashTable_Create(orxFONT_KU32_CHARACTER_TABLE_SIZE, orxHASHTABLE_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN); /* Valid? */ if(pstResult->pstMap->pstCharacterTable != orxNULL) { /* Clears its character list */ pstResult->zCharacterList = orxSTRING_EMPTY; /* Increases count */ orxStructure_IncreaseCount(pstResult); } else { /* Deletes character bank */ orxBank_Delete(pstResult->pstMap->pstCharacterBank); /* Deletes maps */ orxBank_Free(sstFont.pstMapBank, pstResult->pstMap); /* Deletes structure */ orxStructure_Delete(pstResult); /* Updates result */ pstResult = orxNULL; /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't allocate font's character table."); } } else { /* Deletes map */ orxBank_Free(sstFont.pstMapBank, pstResult->pstMap); /* Deletes structure */ orxStructure_Delete(pstResult); /* Updates result */ pstResult = orxNULL; /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't allocate font's character bank."); } } else { /* Deletes structure */ orxStructure_Delete(pstResult); /* Updates result */ pstResult = orxNULL; /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't allocate font's map."); } } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Failed to create structure for font."); } return pstResult; } /** Creates a font from config * @param[in] _zConfigID Config ID * @return orxFONT / orxNULL */ orxFONT *orxFASTCALL orxFont_CreateFromConfig(const orxSTRING _zConfigID) { orxFONT *pstResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxASSERT(_zConfigID != orxNULL); /* Search for font */ pstResult = (orxFONT *)orxHashTable_Get(sstFont.pstReferenceTable, orxString_Hash(_zConfigID)); /* Found? */ if(pstResult != orxNULL) { /* Increases count */ orxStructure_IncreaseCount(pstResult); } else { /* Pushes section */ if((orxConfig_HasSection(_zConfigID) != orxFALSE) && (orxConfig_PushSection(_zConfigID) != orxSTATUS_FAILURE)) { /* Creates font */ pstResult = orxFont_Create(); /* Valid? */ if(pstResult != orxNULL) { /* Stores its reference key */ pstResult->zReference = orxConfig_GetCurrentSection(); /* Processes its config data */ if(orxFont_ProcessConfigData(pstResult) != orxSTATUS_FAILURE) { /* Adds it to reference table */ orxHashTable_Add(sstFont.pstReferenceTable, orxString_Hash(pstResult->zReference), pstResult); } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't process config data for font <%s>.", _zConfigID); /* Deletes font */ orxFont_Delete(pstResult); /* Updates result */ pstResult = orxNULL; } } /* Pops previous section */ orxConfig_PopSection(); } else { /* Logs message */ orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't find config section named (%s).", _zConfigID); /* Updates result */ pstResult = orxNULL; } } /* Done! */ return pstResult; } /** Deletes a font * @param[in] _pstFont Concerned font * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_Delete(orxFONT *_pstFont) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Decreases count */ orxStructure_DecreaseCount(_pstFont); /* Not referenced? */ if(orxStructure_GetRefCount(_pstFont) == 0) { /* Removes texture */ orxFont_SetTexture(_pstFont, orxNULL); /* Deletes character table */ orxHashTable_Delete(_pstFont->pstMap->pstCharacterTable); /* Deletes character bank */ orxBank_Delete(_pstFont->pstMap->pstCharacterBank); /* Deletes map */ orxBank_Free(sstFont.pstMapBank, _pstFont->pstMap); /* Is referenced? */ if(orxStructure_TestFlags(_pstFont, orxFONT_KU32_FLAG_REFERENCED) != orxFALSE) { /* Removes it from reference table */ orxHashTable_Remove(sstFont.pstReferenceTable, orxString_Hash(_pstFont->zReference)); } /* Deletes structure */ orxStructure_Delete(_pstFont); } else { /* Referenced by others */ eResult = orxSTATUS_FAILURE; } /* Done! */ return eResult; } /** Gets default font * @return Default font / orxNULL */ const orxFONT *orxFASTCALL orxFont_GetDefaultFont() { orxFONT *pstResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); /* Updates result */ pstResult = sstFont.pstDefaultFont; /* Done ! */ return pstResult; } /** Sets font's texture * @param[in] _pstFont Concerned font * @param[in] _pstTexture Texture to set * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetTexture(orxFONT *_pstFont, orxTEXTURE *_pstTexture) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Had previous texture? */ if(_pstFont->pstTexture != orxNULL) { /* Updates structure reference count */ orxStructure_DecreaseCount(_pstFont->pstTexture); /* Internally handled? */ if(orxStructure_TestFlags(_pstFont, orxFONT_KU32_FLAG_INTERNAL)) { /* Removes its owner */ orxStructure_SetOwner(_pstFont->pstTexture, orxNULL); /* Deletes it */ orxTexture_Delete(_pstFont->pstTexture); /* Updates flags */ orxStructure_SetFlags(_pstFont, orxFONT_KU32_FLAG_NONE, orxFONT_KU32_FLAG_INTERNAL); } /* Cleans reference */ _pstFont->pstTexture = orxNULL; /* Clears origin & size */ _pstFont->fTop = _pstFont->fLeft = _pstFont->fWidth = _pstFont->fHeight = orxFLOAT_0; } /* New texture? */ if(_pstTexture != orxNULL) { /* Stores it */ _pstFont->pstTexture = _pstTexture; /* Updates its reference count */ orxStructure_IncreaseCount(_pstTexture); /* Updates font's size */ orxTexture_GetSize(_pstTexture, &(_pstFont->fWidth), &(_pstFont->fHeight)); } /* Updates font's map */ orxFont_UpdateMap(_pstFont); /* Done! */ return eResult; } /** Sets font's character list * @param[in] _pstFont Concerned font * @param[in] _zList Character list * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetCharacterList(orxFONT *_pstFont, const orxSTRING _zList) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Had a character list? */ if(_pstFont->zCharacterList != orxSTRING_EMPTY) { /* Cleans its reference */ _pstFont->zCharacterList = orxSTRING_EMPTY; } /* Valid? */ if((_zList != orxNULL) && (_zList != orxSTRING_EMPTY)) { /* Stores it */ _pstFont->zCharacterList = orxString_Store(_zList); } else { /* Updates result */ eResult = orxSTATUS_FAILURE; } /* Updates font's map */ orxFont_UpdateMap(_pstFont); /* Done! */ return eResult; } /** Sets font's character height * @param[in] _pstFont Concerned font * @param[in] _fCharacterHeight Character's height * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetCharacterHeight(orxFONT *_pstFont, orxFLOAT _fCharacterHeight) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Stores it */ _pstFont->fCharacterHeight = _fCharacterHeight; /* Done! */ return eResult; } /** Sets font's character width list * @param[in] _pstFont Concerned font * @param[in] _u32CharacterNumber Character's number = * @param[in] _afCharacterWidthList List of widths for all the characters * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetCharacterWidthList(orxFONT *_pstFont, orxU32 _u32CharacterNumber, const orxFLOAT *_afCharacterWidthList) { orxU32 u32CharacterCount; orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_afCharacterWidthList != orxNULL); /* Gets character count */ u32CharacterCount = orxString_GetCharacterCount(_pstFont->zCharacterList); /* Valid? */ if(_u32CharacterNumber == u32CharacterCount) { /* Had a character width list? */ if(_pstFont->afCharacterWidthList != orxNULL) { /* Frees it */ orxMemory_Free(_pstFont->afCharacterWidthList); } /* Allocates character width list */ _pstFont->afCharacterWidthList = (orxFLOAT *)orxMemory_Allocate(u32CharacterCount * sizeof(orxFLOAT), orxMEMORY_TYPE_MAIN); /* Stores values */ orxMemory_Copy(_pstFont->afCharacterWidthList, _afCharacterWidthList, u32CharacterCount * sizeof(orxFLOAT)); /* Updates font's map */ orxFont_UpdateMap(_pstFont); } else { /* Updates result */ eResult = orxSTATUS_FAILURE; } /* Done! */ return eResult; } /** Sets font's character spacing * @param[in] _pstFont Concerned font * @param[in] _pvSpacing Character's spacing * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetCharacterSpacing(orxFONT *_pstFont, const orxVECTOR *_pvSpacing) { orxSTATUS eResult = orxSTATUS_SUCCESS; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvSpacing != orxNULL); /* Valid? */ if((_pvSpacing->fX >= orxFLOAT_0) && (_pvSpacing->fY >= orxFLOAT_0)) { /* Stores it */ orxVector_Set(&(_pstFont->vCharacterSpacing), _pvSpacing->fX, _pvSpacing->fY, orxFLOAT_0); /* Updates font's map */ orxFont_UpdateMap(_pstFont); } else { /* Updates result */ eResult = orxSTATUS_FAILURE; } /* Done! */ return eResult; } /** Sets font's origin * @param[in] _pstFont Concerned font * @param[in] _pvOrigin Font's origin * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetOrigin(orxFONT *_pstFont, const orxVECTOR *_pvOrigin) { orxSTATUS eResult = orxSTATUS_FAILURE; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvOrigin != orxNULL); /* Has texture? */ if(_pstFont->pstTexture) { orxFLOAT fWidth, fHeight; /* Gets its size */ orxTexture_GetSize(_pstFont->pstTexture, &fWidth, &fHeight); /* Valid? */ if((_pvOrigin->fX >= orxFLOAT_0) && (_pvOrigin->fX < fWidth) && (_pvOrigin->fY >= orxFLOAT_0) && (_pvOrigin->fY < fHeight)) { /* Stores it */ _pstFont->fLeft = _pvOrigin->fX; _pstFont->fTop = _pvOrigin->fY; /* Updates font's map */ orxFont_UpdateMap(_pstFont); /* Updates result */ eResult = orxSTATUS_SUCCESS; } } /* Done! */ return eResult; } /** Sets font's size * @param[in] _pstFont Concerned font * @param[in] _pvSize Font's size * @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE */ orxSTATUS orxFASTCALL orxFont_SetSize(orxFONT *_pstFont, const orxVECTOR *_pvSize) { orxSTATUS eResult = orxSTATUS_FAILURE; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvSize != orxNULL); /* Has texture? */ if(_pstFont->pstTexture) { orxFLOAT fWidth, fHeight; /* Gets its size */ orxTexture_GetSize(_pstFont->pstTexture, &fWidth, &fHeight); /* Valid? */ if((_pvSize->fX > orxFLOAT_0) && (_pvSize->fX <= fWidth) && (_pvSize->fY > orxFLOAT_0) && (_pvSize->fY <= fHeight)) { /* Stores it */ _pstFont->fWidth = _pvSize->fX; _pstFont->fHeight = _pvSize->fY; /* Updates font's map */ orxFont_UpdateMap(_pstFont); /* Updates result */ eResult = orxSTATUS_SUCCESS; } } /* Done! */ return eResult; } /** Gets font's texture * @param[in] _pstFont Concerned font * @return Font texture / orxNULL */ orxTEXTURE *orxFASTCALL orxFont_GetTexture(const orxFONT *_pstFont) { orxTEXTURE *pstResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Updates result */ pstResult = _pstFont->pstTexture; /* Done! */ return pstResult; } /** Gets font's character list * @param[in] _pstFont Concerned font * @return Font's character list / orxNULL */ const orxSTRING orxFASTCALL orxFont_GetCharacterList(const orxFONT *_pstFont) { const orxSTRING zResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Updates result */ zResult = _pstFont->zCharacterList; /* Done! */ return zResult; } /** Gets font's character height * @param[in] _pstFont Concerned font * @return orxFLOAT */ orxFLOAT orxFASTCALL orxFont_GetCharacterHeight(const orxFONT *_pstFont) { orxFLOAT fResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Updates result */ fResult = _pstFont->fCharacterHeight; /* Done! */ return fResult; } /** Gets font's character width * @param[in] _pstFont Concerned font * @param[in] _u32CharacterCodePoint Character code point * @return orxFLOAT */ orxFLOAT orxFASTCALL orxFont_GetCharacterWidth(const orxFONT *_pstFont, orxU32 _u32CharacterCodePoint) { orxCHARACTER_GLYPH *pstGlyph; orxFLOAT fResult = orxFLOAT_0; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Has character map? */ if(_pstFont->pstMap != orxNULL) { /* Gets glyph */ pstGlyph = (orxCHARACTER_GLYPH *)orxHashTable_Get(_pstFont->pstMap->pstCharacterTable, _u32CharacterCodePoint); /* Valid? */ if(pstGlyph != orxNULL) { /* Updates result */ fResult = pstGlyph->fWidth; } } /* Done! */ return fResult; } /** Gets font's character spacing * @param[in] _pstFont Concerned font * @param[out] _pvSpacing Character's spacing * @return orxVECTOR / orxNULL */ orxVECTOR *orxFASTCALL orxFont_GetCharacterSpacing(const orxFONT *_pstFont, orxVECTOR *_pvSpacing) { orxVECTOR *pvResult = _pvSpacing; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvSpacing != orxNULL); /* Updates result */ orxVector_Copy(pvResult, &(_pstFont->vCharacterSpacing)); /* Done! */ return pvResult; } /** Gets font's origin * @param[in] _pstFont Concerned font * @param[out] _pvOrigin Font's origin * @return orxVECTOR / orxNULL */ orxVECTOR *orxFASTCALL orxFont_GetOrigin(const orxFONT *_pstFont, orxVECTOR *_pvOrigin) { orxVECTOR *pvResult = _pvOrigin; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvOrigin != orxNULL); /* Updates result */ orxVector_Set(pvResult, _pstFont->fLeft, _pstFont->fTop, orxFLOAT_0); /* Done! */ return pvResult; } /** Gets font's size * @param[in] _pstFont Concerned font * @param[out] _pvSize Font's size * @return orxVECTOR / orxNULL */ orxVECTOR *orxFASTCALL orxFont_GetSize(const orxFONT *_pstFont, orxVECTOR *_pvSize) { orxVECTOR *pvResult = _pvSize; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); orxASSERT(_pvSize != orxNULL); /* Updates result */ orxVector_Set(pvResult, _pstFont->fWidth, _pstFont->fHeight, orxFLOAT_0); /* Done! */ return pvResult; } /** Gets font's map * @param[in] _pstFont Concerned font * @return orxCHARACTER_MAP / orxNULL */ const orxCHARACTER_MAP *orxFASTCALL orxFont_GetMap(const orxFONT *_pstFont) { const orxCHARACTER_MAP *pstResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Updates result */ pstResult = _pstFont->pstMap; /* Done! */ return pstResult; } /** Gets font name * @param[in] _pstFont Concerned font * @return Font name / orxSTRING_EMPTY */ const orxSTRING orxFASTCALL orxFont_GetName(const orxFONT *_pstFont) { const orxSTRING zResult; /* Checks */ orxASSERT(sstFont.u32Flags & orxFONT_KU32_STATIC_FLAG_READY); orxSTRUCTURE_ASSERT(_pstFont); /* Updates result */ zResult = (_pstFont->zReference != orxNULL) ? _pstFont->zReference : orxSTRING_EMPTY; /* Done! */ return zResult; }
ae8435919a72e1d22ba850445d47fed0a4af94f9
a212573b7e2de18939686746cb405ea228a25f1b
/tests/mypaint-benchmark.c
89278437749fc39b72eaa32e7fdc179a201e59e0
[ "ISC" ]
permissive
mypaint/libmypaint
0878b446455eb8773ea708e646dff97cf5afbcb9
826069db12843b5b3ddbc8ad1690453c9a36e19e
refs/heads/master
2023-06-23T07:10:42.234308
2021-04-16T13:40:11
2021-04-17T14:27:41
20,728,367
305
112
NOASSERTION
2023-06-14T18:41:00
2014-06-11T14:31:54
C
UTF-8
C
false
false
2,444
c
mypaint-benchmark.c
/* libmypaint - The MyPaint Brush Library * Copyright (C) 2012 Jon Nordby <jononor@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "mypaint-benchmark.h" #if MYPAINT_CONFIG_USE_GLIB #include <glib.h> #else // not MYPAINT_CONFIG_USE_GLIB #include "mypaint-glib-compat.h" #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #ifdef HAVE_GPERFTOOLS #include <gperftools/profiler.h> #endif #ifdef _WIN32 #include <windows.h> double get_time(void) { LARGE_INTEGER t, f; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&f); return (double)t.QuadPart/(double)f.QuadPart; } #else #include <sys/time.h> #include <sys/resource.h> double get_time(void) { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec + t.tv_usec*1e-6; } #endif static double g_start_time = 0.0; gboolean profiling_enabled(void) { char * enabled = getenv("MYPAINT_ENABLE_PROFILING"); if (enabled != NULL && strcmp(enabled, "1") == 0) { return TRUE; } return FALSE; } void mypaint_benchmark_start(const char *name) { if (profiling_enabled()) { #ifdef HAVE_GPERFTOOLS ProfilerStart(name); #else fprintf(stderr, "Warning: Not built with gperftools support.\n"); #endif } g_start_time = get_time(); } /** * returns number of milliseconds spent since _start() */ int mypaint_benchmark_end(void) { double time_spent = get_time() - g_start_time; g_start_time = 0.0; if (profiling_enabled()) { #ifdef HAVE_GPERFTOOLS ProfilerStop(); #else fprintf(stderr, "Warning: Not built with gperftools support.\n"); #endif } assert(time_spent*1000 < INT_MAX); return (int)(time_spent*1000); }
bf2125b1d2dbb112f3d09e810307436078490a22
060c02561085a494df306deb2f3a8fddb984c73a
/inc/car-cdrdefs.h
584f802e1e577ddd8eb07a3f3845e357ecc845f1
[ "MIT" ]
permissive
Interlisp/maiko
48631ae6abc9d98d5c3eeb5f5eb736adf400ea8f
7fce08f92c221bcb98e5f6d560aa50cb942e95b3
refs/heads/master
2023-09-03T12:23:43.081470
2023-08-09T21:04:51
2023-08-09T21:04:51
279,184,900
110
33
MIT
2023-09-13T14:49:28
2020-07-13T02:00:09
C
UTF-8
C
false
false
495
h
car-cdrdefs.h
#ifndef CAR_CDRDEFS_H #define CAR_CDRDEFS_H 1 #include "cell.h" /* for ConsCell */ #include "lispemul.h" /* for LispPTR */ LispPTR car(LispPTR datum); LispPTR cdr(LispPTR datum); LispPTR rplaca(LispPTR x, LispPTR y); LispPTR rplacd(LispPTR x, LispPTR y); LispPTR N_OP_car(LispPTR tos); LispPTR N_OP_cdr(LispPTR tos); LispPTR N_OP_rplaca(LispPTR tosm1, LispPTR tos); LispPTR N_OP_rplacd(LispPTR tosm1, LispPTR tos); ConsCell *find_close_prior_cell(struct conspage *page, LispPTR oldcell); #endif
81f4acdc2ee2668a80c3eeaefe008a161548d0fd
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/grpc/src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/secret.upb.h
9937d7b8894f4ebfcfe83e202de0b12c6caf9ec0
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
22,660
h
secret.upb.h
/* This file was generated by upbc (the upb compiler) from the input * file: * * envoy/extensions/transport_sockets/tls/v3/secret.proto * * Do not edit -- your changes will be discarded when the file is * regenerated. */ #ifndef ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_SECRET_PROTO_UPB_H_ #define ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_SECRET_PROTO_UPB_H_ #include "upb/msg_internal.h" #include "upb/decode.h" #include "upb/decode_fast.h" #include "upb/encode.h" #include "upb/port_def.inc" #ifdef __cplusplus extern "C" { #endif struct envoy_extensions_transport_sockets_tls_v3_GenericSecret; struct envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig; struct envoy_extensions_transport_sockets_tls_v3_Secret; typedef struct envoy_extensions_transport_sockets_tls_v3_GenericSecret envoy_extensions_transport_sockets_tls_v3_GenericSecret; typedef struct envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig; typedef struct envoy_extensions_transport_sockets_tls_v3_Secret envoy_extensions_transport_sockets_tls_v3_Secret; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_Secret_msginit; struct envoy_config_core_v3_ConfigSource; struct envoy_config_core_v3_DataSource; struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext; struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate; struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys; extern const upb_MiniTable envoy_config_core_v3_ConfigSource_msginit; extern const upb_MiniTable envoy_config_core_v3_DataSource_msginit; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext_msginit; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_TlsCertificate_msginit; extern const upb_MiniTable envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys_msginit; /* envoy.extensions.transport_sockets.tls.v3.GenericSecret */ UPB_INLINE envoy_extensions_transport_sockets_tls_v3_GenericSecret* envoy_extensions_transport_sockets_tls_v3_GenericSecret_new(upb_Arena* arena) { return (envoy_extensions_transport_sockets_tls_v3_GenericSecret*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, arena); } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_GenericSecret* envoy_extensions_transport_sockets_tls_v3_GenericSecret_parse(const char* buf, size_t size, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_GenericSecret* ret = envoy_extensions_transport_sockets_tls_v3_GenericSecret_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_GenericSecret* envoy_extensions_transport_sockets_tls_v3_GenericSecret_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_GenericSecret* ret = envoy_extensions_transport_sockets_tls_v3_GenericSecret_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_GenericSecret_serialize(const envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, 0, arena, &ptr, len); return ptr; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_GenericSecret_serialize_ex(const envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg, int options, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, options, arena, &ptr, len); return ptr; } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_GenericSecret_has_secret(const envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg) { return _upb_hasbit(msg, 1); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_GenericSecret_clear_secret(const envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const upb_Message*) = NULL; } UPB_INLINE const struct envoy_config_core_v3_DataSource* envoy_extensions_transport_sockets_tls_v3_GenericSecret_secret(const envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const struct envoy_config_core_v3_DataSource*); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_GenericSecret_set_secret(envoy_extensions_transport_sockets_tls_v3_GenericSecret *msg, struct envoy_config_core_v3_DataSource* value) { _upb_sethas(msg, 1); *UPB_PTR_AT(msg, UPB_SIZE(4, 8), struct envoy_config_core_v3_DataSource*) = value; } UPB_INLINE struct envoy_config_core_v3_DataSource* envoy_extensions_transport_sockets_tls_v3_GenericSecret_mutable_secret(envoy_extensions_transport_sockets_tls_v3_GenericSecret* msg, upb_Arena* arena) { struct envoy_config_core_v3_DataSource* sub = (struct envoy_config_core_v3_DataSource*)envoy_extensions_transport_sockets_tls_v3_GenericSecret_secret(msg); if (sub == NULL) { sub = (struct envoy_config_core_v3_DataSource*)_upb_Message_New(&envoy_config_core_v3_DataSource_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_GenericSecret_set_secret(msg, sub); } return sub; } /* envoy.extensions.transport_sockets.tls.v3.SdsSecretConfig */ UPB_INLINE envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_new(upb_Arena* arena) { return (envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit, arena); } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_parse(const char* buf, size_t size, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* ret = envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* ret = envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_serialize(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit, 0, arena, &ptr, len); return ptr; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_serialize_ex(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg, int options, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_msginit, options, arena, &ptr, len); return ptr; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_clear_name(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0); } UPB_INLINE upb_StringView envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_name(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView); } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_has_sds_config(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg) { return _upb_hasbit(msg, 1); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_clear_sds_config(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg) { *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const upb_Message*) = NULL; } UPB_INLINE const struct envoy_config_core_v3_ConfigSource* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_sds_config(const envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const struct envoy_config_core_v3_ConfigSource*); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_set_name(envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig *msg, upb_StringView value) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView) = value; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_set_sds_config(envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig *msg, struct envoy_config_core_v3_ConfigSource* value) { _upb_sethas(msg, 1); *UPB_PTR_AT(msg, UPB_SIZE(12, 24), struct envoy_config_core_v3_ConfigSource*) = value; } UPB_INLINE struct envoy_config_core_v3_ConfigSource* envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_mutable_sds_config(envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig* msg, upb_Arena* arena) { struct envoy_config_core_v3_ConfigSource* sub = (struct envoy_config_core_v3_ConfigSource*)envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_sds_config(msg); if (sub == NULL) { sub = (struct envoy_config_core_v3_ConfigSource*)_upb_Message_New(&envoy_config_core_v3_ConfigSource_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_SdsSecretConfig_set_sds_config(msg, sub); } return sub; } /* envoy.extensions.transport_sockets.tls.v3.Secret */ UPB_INLINE envoy_extensions_transport_sockets_tls_v3_Secret* envoy_extensions_transport_sockets_tls_v3_Secret_new(upb_Arena* arena) { return (envoy_extensions_transport_sockets_tls_v3_Secret*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_Secret_msginit, arena); } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_Secret* envoy_extensions_transport_sockets_tls_v3_Secret_parse(const char* buf, size_t size, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_Secret* ret = envoy_extensions_transport_sockets_tls_v3_Secret_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_Secret_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE envoy_extensions_transport_sockets_tls_v3_Secret* envoy_extensions_transport_sockets_tls_v3_Secret_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { envoy_extensions_transport_sockets_tls_v3_Secret* ret = envoy_extensions_transport_sockets_tls_v3_Secret_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_extensions_transport_sockets_tls_v3_Secret_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_Secret_serialize(const envoy_extensions_transport_sockets_tls_v3_Secret* msg, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_Secret_msginit, 0, arena, &ptr, len); return ptr; } UPB_INLINE char* envoy_extensions_transport_sockets_tls_v3_Secret_serialize_ex(const envoy_extensions_transport_sockets_tls_v3_Secret* msg, int options, upb_Arena* arena, size_t* len) { char* ptr; (void)upb_Encode(msg, &envoy_extensions_transport_sockets_tls_v3_Secret_msginit, options, arena, &ptr, len); return ptr; } typedef enum { envoy_extensions_transport_sockets_tls_v3_Secret_type_tls_certificate = 2, envoy_extensions_transport_sockets_tls_v3_Secret_type_session_ticket_keys = 3, envoy_extensions_transport_sockets_tls_v3_Secret_type_validation_context = 4, envoy_extensions_transport_sockets_tls_v3_Secret_type_generic_secret = 5, envoy_extensions_transport_sockets_tls_v3_Secret_type_NOT_SET = 0 } envoy_extensions_transport_sockets_tls_v3_Secret_type_oneofcases; UPB_INLINE envoy_extensions_transport_sockets_tls_v3_Secret_type_oneofcases envoy_extensions_transport_sockets_tls_v3_Secret_type_case(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return (envoy_extensions_transport_sockets_tls_v3_Secret_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_clear_name(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0); } UPB_INLINE upb_StringView envoy_extensions_transport_sockets_tls_v3_Secret_name(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView); } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_Secret_has_tls_certificate(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return _upb_getoneofcase(msg, UPB_SIZE(0, 0)) == 2; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_clear_tls_certificate(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate*, UPB_SIZE(12, 24), 0, UPB_SIZE(0, 0), envoy_extensions_transport_sockets_tls_v3_Secret_type_NOT_SET); } UPB_INLINE const struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate* envoy_extensions_transport_sockets_tls_v3_Secret_tls_certificate(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return UPB_READ_ONEOF(msg, const struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate*, UPB_SIZE(12, 24), UPB_SIZE(0, 0), 2, NULL); } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_Secret_has_session_ticket_keys(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return _upb_getoneofcase(msg, UPB_SIZE(0, 0)) == 3; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_clear_session_ticket_keys(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys*, UPB_SIZE(12, 24), 0, UPB_SIZE(0, 0), envoy_extensions_transport_sockets_tls_v3_Secret_type_NOT_SET); } UPB_INLINE const struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys* envoy_extensions_transport_sockets_tls_v3_Secret_session_ticket_keys(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return UPB_READ_ONEOF(msg, const struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys*, UPB_SIZE(12, 24), UPB_SIZE(0, 0), 3, NULL); } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_Secret_has_validation_context(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return _upb_getoneofcase(msg, UPB_SIZE(0, 0)) == 4; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_clear_validation_context(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext*, UPB_SIZE(12, 24), 0, UPB_SIZE(0, 0), envoy_extensions_transport_sockets_tls_v3_Secret_type_NOT_SET); } UPB_INLINE const struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext* envoy_extensions_transport_sockets_tls_v3_Secret_validation_context(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return UPB_READ_ONEOF(msg, const struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext*, UPB_SIZE(12, 24), UPB_SIZE(0, 0), 4, NULL); } UPB_INLINE bool envoy_extensions_transport_sockets_tls_v3_Secret_has_generic_secret(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return _upb_getoneofcase(msg, UPB_SIZE(0, 0)) == 5; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_clear_generic_secret(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { UPB_WRITE_ONEOF(msg, envoy_extensions_transport_sockets_tls_v3_GenericSecret*, UPB_SIZE(12, 24), 0, UPB_SIZE(0, 0), envoy_extensions_transport_sockets_tls_v3_Secret_type_NOT_SET); } UPB_INLINE const envoy_extensions_transport_sockets_tls_v3_GenericSecret* envoy_extensions_transport_sockets_tls_v3_Secret_generic_secret(const envoy_extensions_transport_sockets_tls_v3_Secret* msg) { return UPB_READ_ONEOF(msg, const envoy_extensions_transport_sockets_tls_v3_GenericSecret*, UPB_SIZE(12, 24), UPB_SIZE(0, 0), 5, NULL); } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_set_name(envoy_extensions_transport_sockets_tls_v3_Secret *msg, upb_StringView value) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_StringView) = value; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_set_tls_certificate(envoy_extensions_transport_sockets_tls_v3_Secret *msg, struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate* value) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate*, UPB_SIZE(12, 24), value, UPB_SIZE(0, 0), 2); } UPB_INLINE struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate* envoy_extensions_transport_sockets_tls_v3_Secret_mutable_tls_certificate(envoy_extensions_transport_sockets_tls_v3_Secret* msg, upb_Arena* arena) { struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate* sub = (struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate*)envoy_extensions_transport_sockets_tls_v3_Secret_tls_certificate(msg); if (sub == NULL) { sub = (struct envoy_extensions_transport_sockets_tls_v3_TlsCertificate*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_TlsCertificate_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_Secret_set_tls_certificate(msg, sub); } return sub; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_set_session_ticket_keys(envoy_extensions_transport_sockets_tls_v3_Secret *msg, struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys* value) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys*, UPB_SIZE(12, 24), value, UPB_SIZE(0, 0), 3); } UPB_INLINE struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys* envoy_extensions_transport_sockets_tls_v3_Secret_mutable_session_ticket_keys(envoy_extensions_transport_sockets_tls_v3_Secret* msg, upb_Arena* arena) { struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys* sub = (struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys*)envoy_extensions_transport_sockets_tls_v3_Secret_session_ticket_keys(msg); if (sub == NULL) { sub = (struct envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_Secret_set_session_ticket_keys(msg, sub); } return sub; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_set_validation_context(envoy_extensions_transport_sockets_tls_v3_Secret *msg, struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext* value) { UPB_WRITE_ONEOF(msg, struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext*, UPB_SIZE(12, 24), value, UPB_SIZE(0, 0), 4); } UPB_INLINE struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext* envoy_extensions_transport_sockets_tls_v3_Secret_mutable_validation_context(envoy_extensions_transport_sockets_tls_v3_Secret* msg, upb_Arena* arena) { struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext* sub = (struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext*)envoy_extensions_transport_sockets_tls_v3_Secret_validation_context(msg); if (sub == NULL) { sub = (struct envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_Secret_set_validation_context(msg, sub); } return sub; } UPB_INLINE void envoy_extensions_transport_sockets_tls_v3_Secret_set_generic_secret(envoy_extensions_transport_sockets_tls_v3_Secret *msg, envoy_extensions_transport_sockets_tls_v3_GenericSecret* value) { UPB_WRITE_ONEOF(msg, envoy_extensions_transport_sockets_tls_v3_GenericSecret*, UPB_SIZE(12, 24), value, UPB_SIZE(0, 0), 5); } UPB_INLINE struct envoy_extensions_transport_sockets_tls_v3_GenericSecret* envoy_extensions_transport_sockets_tls_v3_Secret_mutable_generic_secret(envoy_extensions_transport_sockets_tls_v3_Secret* msg, upb_Arena* arena) { struct envoy_extensions_transport_sockets_tls_v3_GenericSecret* sub = (struct envoy_extensions_transport_sockets_tls_v3_GenericSecret*)envoy_extensions_transport_sockets_tls_v3_Secret_generic_secret(msg); if (sub == NULL) { sub = (struct envoy_extensions_transport_sockets_tls_v3_GenericSecret*)_upb_Message_New(&envoy_extensions_transport_sockets_tls_v3_GenericSecret_msginit, arena); if (!sub) return NULL; envoy_extensions_transport_sockets_tls_v3_Secret_set_generic_secret(msg, sub); } return sub; } extern const upb_MiniTable_File envoy_extensions_transport_sockets_tls_v3_secret_proto_upb_file_layout; #ifdef __cplusplus } /* extern "C" */ #endif #include "upb/port_undef.inc" #endif /* ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_SECRET_PROTO_UPB_H_ */
1f2545cdfa676d82ae1d0b6b4384ede0f4a87f5c
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/plugins/unittest/crypto/rfc4231.c
127e1bfe521b300ac2596bec9c33326c5d09cab4
[ "Apache-2.0" ]
permissive
FDio/vpp
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
f234b0d4626d7e686422cc9dfd25958584f4931e
refs/heads/master
2023-08-31T16:09:04.068646
2022-03-14T09:49:15
2023-08-31T09:50:00
96,556,718
1,048
630
Apache-2.0
2023-06-21T05:39:17
2017-07-07T16:29:40
C
UTF-8
C
false
false
19,546
c
rfc4231.c
/* * Copyright (c) 2019 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Test vectors published in RFC4231 */ #include <vppinfra/clib.h> #include <vnet/crypto/crypto.h> #include <unittest/crypto/crypto.h> static u8 tc1_key[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; static char tc1_data[8] = "Hi There"; static u8 tc1_digest_sha224[] = { 0x89, 0x6f, 0xb1, 0x12, 0x8a, 0xbb, 0xdf, 0x19, 0x68, 0x32, 0x10, 0x7c, 0xd4, 0x9d, 0xf3, 0x3f, 0x47, 0xb4, 0xb1, 0x16, 0x99, 0x12, 0xba, 0x4f, 0x53, 0x68, 0x4b, 0x22 }; static u8 tc1_digest_sha256[] = { 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7, }; static u8 tc1_digest_sha384[] = { 0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4, 0xab, 0x46, 0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6, 0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9, 0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6 }; static u8 tc1_digest_sha512[] = { 0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a, 0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0, 0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7, 0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e, 0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54 }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc1_sha224) = { .name = "RFC4231 TC1", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc1_key), .plaintext = TEST_DATA (tc1_data), .digest = TEST_DATA (tc1_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc1_sha256) = { .name = "RFC4231 TC1", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc1_key), .plaintext = TEST_DATA (tc1_data), .digest = TEST_DATA (tc1_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc1_sha384) = { .name = "RFC4231 TC1", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc1_key), .plaintext = TEST_DATA (tc1_data), .digest = TEST_DATA (tc1_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc1_sha512) = { .name = "RFC4231 TC1", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc1_key), .plaintext = TEST_DATA (tc1_data), .digest = TEST_DATA (tc1_digest_sha512), }; /* *INDENT-ON* */ static char tc2_key[4] = "Jefe"; static char tc2_data[28] = "what do ya want for nothing?"; static u8 tc2_digest_sha224[] = { 0xa3, 0x0e, 0x01, 0x09, 0x8b, 0xc6, 0xdb, 0xbf, 0x45, 0x69, 0x0f, 0x3a, 0x7e, 0x9e, 0x6d, 0x0f, 0x8b, 0xbe, 0xa2, 0xa3, 0x9e, 0x61, 0x48, 0x00, 0x8f, 0xd0, 0x5e, 0x44 }; static u8 tc2_digest_sha256[] = { 0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43, }; static u8 tc2_digest_sha384[] = { 0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2, 0xb5, 0x8a, 0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47, 0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca, 0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49, }; static u8 tc2_digest_sha512[] = { 0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b, 0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27, 0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99, 0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3, 0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37, }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc2_sha224) = { .name = "RFC4231 TC2", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc2_key), .plaintext = TEST_DATA (tc2_data), .digest = TEST_DATA (tc2_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc2_sha256) = { .name = "RFC4231 TC2", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc2_key), .plaintext = TEST_DATA (tc2_data), .digest = TEST_DATA (tc2_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc2_sha384) = { .name = "RFC4231 TC2", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc2_key), .plaintext = TEST_DATA (tc2_data), .digest = TEST_DATA (tc2_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc2_sha512) = { .name = "RFC4231 TC2", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc2_key), .plaintext = TEST_DATA (tc2_data), .digest = TEST_DATA (tc2_digest_sha512), }; /* *INDENT-ON* */ static u8 tc3_key[20] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; static u8 tc3_data[50] = { 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, }; static u8 tc3_digest_sha224[] = { 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a, 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea }; static u8 tc3_digest_sha256[] = { 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe }; static u8 tc3_digest_sha384[] = { 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0, 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb, 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d, 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27 }; static u8 tc3_digest_sha512[] = { 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c, 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8, 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22, 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37, 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc3_sha224) = { .name = "RFC4231 TC3", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc3_key), .plaintext = TEST_DATA (tc3_data), .digest = TEST_DATA (tc3_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc3_sha256) = { .name = "RFC4231 TC3", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc3_key), .plaintext = TEST_DATA (tc3_data), .digest = TEST_DATA (tc3_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc3_sha384) = { .name = "RFC4231 TC3", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc3_key), .plaintext = TEST_DATA (tc3_data), .digest = TEST_DATA (tc3_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc3_sha512) = { .name = "RFC4231 TC3", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc3_key), .plaintext = TEST_DATA (tc3_data), .digest = TEST_DATA (tc3_digest_sha512), }; /* *INDENT-ON* */ static u8 tc4_key[25] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19 }; static u8 tc4_data[50] = { 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd }; static u8 tc4_digest_sha224[] = { 0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82, 0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a }; static u8 tc4_digest_sha256[] = { 0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b }; static u8 tc4_digest_sha384[] = { 0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62, 0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c, 0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23, 0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb }; static u8 tc4_digest_sha512[] = { 0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6, 0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f, 0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e, 0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41, 0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc4_sha224) = { .name = "RFC4231 TC4", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc4_key), .plaintext = TEST_DATA (tc4_data), .digest = TEST_DATA (tc4_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc4_sha256) = { .name = "RFC4231 TC4", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc4_key), .plaintext = TEST_DATA (tc4_data), .digest = TEST_DATA (tc4_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc4_sha384) = { .name = "RFC4231 TC4", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc4_key), .plaintext = TEST_DATA (tc4_data), .digest = TEST_DATA (tc4_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc4_sha512) = { .name = "RFC4231 TC4", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc4_key), .plaintext = TEST_DATA (tc4_data), .digest = TEST_DATA (tc4_digest_sha512), }; /* *INDENT-ON* */ static u8 tc5_key[20] = { 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }; static u8 tc5_data[] = { 0x54, 0x65, 0x73, 0x74, 0x20, 0x57, 0x69, 0x74, 0x68, 0x20, 0x54, 0x72, 0x75, 0x6e, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e }; static u8 tc5_digest_sha224[16] = { 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37, 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8 }; static u8 tc5_digest_sha256[16] = { 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0, 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b }; static u8 tc5_digest_sha384[16] = { 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23, 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97 }; static u8 tc5_digest_sha512[16] = { 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53, 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6 }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc5_sha224) = { .name = "RFC4231 TC5", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc5_key), .plaintext = TEST_DATA (tc5_data), .digest = TEST_DATA (tc5_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc5_sha256) = { .name = "RFC4231 TC5", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc5_key), .plaintext = TEST_DATA (tc5_data), .digest = TEST_DATA (tc5_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc5_sha384) = { .name = "RFC4231 TC5", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc5_key), .plaintext = TEST_DATA (tc5_data), .digest = TEST_DATA (tc5_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc5_sha512) = { .name = "RFC4231 TC5", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc5_key), .plaintext = TEST_DATA (tc5_data), .digest = TEST_DATA (tc5_digest_sha512), }; /* *INDENT-ON* */ static u8 tc6_key[131] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; static char tc6_data[54] = "Test Using Larger Than Block-Size Key - Hash Key First"; static u8 tc6_digest_sha224[] = { 0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d, 0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e }; static u8 tc6_digest_sha256[] = { 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54 }; static u8 tc6_digest_sha384[] = { 0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a, 0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f, 0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab, 0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52 }; static u8 tc6_digest_sha512[] = { 0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd, 0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b, 0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25, 0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73, 0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98 }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc6_sha224) = { .name = "RFC4231 TC6", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc6_key), .plaintext = TEST_DATA (tc6_data), .digest = TEST_DATA (tc6_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc6_sha256) = { .name = "RFC4231 TC6", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc6_key), .plaintext = TEST_DATA (tc6_data), .digest = TEST_DATA (tc6_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc6_sha384) = { .name = "RFC4231 TC6", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc6_key), .plaintext = TEST_DATA (tc6_data), .digest = TEST_DATA (tc6_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc6_sha512) = { .name = "RFC4231 TC6", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc6_key), .plaintext = TEST_DATA (tc6_data), .digest = TEST_DATA (tc6_digest_sha512), }; /* *INDENT-ON* */ static u8 tc7_key[131] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; static char tc7_data[152] = "This is a test using a larger than block-size key and a larger than " "block-size data. The key needs to be hashed before being used by the " "HMAC algorithm."; static u8 tc7_digest_sha224[] = { 0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3, 0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1 }; static u8 tc7_digest_sha256[] = { 0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2 }; static u8 tc7_digest_sha384[] = { 0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25, 0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a, 0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31, 0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e }; static u8 tc7_digest_sha512[] = { 0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e, 0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5, 0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82, 0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb, 0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58 }; /* *INDENT-OFF* */ UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc7_sha224) = { .name = "RFC4231 TC7", .alg = VNET_CRYPTO_ALG_HMAC_SHA224, .key = TEST_DATA (tc7_key), .plaintext = TEST_DATA (tc7_data), .digest = TEST_DATA (tc7_digest_sha224), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc7_sha256) = { .name = "RFC4231 TC7", .alg = VNET_CRYPTO_ALG_HMAC_SHA256, .key = TEST_DATA (tc7_key), .plaintext = TEST_DATA (tc7_data), .digest = TEST_DATA (tc7_digest_sha256), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc7_sha384) = { .name = "RFC4231 TC7", .alg = VNET_CRYPTO_ALG_HMAC_SHA384, .key = TEST_DATA (tc7_key), .plaintext = TEST_DATA (tc7_data), .digest = TEST_DATA (tc7_digest_sha384), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc7_sha512) = { .name = "RFC4231 TC7", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc7_key), .plaintext = TEST_DATA (tc7_data), .digest = TEST_DATA (tc7_digest_sha512), }; UNITTEST_REGISTER_CRYPTO_TEST (rfc4231_tc7_sha512_chain) = { .name = "RFC4231 TC7 [chained]", .alg = VNET_CRYPTO_ALG_HMAC_SHA512, .key = TEST_DATA (tc7_key), .digest = TEST_DATA (tc7_digest_sha512), .is_chained = 1, .pt_chunks = { TEST_DATA_CHUNK (tc7_data, 0, 50), TEST_DATA_CHUNK (tc7_data, 50, 50), TEST_DATA_CHUNK (tc7_data, 100, 50), TEST_DATA_CHUNK (tc7_data, 150, 2), }, }; /* *INDENT-ON* */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
25b614ce2a57c83288172197a488dd557062c06c
dcbef06d5a00f07756339b9e62c684dec2fee425
/nuitka/build/static_src/HelpersOperationBinaryTruediv.c
d3ec97f6bcfe2ff60a0dae626374ea1cebaf5186
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Nuitka/Nuitka
f9543d8d95bfa0b81d4e60af0dfad99fb72893a4
d87faf2f7e1d6ed9bfe4cf8c1d648f34307e33f2
refs/heads/develop
2023-08-28T14:00:32.861328
2023-08-27T09:16:45
2023-08-27T09:16:45
9,626,741
8,573
599
Apache-2.0
2023-09-13T02:49:41
2013-04-23T15:40:33
Python
UTF-8
C
false
false
68,005
c
HelpersOperationBinaryTruediv.c
// Copyright 2023, Kay Hayen, mailto:kay.hayen@gmail.com // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // 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. // /* WARNING, this code is GENERATED. Modify the template HelperOperationBinary.c.j2 instead! */ /* This file is included from another C file, help IDEs to still parse it on its own. */ #ifdef __IDE_ONLY__ #include "nuitka/prelude.h" #endif /* C helpers for type specialized "/" (TRUEDIV) operations */ #if PYTHON_VERSION < 0x300 /* Code referring to "INT" corresponds to Python2 'int' and "INT" to Python2 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_INT_INT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); PyObject *result; // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); const long a = PyInt_AS_LONG(operand1); const long b = PyInt_AS_LONG(operand2); if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = operand1; PyObject *operand2_object = operand2; PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_INT_INT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_INT(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "OBJECT" corresponds to any Python object and "INT" to Python2 'int'. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_INT(PyObject *operand1, PyObject *operand2) { PyTypeObject *type1 = Py_TYPE(operand1); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_true_divide : NULL; binaryfunc slot2 = NULL; if (!(type1 == &PyInt_Type)) { // Different types, need to consider second value slot. slot2 = PyInt_Type.tp_as_number->nb_true_divide; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!NEW_STYLE_NUMBER_TYPE(type1) || !1) { coercion c1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_coerce : NULL; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = PyInt_Type.tp_as_number->nb_coerce; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and 'int'", type1->tp_name); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_INT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); PyTypeObject *type1 = Py_TYPE(operand1); if (type1 == &PyInt_Type) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_INT(operand1, operand2); // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); const long a = PyInt_AS_LONG(operand1); const long b = PyInt_AS_LONG(operand2); if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = operand1; PyObject *operand2_object = operand2; PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_INT(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_INT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_INT(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "INT" corresponds to Python2 'int' and "OBJECT" to any Python object. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_INT_OBJECT(PyObject *operand1, PyObject *operand2) { PyTypeObject *type2 = Py_TYPE(operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyInt_Type.tp_as_number->nb_true_divide; binaryfunc slot2 = NULL; if (!(&PyInt_Type == type2)) { // Different types, need to consider second value slot. slot2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_true_divide : NULL; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { if (slot2 != NULL) { if (Nuitka_Type_IsSubtype(type2, &PyInt_Type)) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); slot2 = NULL; } } PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!1 || !NEW_STYLE_NUMBER_TYPE(type2)) { coercion c1 = PyInt_Type.tp_as_number->nb_coerce; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_coerce : NULL; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'int' and '%s'", type2->tp_name); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_INT_OBJECT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); PyTypeObject *type2 = Py_TYPE(operand2); if (&PyInt_Type == type2) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_INT(operand1, operand2); // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); const long a = PyInt_AS_LONG(operand1); const long b = PyInt_AS_LONG(operand2); if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = operand1; PyObject *operand2_object = operand2; PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_INT_OBJECT(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_INT_OBJECT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_OBJECT(operand1, operand2); } #endif /* Code referring to "LONG" corresponds to Python2 'long', Python3 'int' and "LONG" to Python2 'long', Python3 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_LONG_LONG(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyLong_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyLong_CheckExact(operand2)); PyObject *result; // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; #ifdef _MSC_VER #pragma warning(pop) #endif PyObject *x = PyLong_Type.tp_as_number->nb_true_divide(operand1, operand2); assert(x != Py_NotImplemented); obj_result = x; goto exit_result_object; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_LONG_LONG(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_LONG(operand1, operand2); } /* Code referring to "OBJECT" corresponds to any Python object and "LONG" to Python2 'long', Python3 'int'. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_LONG(PyObject *operand1, PyObject *operand2) { PyTypeObject *type1 = Py_TYPE(operand1); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_true_divide : NULL; binaryfunc slot2 = NULL; if (!(type1 == &PyLong_Type)) { // Different types, need to consider second value slot. slot2 = PyLong_Type.tp_as_number->nb_true_divide; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!NEW_STYLE_NUMBER_TYPE(type1) || !1) { coercion c1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_coerce : NULL; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = PyLong_Type.tp_as_number->nb_coerce; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif #if PYTHON_VERSION < 0x300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and 'long'", type1->tp_name); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and 'int'", type1->tp_name); #endif goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_LONG(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); CHECK_OBJECT(operand2); assert(PyLong_CheckExact(operand2)); PyTypeObject *type1 = Py_TYPE(operand1); if (type1 == &PyLong_Type) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_LONG(operand1, operand2); // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; #ifdef _MSC_VER #pragma warning(pop) #endif PyObject *x = PyLong_Type.tp_as_number->nb_true_divide(operand1, operand2); assert(x != Py_NotImplemented); obj_result = x; goto exit_result_object; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_LONG(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_LONG(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_LONG(operand1, operand2); } /* Code referring to "LONG" corresponds to Python2 'long', Python3 'int' and "OBJECT" to any Python object. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_LONG_OBJECT(PyObject *operand1, PyObject *operand2) { PyTypeObject *type2 = Py_TYPE(operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyLong_Type.tp_as_number->nb_true_divide; binaryfunc slot2 = NULL; if (!(&PyLong_Type == type2)) { // Different types, need to consider second value slot. slot2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_true_divide : NULL; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { if (slot2 != NULL) { if (Nuitka_Type_IsSubtype(type2, &PyLong_Type)) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); slot2 = NULL; } } PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!1 || !NEW_STYLE_NUMBER_TYPE(type2)) { coercion c1 = PyLong_Type.tp_as_number->nb_coerce; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_coerce : NULL; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif #if PYTHON_VERSION < 0x300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'long' and '%s'", type2->tp_name); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'int' and '%s'", type2->tp_name); #endif goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_LONG_OBJECT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyLong_CheckExact(operand1)); CHECK_OBJECT(operand2); PyTypeObject *type2 = Py_TYPE(operand2); if (&PyLong_Type == type2) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_LONG(operand1, operand2); // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; #ifdef _MSC_VER #pragma warning(pop) #endif PyObject *x = PyLong_Type.tp_as_number->nb_true_divide(operand1, operand2); assert(x != Py_NotImplemented); obj_result = x; goto exit_result_object; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_LONG_OBJECT(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_LONG_OBJECT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_OBJECT(operand1, operand2); } /* Code referring to "FLOAT" corresponds to Python 'float' and "FLOAT" to Python 'float'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_FLOAT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); PyObject *result; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif // Not every code path will make use of all possible results. NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); const double a = PyFloat_AS_DOUBLE(operand1); const double b = PyFloat_AS_DOUBLE(operand2); if (unlikely(b == 0.0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "float division by zero"); goto exit_result_exception; } { double r = a / b; cfloat_result = r; goto exit_result_ok_cfloat; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_FLOAT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_FLOAT(operand1, operand2); } /* Code referring to "OBJECT" corresponds to any Python object and "FLOAT" to Python 'float'. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_FLOAT(PyObject *operand1, PyObject *operand2) { PyTypeObject *type1 = Py_TYPE(operand1); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_true_divide : NULL; binaryfunc slot2 = NULL; if (!(type1 == &PyFloat_Type)) { // Different types, need to consider second value slot. slot2 = PyFloat_Type.tp_as_number->nb_true_divide; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!NEW_STYLE_NUMBER_TYPE(type1) || !1) { coercion c1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_coerce : NULL; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = PyFloat_Type.tp_as_number->nb_coerce; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and 'float'", type1->tp_name); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_FLOAT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); PyTypeObject *type1 = Py_TYPE(operand1); if (type1 == &PyFloat_Type) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_FLOAT(operand1, operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif // Not every code path will make use of all possible results. NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); const double a = PyFloat_AS_DOUBLE(operand1); const double b = PyFloat_AS_DOUBLE(operand2); if (unlikely(b == 0.0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "float division by zero"); goto exit_result_exception; } { double r = a / b; cfloat_result = r; goto exit_result_ok_cfloat; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_FLOAT(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_FLOAT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_FLOAT(operand1, operand2); } /* Code referring to "FLOAT" corresponds to Python 'float' and "OBJECT" to any Python object. */ static HEDLEY_NEVER_INLINE PyObject *__BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_OBJECT(PyObject *operand1, PyObject *operand2) { PyTypeObject *type2 = Py_TYPE(operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyFloat_Type.tp_as_number->nb_true_divide; binaryfunc slot2 = NULL; if (!(&PyFloat_Type == type2)) { // Different types, need to consider second value slot. slot2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_true_divide : NULL; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { if (slot2 != NULL) { if (Nuitka_Type_IsSubtype(type2, &PyFloat_Type)) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); slot2 = NULL; } } PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!1 || !NEW_STYLE_NUMBER_TYPE(type2)) { coercion c1 = PyFloat_Type.tp_as_number->nb_coerce; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_coerce : NULL; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'float' and '%s'", type2->tp_name); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_OBJECT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); PyTypeObject *type2 = Py_TYPE(operand2); if (&PyFloat_Type == type2) { PyObject *result; // return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_FLOAT(operand1, operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif // Not every code path will make use of all possible results. NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); const double a = PyFloat_AS_DOUBLE(operand1); const double b = PyFloat_AS_DOUBLE(operand2); if (unlikely(b == 0.0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "float division by zero"); goto exit_result_exception; } { double r = a / b; cfloat_result = r; goto exit_result_ok_cfloat; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } return __BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_OBJECT(operand1, operand2); } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_OBJECT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_OBJECT(operand1, operand2); } /* Code referring to "FLOAT" corresponds to Python 'float' and "LONG" to Python2 'long', Python3 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_LONG(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyLong_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyFloat_Type.tp_as_number->nb_true_divide; // Slot2 ignored on purpose, type1 takes precedence. if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types #if PYTHON_VERSION < 0x300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'float' and 'long'"); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'float' and 'int'"); #endif goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_LONG(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_LONG(operand1, operand2); } /* Code referring to "LONG" corresponds to Python2 'long', Python3 'int' and "FLOAT" to Python 'float'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_LONG_FLOAT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyLong_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif // Slot1 ignored on purpose, type2 takes precedence. binaryfunc slot2 = NULL; if (!(0)) { // Different types, need to consider second value slot. slot2 = PyFloat_Type.tp_as_number->nb_true_divide; } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types #if PYTHON_VERSION < 0x300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'long' and 'float'"); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'int' and 'float'"); #endif goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_LONG_FLOAT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_FLOAT(operand1, operand2); } #if PYTHON_VERSION < 0x300 /* Code referring to "FLOAT" corresponds to Python 'float' and "INT" to Python2 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_INT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyFloat_Type.tp_as_number->nb_true_divide; // Slot2 ignored on purpose, type1 takes precedence. if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'float' and 'int'"); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_INT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_INT(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "INT" corresponds to Python2 'int' and "FLOAT" to Python 'float'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_INT_FLOAT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif // Slot1 ignored on purpose, type2 takes precedence. binaryfunc slot2 = NULL; if (!(0)) { // Different types, need to consider second value slot. slot2 = PyFloat_Type.tp_as_number->nb_true_divide; } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'int' and 'float'"); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_INT_FLOAT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_FLOAT(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "LONG" corresponds to Python2 'long', Python3 'int' and "INT" to Python2 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_LONG_INT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyLong_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = PyLong_Type.tp_as_number->nb_true_divide; // Slot2 ignored on purpose, type1 takes precedence. if (slot1 != NULL) { PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'long' and 'int'"); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_LONG_INT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_LONG_INT(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "INT" corresponds to Python2 'int' and "LONG" to Python2 'long', Python3 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_INT_LONG(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyLong_CheckExact(operand2)); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif // Slot1 ignored on purpose, type2 takes precedence. binaryfunc slot2 = NULL; if (!(0)) { // Different types, need to consider second value slot. slot2 = PyLong_Type.tp_as_number->nb_true_divide; } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } // Statically recognized that coercion is not possible with these types PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: 'int' and 'long'"); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_INT_LONG(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_LONG(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "INT" corresponds to Python2 'int' and "CLONG" to C platform long value. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_INT_CLONG(PyObject *operand1, long operand2) { CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); PyObject *result; // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); const long a = PyInt_AS_LONG(operand1); const long b = operand2; if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = operand1; PyObject *operand2_object = PyLong_FromLong(operand2); PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); Py_DECREF(operand2_object); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_INT_CLONG(PyObject *operand1, long operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_INT_CLONG(operand1, operand2); } #endif #if PYTHON_VERSION < 0x300 /* Code referring to "CLONG" corresponds to C platform long value and "INT" to Python2 'int'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_CLONG_INT(long operand1, PyObject *operand2) { CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); PyObject *result; // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); const long a = operand1; const long b = PyInt_AS_LONG(operand2); if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = PyLong_FromLong(operand1); PyObject *operand2_object = operand2; PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); Py_DECREF(operand1_object); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_CLONG_INT(long operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_CLONG_INT(operand1, operand2); } #endif /* Code referring to "FLOAT" corresponds to Python 'float' and "CFLOAT" to C platform float value. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_CFLOAT(PyObject *operand1, double operand2) { CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); PyObject *result; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif // Not every code path will make use of all possible results. NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyFloat_CheckExact(operand1)); const double a = PyFloat_AS_DOUBLE(operand1); const double b = operand2; if (unlikely(b == 0.0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "float division by zero"); goto exit_result_exception; } { double r = a / b; cfloat_result = r; goto exit_result_ok_cfloat; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_CFLOAT(PyObject *operand1, double operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_FLOAT_CFLOAT(operand1, operand2); } /* Code referring to "CFLOAT" corresponds to C platform float value and "FLOAT" to Python 'float'. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_CFLOAT_FLOAT(double operand1, PyObject *operand2) { CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); PyObject *result; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif // Not every code path will make use of all possible results. NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand2); assert(PyFloat_CheckExact(operand2)); const double a = operand1; const double b = PyFloat_AS_DOUBLE(operand2); if (unlikely(b == 0.0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "float division by zero"); goto exit_result_exception; } { double r = a / b; cfloat_result = r; goto exit_result_ok_cfloat; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_CFLOAT_FLOAT(double operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_CFLOAT_FLOAT(operand1, operand2); } /* Code referring to "OBJECT" corresponds to any Python object and "OBJECT" to any Python object. */ static PyObject *_BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_OBJECT(PyObject *operand1, PyObject *operand2) { CHECK_OBJECT(operand1); CHECK_OBJECT(operand2); #if PYTHON_VERSION < 0x300 if (PyInt_CheckExact(operand1) && PyInt_CheckExact(operand2)) { PyObject *result; // Not every code path will make use of all possible results. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; NUITKA_MAY_BE_UNUSED long clong_result; NUITKA_MAY_BE_UNUSED double cfloat_result; #ifdef _MSC_VER #pragma warning(pop) #endif CHECK_OBJECT(operand1); assert(PyInt_CheckExact(operand1)); CHECK_OBJECT(operand2); assert(PyInt_CheckExact(operand2)); const long a = PyInt_AS_LONG(operand1); const long b = PyInt_AS_LONG(operand2); if (unlikely(b == 0)) { SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero"); goto exit_result_exception; } if (a == 0) { if (b < 0) { goto exit_result_ok_const_float_minus_0_0; } else { goto exit_result_ok_const_float_0_0; } } /* May need to resort to LONG code, which we currently do not * specialize yet. TODO: Once we do that, call it here instead. */ #if DBL_MANT_DIG < WIDTH_OF_ULONG if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) { } else #endif { double r = (double)a / (double)b; cfloat_result = r; goto exit_result_ok_cfloat; } { PyObject *operand1_object = operand1; PyObject *operand2_object = operand2; PyObject *r = PyLong_Type.tp_as_number->nb_true_divide(operand1_object, operand2_object); assert(r != Py_NotImplemented); obj_result = r; goto exit_result_object; } exit_result_ok_cfloat: result = MAKE_FLOAT_FROM_DOUBLE(cfloat_result); goto exit_result_ok; exit_result_object: if (unlikely(obj_result == NULL)) { goto exit_result_exception; } result = obj_result; goto exit_result_ok; exit_result_ok_const_float_0_0: Py_INCREF(const_float_0_0); result = const_float_0_0; goto exit_result_ok; exit_result_ok_const_float_minus_0_0: Py_INCREF(const_float_minus_0_0); result = const_float_minus_0_0; goto exit_result_ok; exit_result_ok: return result; exit_result_exception: return NULL; } #endif PyTypeObject *type1 = Py_TYPE(operand1); PyTypeObject *type2 = Py_TYPE(operand2); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4101) #endif NUITKA_MAY_BE_UNUSED bool cbool_result; NUITKA_MAY_BE_UNUSED PyObject *obj_result; #ifdef _MSC_VER #pragma warning(pop) #endif binaryfunc slot1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_true_divide : NULL; binaryfunc slot2 = NULL; if (!(type1 == type2)) { // Different types, need to consider second value slot. slot2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_true_divide : NULL; if (slot1 == slot2) { slot2 = NULL; } } if (slot1 != NULL) { if (slot2 != NULL) { if (Nuitka_Type_IsSubtype(type2, type1)) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); slot2 = NULL; } } PyObject *x = slot1(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } if (slot2 != NULL) { PyObject *x = slot2(operand1, operand2); if (x != Py_NotImplemented) { obj_result = x; goto exit_binary_result_object; } Py_DECREF(x); } #if PYTHON_VERSION < 0x300 if (!NEW_STYLE_NUMBER_TYPE(type1) || !NEW_STYLE_NUMBER_TYPE(type2)) { coercion c1 = (type1->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type1)) ? type1->tp_as_number->nb_coerce : NULL; if (c1 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c1(&coerced1, &coerced2); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } coercion c2 = (type2->tp_as_number != NULL && NEW_STYLE_NUMBER_TYPE(type2)) ? type2->tp_as_number->nb_coerce : NULL; if (c2 != NULL) { PyObject *coerced1 = operand1; PyObject *coerced2 = operand2; int err = c2(&coerced2, &coerced1); if (unlikely(err < 0)) { goto exit_binary_exception; } if (err == 0) { PyNumberMethods *mv = Py_TYPE(coerced1)->tp_as_number; if (likely(mv == NULL)) { binaryfunc slot = mv->nb_true_divide; if (likely(slot != NULL)) { PyObject *x = slot(coerced1, coerced2); Py_DECREF(coerced1); Py_DECREF(coerced2); obj_result = x; goto exit_binary_result_object; } } // nb_coerce took a reference. Py_DECREF(coerced1); Py_DECREF(coerced2); } } } #endif PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for /: '%s' and '%s'", type1->tp_name, type2->tp_name); goto exit_binary_exception; exit_binary_result_object: return obj_result; exit_binary_exception: return NULL; } PyObject *BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_OBJECT(PyObject *operand1, PyObject *operand2) { return _BINARY_OPERATION_TRUEDIV_OBJECT_OBJECT_OBJECT(operand1, operand2); }
182f3ceab49287442dc7f9894c64ca6cb0f4cf46
7664f318ed04bd0680f3d82321c18896e3ef6ad5
/src/libultra/io/pfsinitpak.c
59fb8eda9bf52624192a4554b0d8b77320c77fde
[]
no_license
zeldaret/oot
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
refs/heads/master
2023-08-29T05:29:31.356427
2023-08-28T22:48:52
2023-08-28T22:48:52
247,875,738
4,401
802
null
2023-09-14T13:34:38
2020-03-17T04:02:19
C
UTF-8
C
false
false
2,699
c
pfsinitpak.c
#include "ultra64.h" #include "global.h" s32 osPfsInitPak(OSMesgQueue* queue, OSPfs* pfs, s32 channel) { s32 ret; u16 sum; u16 isum; u8 temp[BLOCKSIZE]; __OSPackId* id; __OSPackId newid; __osSiGetAccess(); ret = __osPfsGetStatus(queue, channel); __osSiRelAccess(); if (ret != 0) { return ret; } pfs->queue = queue; pfs->channel = channel; pfs->status = 0; if ((ret = __osPfsCheckRamArea(pfs)) != 0) { return ret; } if ((ret = __osPfsSelectBank(pfs, 0)) != 0) { return ret; } if ((ret = __osContRamRead(pfs->queue, pfs->channel, PFS_ID_0AREA, temp)) != 0) { return (ret); } __osIdCheckSum((u16*)temp, &sum, &isum); id = (__OSPackId*)temp; if ((id->checksum != sum) || (id->invertedChecksum != isum)) { if ((ret = __osCheckPackId(pfs, id)) != 0) { pfs->status |= PFS_ID_BROKEN; return ret; } } if ((id->deviceid & 0x01) == 0) { ret = __osRepairPackId(pfs, id, &newid); if (ret) { if (ret == PFS_ERR_ID_FATAL) { pfs->status |= PFS_ID_BROKEN; } return ret; } id = &newid; if ((id->deviceid & 0x01) == 0) { return PFS_ERR_DEVICE; } } bcopy(id, pfs->id, BLOCKSIZE); if (1) {} pfs->version = id->version; pfs->banks = id->banks; pfs->inodeStartPage = 1 + DEF_DIR_PAGES + (2 * pfs->banks); pfs->dir_size = DEF_DIR_PAGES * PFS_ONE_PAGE; pfs->inode_table = 1 * PFS_ONE_PAGE; pfs->minode_table = (1 + pfs->banks) * PFS_ONE_PAGE; pfs->dir_table = pfs->minode_table + (pfs->banks * PFS_ONE_PAGE); if ((ret = __osContRamRead(pfs->queue, pfs->channel, PFS_LABEL_AREA, pfs->label)) != 0) { return ret; } ret = osPfsChecker(pfs); pfs->status |= PFS_INITIALIZED; return ret; } s32 __osPfsCheckRamArea(OSPfs* pfs) { s32 i = 0; s32 ret = 0; u8 temp1[BLOCKSIZE]; u8 temp2[BLOCKSIZE]; u8 saveReg[BLOCKSIZE]; if ((ret = __osPfsSelectBank(pfs, PFS_ID_BANK_256K)) != 0) { return ret; } if ((ret = __osContRamRead(pfs->queue, pfs->channel, 0, saveReg)) != 0) { return ret; } for (i = 0; i < BLOCKSIZE; i++) { temp1[i] = i; } if ((ret = __osContRamWrite(pfs->queue, pfs->channel, 0, temp1, 0)) != 0) { return ret; } if ((ret = __osContRamRead(pfs->queue, pfs->channel, 0, temp2)) != 0) { return ret; } if (bcmp(temp1, temp2, BLOCKSIZE) != 0) { return PFS_ERR_DEVICE; } return __osContRamWrite(pfs->queue, pfs->channel, 0, saveReg, 0); }
34bcdfd4be017ab595f600bbaf21f1cc42fe77fa
bc4b4d40abb9a76423cec89944fbc0614caf43b4
/tests/signal_processing_unittest.c
1e945c2c557f95ae10993db559e6ecaa46542f9d
[ "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webrtc" ]
permissive
dpirch/libfvad
3999d70ba31e4af9095e607152fc983ccfd75d71
997e9dc85bcf5a8be27b0b5b422c7c260c667a41
refs/heads/master
2023-09-03T12:15:37.956618
2021-07-08T10:40:11
2023-06-21T16:00:34
68,475,640
398
160
BSD-3-Clause
2023-09-03T13:31:08
2016-09-17T20:09:03
C
UTF-8
C
false
false
4,345
c
signal_processing_unittest.c
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "../src/signal_processing/signal_processing_library.h" #include "test_common.h" #include <string.h> #ifdef TEST_SPL_MACRO void test_main() { // Macros with inputs. int B = 21; int a = -3; int b = WEBRTC_SPL_WORD32_MAX; EXPECT_EQ(-63, WEBRTC_SPL_MUL(a, B)); EXPECT_EQ(-2147483645, WEBRTC_SPL_MUL(a, b)); // note: this check has been removed in upstream webrtc } #endif // TEST_SPL_MACRO #ifdef TEST_SPL_INLINE void test_main() { int32_t a32 = 111121; EXPECT_EQ(17, WebRtcSpl_GetSizeInBits(a32)); EXPECT_EQ(0, WebRtcSpl_NormW32(0)); EXPECT_EQ(31, WebRtcSpl_NormW32(-1)); EXPECT_EQ(0, WebRtcSpl_NormW32(WEBRTC_SPL_WORD32_MIN)); EXPECT_EQ(14, WebRtcSpl_NormW32(a32)); EXPECT_EQ(0, WebRtcSpl_NormU32(0u)); EXPECT_EQ(0, WebRtcSpl_NormU32(0xffffffff)); EXPECT_EQ(15, WebRtcSpl_NormU32(a32)); } #endif // TEST_SPL_INLINE #ifdef TEST_SPL_LEADING_ZEROS void test_main() { EXPECT_EQ(32, WebRtcSpl_CountLeadingZeros32(0)); EXPECT_EQ(32, WebRtcSpl_CountLeadingZeros32_NotBuiltin(0)); for (int i = 0; i < 32; ++i) { const uint32_t single_one = (uint32_t)1 << i; const uint32_t all_ones = 2 * single_one - 1; EXPECT_EQ(31 - i, WebRtcSpl_CountLeadingZeros32(single_one)); EXPECT_EQ(31 - i, WebRtcSpl_CountLeadingZeros32_NotBuiltin(single_one)); EXPECT_EQ(31 - i, WebRtcSpl_CountLeadingZeros32(all_ones)); EXPECT_EQ(31 - i, WebRtcSpl_CountLeadingZeros32_NotBuiltin(all_ones)); } } #endif // TEST_SPL_LEADING_ZEROS #ifdef TEST_SPL_MATH_OPERATIONS void test_main() { int32_t num = 117; int32_t den = -5; EXPECT_EQ(-23, WebRtcSpl_DivW32W16(num, (int16_t)den)); } #endif // TEST_SPL_MATH_OPERATIONS #ifdef TEST_SPL_SIGNAL_PROCESSING void test_main() { const size_t kVectorSize = 4; int A[] = {1, 2, 33, 100}; // const int16_t kHanning[4] = { 2399, 8192, 13985, 16384 }; int16_t b16[kVectorSize]; // int16_t bTmp16[kVectorSize]; int bScale = 0; for (size_t kk = 0; kk < kVectorSize; ++kk) { b16[kk] = A[kk]; } for (size_t kk = 0; kk < kVectorSize; ++kk) { b16[kk] = A[kk]; } EXPECT_EQ(11094 , WebRtcSpl_Energy(b16, kVectorSize, &bScale)); EXPECT_EQ(0, bScale); } #endif // TEST_SPL_SIGNAL_PROCESSING #ifdef TEST_SPL_RESAMPLE_48 void test_main() { // The test resamples 3*kBlockSize number of samples to 2*kBlockSize number // of samples. #define kBlockSize 16 // Saturated input vector of 48 samples. const int32_t kVectorSaturated[3 * kBlockSize + 7] = { -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767 }; // All values in |out_vector| should be |kRefValue32kHz|. const int32_t kRefValue32kHz1 = -1077493760; const int32_t kRefValue32kHz2 = 1077493645; // After bit shift with saturation, |out_vector_w16| is saturated. //const int16_t kRefValue16kHz1 = -32768; //const int16_t kRefValue16kHz2 = 32767; // Vector for storing output. int32_t out_vector[2 * kBlockSize]; // int16_t out_vector_w16[2 * kBlockSize]; WebRtcSpl_Resample48khzTo32khz(kVectorSaturated, out_vector, kBlockSize); // Comparing output values against references. The values at position // 12-15 are skipped to account for the filter lag. for (size_t i = 0; i < 12; ++i) { EXPECT_EQ(kRefValue32kHz1, out_vector[i]); //EXPECT_EQ(kRefValue16kHz1, out_vector_w16[i]); } for (size_t i = 16; i < 2 * kBlockSize; ++i) { EXPECT_EQ(kRefValue32kHz2, out_vector[i]); //EXPECT_EQ(kRefValue16kHz2, out_vector_w16[i]); } } #endif
72530686844b772baf42ca4091662c1062ae1c09
dae15b230f6a39e8451420b2dea61fb719f9ffdf
/include/api/ofp_route_arp.h
ad2aea3e056b5a94842ad994c97f280b30c84512
[ "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
OpenFastPath/ofp
2b97bbd152fd877cb8b2125128d6826c0f4491dd
6b48500af9752c7d51a290390751988759a8256d
refs/heads/master
2023-05-25T15:21:17.682339
2023-05-10T07:14:01
2023-05-10T11:01:16
37,121,923
367
146
BSD-3-Clause
2023-09-13T14:19:24
2015-06-09T09:08:43
C
UTF-8
C
false
false
3,328
h
ofp_route_arp.h
/* Copyright (c) 2016, ENEA Software AB * Copyright (c) 2016, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef __OFP_ROUTE_ARP_H__ #define __OFP_ROUTE_ARP_H__ #include <stdint.h> #include <string.h> #include "ofp_log.h" #if __GNUC__ >= 4 #pragma GCC visibility push(default) #endif /* ROUTE: ADD/DEL*/ struct ofp_route_msg { uint32_t type; #define OFP_ROUTE_ADD 1 #define OFP_ROUTE_DEL 2 #define OFP_MOBILE_ROUTE_ADD 3 #define OFP_MOBILE_ROUTE_DEL 4 #define OFP_LOCAL_INTERFACE_ADD 5 #define OFP_LOCAL_INTERFACE_DEL 6 #define OFP_ROUTE6_ADD 7 #define OFP_ROUTE6_DEL 8 uint32_t flags; #define OFP_RTF_NET 0x1 /* route usable */ #define OFP_RTF_GATEWAY 0x2 /* destination is a gateway */ #define OFP_RTF_HOST 0x4 /* host entry (lb, p2p)(net otherwise)*/ #define OFP_RTF_REJECT 0x8 /* host or net unreachable */ #define OFP_RTF_BLACKHOLE 0x1000 /* just discard pkts (during updates) */ #define OFP_RTF_LOCAL 0x200000/* route represents a local address */ #define OFP_RTF_BROADCAST 0x400000/* route represents a bcast address */ #define OFP_RTF_MULTICAST 0x800000/* route represents a mcast address */ uint32_t dst; uint32_t masklen; uint32_t gw; uint32_t port; uint16_t vlan; uint16_t vrf; uint8_t dst6[16]; uint8_t gw6[16]; }; int32_t ofp_set_route_msg(struct ofp_route_msg *msg); static inline int32_t ofp_set_route_params(uint32_t type, uint16_t vrf, uint16_t vlan, uint32_t port, uint32_t dst, uint32_t masklen, uint32_t gw, uint32_t flags) { struct ofp_route_msg msg; #if defined(OFP_DEBUG) if (type == OFP_ROUTE6_ADD || type == OFP_ROUTE6_DEL) { OFP_ERR("Incompatible type=%d\n", type); return -1; } #endif msg.type = type; msg.flags = flags; msg.vrf = vrf; msg.vlan = vlan; msg.port = port; msg.dst = dst; msg.masklen = masklen; msg.gw = gw; return ofp_set_route_msg(&msg); } static inline int32_t ofp_set_route6_params(uint32_t type, uint16_t vrf, uint16_t vlan, uint32_t port, const uint8_t dst6[], uint32_t masklen, const uint8_t gw6[], uint32_t flags) { struct ofp_route_msg msg; #if defined(OFP_DEBUG) if (type != OFP_ROUTE6_ADD && type != OFP_ROUTE6_DEL) { OFP_ERR("Incompatible type=%d\n", type); return -1; } #endif msg.type = type; msg.flags = flags; msg.vrf = vrf; msg.vlan = vlan; msg.port = port; if (dst6) { memcpy(msg.dst6, dst6, (masklen > 0) ? (1 + ((masklen - 1) >> 3)) : 0); } msg.masklen = masklen; if (gw6) { memcpy(msg.gw6, gw6, 16); } return ofp_set_route_msg(&msg); } /* ROUTE: SHOW */ #define OFP_SHOW_ARP 0 #define OFP_SHOW_ROUTES 1 void ofp_show_routes(int fd, int what); /* ROUTE operations */ struct ofp_nh_entry *ofp_get_next_hop(uint16_t vrf, uint32_t addr, uint32_t *flags); struct ofp_nh6_entry *ofp_get_next_hop6(uint16_t vrf, uint8_t *addr, uint32_t *flags); /* ARP */ struct ofp_ifnet; int ofp_add_mac(struct ofp_ifnet *dev, uint32_t addr, uint8_t *mac); int ofp_get_mac(struct ofp_ifnet *dev, struct ofp_nh_entry *nh_data, uint32_t addr, uint32_t is_link_local, uint8_t *mac_out); void ofp_add_mac6(struct ofp_ifnet *dev, uint8_t *addr, uint8_t *mac); #if __GNUC__ >= 4 #pragma GCC visibility pop #endif #endif /* __OFP_ROUTE_ARP_H__ */
547bea6a386d50e7d7cd1abeb782c0769e61726b
178a0e20a6e63b7ce13223c8b3c9dfa4044235ff
/tests/test_list.c
5af063acbd5c1ac049aa60dd2af63905b21763aa
[ "MIT" ]
permissive
FedeDP/libmodule
ee82cb32ba740dd6d779629635b244a751e8adfa
f4c4bb2d56b7fd7d27cdeba245a153b55aa5c871
refs/heads/master
2023-06-22T08:48:53.349034
2023-01-03T17:31:22
2023-01-03T21:43:06
123,963,483
121
9
MIT
2023-01-04T18:06:16
2018-03-05T18:49:59
C
UTF-8
C
false
false
3,930
c
test_list.c
#include "test_list.h" #include <module/structs/itr.h> #include <stdlib.h> static m_list_t *my_l; static int val1 = 1; static int val2 = 2; static int val3 = 3; void test_list_insert(void **state) { (void) state; /* unused */ /* NULL map */ int ret = m_list_insert(my_l, &val1); assert_false(ret == 0); my_l = m_list_new(NULL, NULL); /* NULL value */ ret = m_list_insert(my_l, NULL); assert_false(ret == 0); ret = m_list_insert(my_l, &val1); assert_true(ret == 0); ret = m_list_insert(my_l, &val2); assert_true(ret == 0); ret = m_list_insert(my_l, &val3); assert_true(ret == 0); } void test_list_length(void **state) { (void) state; /* unused */ int len = m_list_len(NULL); assert_false(len > 0); len = m_list_len(my_l); assert_int_equal(len, 3); } void test_list_iterator(void **state) { (void) state; /* unused */ /* NULL list */ m_list_itr_t *itr = m_list_itr_new(NULL); assert_null(itr); itr = m_list_itr_new(my_l); assert_non_null(itr); int count = m_list_len(my_l); while (count) { count--; printf("%p\n", m_itr_get(itr)); /* Insert a node */ int ret = m_list_itr_insert(itr, &val1); assert_true(ret == 0); /* Remove previously inserted node */ ret = m_itr_rm(itr); assert_true(ret == 0); m_itr_next(&itr); } assert_int_equal(count, 0); assert_null(itr); } void test_list_find(void **state) { void *data = m_list_find(NULL, NULL); assert_null(data); data = m_list_find(my_l, NULL); assert_null(data); int c = 0; data = m_list_find(my_l, &c); assert_null(data); data = m_list_find(my_l, &val2); assert_non_null(data); assert_ptr_equal(data, &val2); } void test_list_remove(void **state) { (void) state; /* unused */ int ret = m_list_remove(NULL, NULL); assert_false(ret == 0); ret = m_list_remove(my_l, NULL); assert_false(ret == 0); ret = m_list_remove(my_l, &val1); assert_true(ret == 0); ret = m_list_remove(my_l, &val2); assert_true(ret == 0); int len = m_list_len(my_l); assert_int_equal(len, 1); // one element left, ie: val3 } void test_list_clear(void **state) { (void) state; /* unused */ int ret = m_list_clear(NULL); assert_false(ret == 0); ret = m_list_clear(my_l); assert_true(ret == 0); int len = m_list_len(my_l); assert_int_equal(len, 0); } void test_list_free(void **state) { (void) state; /* unused */ int ret = m_list_free(NULL); assert_false(ret == 0); ret = m_list_free(&my_l); assert_true(ret == 0); assert_null(my_l); } static int int_match(void *my_data, void *list_data) { int a = *((int *)my_data); int b = *((int *)list_data); return !(a == b); } void test_list_int(void **state) { int ret; my_l = m_list_new(int_match, free); for (int i = 0; i < 10; i++) { int *p = malloc(sizeof(int)); *p = i; ret = m_list_insert(my_l, p); assert_true(ret == 0); } int len = m_list_len(my_l); assert_int_equal(len, 10); int val = 5; int *data = m_list_find(my_l, &val); assert_non_null(data); assert_int_equal(*data, 5); val = 7; ret = m_list_remove(my_l, &val); assert_int_equal(ret, 0); len = m_list_len(my_l); assert_int_equal(len, 9); val = 9; ret = m_list_remove(my_l, &val); assert_int_equal(ret, 0); len = m_list_len(my_l); assert_int_equal(len, 8); val = 10; ret = m_list_remove(my_l, &val); assert_false(ret == 0); // nonexistent! len = m_list_len(my_l); assert_int_equal(len, 8); ret = m_list_free(&my_l); assert_true(ret == 0); assert_null(my_l); }
732ec000b30bb5aceea220a0c5241508a05d058f
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/amiga/dev/zz9kvar.h
e0fa8fae240485ba9ff2b497ad18b5cdcbd237ed
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
2,099
h
zz9kvar.h
/* $NetBSD: zz9kvar.h,v 1.1 2023/05/03 13:49:30 phx Exp $ */ /* * Copyright (c) 2020 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Alain Runa. * * 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. */ #ifndef ZZ9KVAR_H #define ZZ9KVAR_H #include <sys/types.h> /* size_t, char */ #include <sys/bus.h> /* bus_space_xxx, bus_addr_t */ #include <sys/device.h> /* device_t */ #include <amiga/dev/zbusvar.h> /* zbus_args */ #define ZZREG_R(r) bus_space_read_2(sc->sc_iot, sc->sc_regh, (r)) #define ZZREG_W(r, v) bus_space_write_2(sc->sc_iot, sc->sc_regh, (r), (v)) struct zz9k_softc { device_t sc_dev; struct bus_space_tag sc_bst; bus_space_tag_t sc_iot; bus_space_handle_t sc_regh; size_t sc_zsize; }; struct zz9kbus_attach_args { char zzaa_name[32]; bus_addr_t zzaa_base; }; #endif /* ZZ9KVAR_H */
b7bde5f0bb60c83f1042dd17e5a4eaae58d5a047
8838eb997879add5759b6dfb23f9a646464e53ca
/src/net/socket/net_sock.h
99168ceaa0efc9f379a1731c5b3518acf694a045
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
1,409
h
net_sock.h
/** * @file * @brief Main Embox netsock include file for user net sockets. * * @date 05.07.11 * @author Dmitry Zubarevich */ #ifndef EMBOX_NET_SOCK_H_ #define EMBOX_NET_SOCK_H_ struct sock_proto_ops; /** * Each netsock implements this interface. */ struct net_sock { int family; int type; int protocol; int is_default; const struct sock_proto_ops *ops; }; extern const struct net_sock * net_sock_lookup(int family, int type, int protocol); #include <util/array.h> ARRAY_SPREAD_DECLARE(const struct net_sock, __net_sock_registry); #define net_sock_foreach(net_sock_ptr) \ array_spread_foreach_ptr(net_sock_ptr, __net_sock_registry) #define EMBOX_NET_SOCK(_family, _type, _protocol, _is_default, _ops) \ static const struct sock_proto_ops _ops; \ ARRAY_SPREAD_DECLARE(const struct net_sock, \ __net_sock_registry); \ ARRAY_SPREAD_ADD_NAMED(__net_sock_registry, \ __net_sock_##_family##_type##_protocol, { \ .family = _family, \ .type = _type, \ .protocol = _protocol, \ .is_default = _is_default, \ .ops = &_ops \ }) #endif /* EMBOX_NET_SOCK_H_ */
96dd96ed05b9c5ea2fd7be05898e371011ac00bd
1248f70e2bde2898dee5c675adfe36429702b1a0
/common/trie.c
bdbd6eaa3e4fc544ac39b5ba56d689f755a6f4e9
[]
no_license
dgod/yong
d009b12cd6e78eeae33a3a3f4ea445aaa7378c60
a7a1f83a0bea4078ee3e615c1a0018f8aef37b2e
refs/heads/master
2023-06-25T08:48:07.342805
2023-06-11T01:55:31
2023-06-11T01:55:31
62,427,557
173
46
null
2018-08-10T01:31:01
2016-07-02T01:03:35
C
UTF-8
C
false
false
12,232
c
trie.c
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <assert.h> #include "trie.h" #define TRIE_PAGE (512*1024) #ifdef _WIN32 #include <windows.h> static void *alloc_page(void) { void *p; p=VirtualAlloc(NULL,TRIE_PAGE,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE); return p; } static void free_page(void *p) { VirtualFree(p,0,MEM_RELEASE); } #elif defined(EMSCRIPTEN) static void *alloc_page(void) { return malloc(TRIE_PAGE); } static void free_page(void *p) { free(p); } #else #include <sys/mman.h> static void *alloc_page(void) { void *p; p=mmap(NULL,TRIE_PAGE,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0); return p; //return malloc(TRIE_PAGE); } static void free_page(void *p) { munmap(p,TRIE_PAGE); //free(p); } #endif trie_tree_t *trie_tree_new(void) { trie_tree_t *t; trie_node_t *n; t=calloc(1,sizeof(*t)); t->page[0]=alloc_page(); n=t->page[0]; memset(n,0,sizeof(*n)); n->node=1; t->count=1; return t; } void trie_tree_free(trie_tree_t *t) { int i; if(!t) return; for(i=0;i<256 && t->page[i];i++) free_page(t->page[i]); free(t); } static inline trie_node_t * trie_nth(trie_tree_t *t,int n) { int i,j; i=n>>16,j=n&0xffff; return t->page[i]+j; } static trie_node_t *trie_node(trie_tree_t *t,trie_node_t *n,uint32_t val) { int brother; for(;n->node;n=trie_nth(t,brother)) { if(n->self==val) return n; if(n->self>val) return NULL; brother=n->brother; if(!brother) return NULL; } return NULL; } static trie_node_t *trie_leaf(trie_tree_t *t,trie_node_t *n) { int brother; for(;n->node;n=trie_nth(t,brother)) { brother=n->brother; if(!brother) return NULL; } return n; } trie_node_t *trie_tree_get_path(trie_tree_t *t,const char *s,int len) { trie_node_t *n; int i,val; n=trie_nth(t,0); if(!n->child) return NULL; n=trie_nth(t,n->child); for(i=0;i<len;i++) { val=s[i]; n=trie_node(t,n,val); if(!n) break; if(i+1==len) break; if(!n->child) return NULL; n=trie_nth(t,n->child); } return n; } trie_node_t *trie_tree_get_leaf(trie_tree_t *t,const char *s,int len) { trie_node_t *n; n=trie_tree_get_path(t,s,len); if(!n || !n->child) return NULL; n=trie_nth(t,n->child); n=trie_leaf(t,n); return n; } trie_node_t *trie_node_get_leaf(trie_tree_t *t,trie_node_t *n) { if(!n->leaf) return NULL; n=trie_nth(t,n->child); n=trie_leaf(t,n); return n; } trie_node_t *trie_node_get_child(trie_tree_t *t,trie_node_t *n) { if(!n->node) return NULL; n=trie_nth(t,n->child); if(!n->node) return NULL; return n; } trie_node_t *trie_node_get_brother(trie_tree_t *t,trie_node_t *n) { if(!n->node || !n->brother) return NULL; n=trie_nth(t,n->brother); if(!n->node) return NULL; return n; } int trie_tree_del(trie_tree_t *t,const char *s,int len) { trie_node_t *n; n=trie_tree_get_path(t,s,len); if(!n || !n->leaf) return -1; n->leaf=0; return 0; } int trie_tree_is_leaf(trie_tree_t *t,const char *s,int len) { trie_node_t *n; n=trie_tree_get_path(t,s,len); if(!n || !n->leaf) return 0; return 1; } static inline int trie_add(trie_tree_t *t) { int i=t->count>>16; if(!t->page[i]) t->page[i]=alloc_page(); return t->count++; } static inline trie_node_t *trie_add_child(trie_tree_t *t,trie_node_t *p,uint32_t val) { int j=trie_add(t); trie_node_t *n=trie_nth(t,j); n->brother=p->child; p->child=j; n->node=1; n->leaf=0; n->self=val; n->child=0; return n; } static inline trie_node_t *trie_add_brother(trie_tree_t *t,trie_node_t *p,uint32_t val) { int j=trie_add(t); trie_node_t *n=trie_nth(t,j); n->brother=p->brother; p->brother=j; n->node=1; n->leaf=0; n->self=val; n->child=0; return n; } trie_node_t *trie_tree_add(trie_tree_t *t,const char *s,int len) { trie_node_t *n=NULL,*p; int i,val; p=trie_nth(t,0); for(i=0;i<len;i++) { val=s[i]; if(!p->child) { n=trie_add_child(t,p,val); } else { trie_node_t *h=trie_nth(t,p->child); for(n=h;;) { trie_node_t *nn; int brother; if(n==h) { if(!n->node || n->self>val) { n=trie_add_child(t,p,val); break; } if(n->node && n->self==val) { break; } } brother=n->brother; if(!brother) { n=trie_add_brother(t,n,val); break; } nn=trie_nth(t,brother); if(!nn->node) { n=trie_add_brother(t,n,val); break; } else if(nn->self==val) { n=nn; break; } else if(nn->self>val) { n=trie_add_brother(t,n,val); break; } else { n=nn; } } } p=n; } n->leaf=1; if(!n->child) { i=trie_add(t); n->child=i; n=trie_nth(t,i); n->data=0; } else { n=trie_nth(t,n->child); for(;n->node;n=trie_nth(t,n->brother)) { if(!n->brother) { i=trie_add(t); n->brother=i; n=trie_nth(t,i); n->data=0; break; } } } return n; } trie_node_t *trie_tree_root(trie_tree_t *t) { return trie_nth(t,0); } trie_node_t *trie_iter_leaf_first(trie_iter_t *iter,trie_tree_t *t,trie_node_t *n,int depth) { if(!n) n=trie_nth(t,0); iter->tree=t; iter->root=n; iter->depth=0; iter->skip=1; iter->max=depth; iter->path[0]=n->child; if(n->leaf) { n=trie_nth(t,n->child); return trie_leaf(t,n); } iter->path[0]=n->child; return trie_iter_leaf_next(iter); } static inline void trie_iter_up(trie_iter_t *iter) { trie_node_t *n; iter->depth--; if(iter->depth<0) return; n=trie_nth(iter->tree,iter->path[iter->depth]); iter->path[iter->depth]=n->brother; } int trie_iter_get_path(trie_iter_t *iter,char *s) { trie_tree_t *t=iter->tree; int pos; for(pos=0;pos<iter->depth;pos++) { trie_node_t *r=trie_nth(t,iter->path[pos]); s[pos]=(char)r->self; } s[pos]=0; return pos; } trie_node_t *trie_iter_leaf_next(trie_iter_t *iter) { int pos; trie_tree_t *t=iter->tree; trie_node_t *n; trie_node_t *r; next: if(iter->depth<0) return NULL; pos=iter->path[iter->depth]; if(pos==0) { trie_iter_up(iter); goto next; } n=trie_nth(t,pos); if(!n->node) { trie_iter_up(iter); goto next; } if(n->child) { iter->depth++; if(iter->depth>=iter->max) { iter->depth--; iter->path[iter->depth]=n->brother; goto next; } else { iter->path[iter->depth]=n->child; } } if(n->leaf) { int child=n->child; n=trie_nth(t,child); r=trie_leaf(t,n); return r; } else { goto next; } } trie_node_t *trie_iter_path_first(trie_iter_t *iter,trie_tree_t *t,trie_node_t *n,int depth) { if(!n) n=trie_nth(t,0); iter->tree=t; iter->root=n; iter->depth=0; iter->skip=0; iter->max=depth; if(!n->child) { iter->path[0]=0; return NULL; } iter->path[0]=n->child; n=trie_nth(t,n->child); return n; } trie_node_t *trie_iter_path_next(trie_iter_t *iter) { int skip; int pos; int up=0; trie_tree_t *t=iter->tree; trie_node_t *n=NULL; skip=iter->skip; if(skip) iter->skip=0; do{ if(iter->depth<0) return NULL; pos=iter->path[iter->depth]; if(pos==0) { trie_iter_up(iter); skip=0; up=1; continue; } n=trie_nth(t,pos); if(!n->node) { trie_iter_up(iter); skip=0; up=1; continue; } else if(up!=0) { return n; } if(skip || !n->child || iter->depth>=iter->max-1) { skip=0; if(n->brother) { iter->path[iter->depth]=n->brother; n=trie_nth(t,n->brother); if(n->node) return n; } } else { iter->depth++; iter->path[iter->depth]=n->child; n=trie_nth(t,n->child); if(n->node) return n; } trie_iter_up(iter); up=1; }while(1); } void py_tree_init(py_tree_t *tree) { tree->count=1; tree->node[0]=0; } void py_tree_add(py_tree_t *tree,const char *s,int len,int item) { py_node_t *n,*p; int i,val; p=(py_node_t*)(tree->node+0); if(len<1) return; for(i=0;i<len;i++) { val=s[i]-'a'; if(!p->child) { p->child=tree->count++; n=(py_node_t*)(tree->node+p->child); n->data=0; n->self=val; } else { py_node_t *h=(py_node_t*)(tree->node+p->child); for(n=h;;) { py_node_t *nn; if(n->self==val) break; if(n==h && n->self>val) { int temp=tree->count++; n=(py_node_t*)(tree->node+temp); n->data=0; n->self=val; n->brother=p->child; p->child=temp; break; } if(!n->brother) { n->brother=tree->count++; n=(py_node_t*)(tree->node+n->brother); n->data=0; n->self=val; break; } nn=(py_node_t*)(tree->node+n->brother); if(nn->self==val) { n=nn; break; } else if(nn->self>val) { int temp=tree->count++; nn=(py_node_t*)(tree->node+temp); nn->data=0; nn->self=val; nn->brother=n->brother; n->brother=temp; n=nn; break; } else { n=nn; } } } p=n; } n->item=item+1; } int py_tree_get(py_tree_t *tree,const char *s,int *out) { py_node_t *p; int count=0; int i,val; p=(py_node_t*)(tree->node+0); if(!p->child) return 0; p=(py_node_t*)(tree->node+p->child); for(i=0;;i++) { val=s[i]; if(val<'a' || val>'z') break; val-='a'; for(;;p=(py_node_t*)(tree->node+p->brother)) { if(p->self==val) break; else if(p->self>val) goto out; if(!p->brother) goto out; } if(p->item && s[i+1]!='i' && s[i+1]!='u' && s[i+1]!='v') { out[count++]=p->item-1; } if(!p->child) { break; } p=(py_node_t*)(tree->node+p->child); } out: return count; } #if 0 #include <time.h> int main(int arc,char *arg[]) { char line[4096]; char code[64]; FILE *fp; int indata=0; trie_tree_t *t; trie_iter_t iter; trie_node_t *n; clock_t stamp[4]; if(arc!=2) return -1; stamp[0]=clock(); fp=fopen(arg[1],"rb"); if(!fp) return -1; t=trie_tree_new(); while(fgets(line,sizeof(line),fp)!=NULL) { if(!indata) { if(!strncasecmp(line,"[DATA]",6)) indata=1; continue; } if(line[0]=='\n') continue; if(line[0]=='^') continue; if(line[0]=='{') continue; sscanf(line,"%64s",code); trie_tree_add(t,code,strlen(code)); } fclose(fp); stamp[1]=clock(); n=trie_tree_root(t); n=trie_iter_leaf_first(&iter,t,n,64); while(n!=NULL) { trie_iter_get_path(&iter,code); //printf("%s\n",code); n=trie_iter_leaf_next(&iter); } stamp[2]=clock(); n=trie_tree_root(t); n=trie_iter_path_first(&iter,t,n,64); while(n!=NULL) { trie_iter_get_path(&iter,code); //printf("%s\n",code); n=trie_iter_path_next(&iter); } stamp[3]=clock(); fprintf(stderr,"node count %d\n",t->count); fprintf(stderr,"load time %.3f\n",(double)((stamp[1]-stamp[0]))/CLOCKS_PER_SEC); fprintf(stderr,"iter time %.3f\n",(double)((stamp[2]-stamp[1]))/CLOCKS_PER_SEC); fprintf(stderr,"iter time %.3f\n",(double)((stamp[3]-stamp[2]))/CLOCKS_PER_SEC); trie_tree_free(t); return 0; } #endif #if 0 #include <time.h> int main(int arc,char *arg[]) { py_tree_t py_tree; char line[256]; FILE *fp; int count,i; int out[6]; clock_t start; if(arc!=2) return -1; fp=fopen(arg[1],"r"); if(!fp) return -1; py_tree_init(&py_tree); for(count=1;fgets(line,sizeof(line),fp);count++) { char code[64]; if(line[0]=='\n') continue; if(line[0]=='[') continue; sscanf(line,"%64s",code); py_tree_add(&py_tree,code,strlen(code),count); } fclose(fp); printf("total %d\n",py_tree.count); start=clock(); for(i=0;i<1000000;i++) { count=py_tree_get(&py_tree,"zhuang",out); } printf("%.2f\n",(double)(clock()-start)/CLOCKS_PER_SEC); for(i=0;i<count;i++) { printf("%d\n",out[i]); } return 0; } #endif
792e00915aead9b8ed51e4e9d8bed3ffe0c5e66b
a36899b1da27a9bf6f89c5fef60bd71b96779fc7
/apis/isis-ants-api/test/antenna/antenna.c
ba6dbf6463d7bba4298a668a6b3495986ab01fd7
[ "Apache-2.0" ]
permissive
kubos/kubos
b26cb13f8bc60b9e333906f391c51d8c8651d6ce
49b4bf78939cac4161374e696f1b8c834921ad7c
refs/heads/master
2023-08-03T10:19:22.732695
2023-02-21T19:32:46
2023-02-21T19:32:46
117,996,656
300
70
Apache-2.0
2023-07-25T22:54:04
2018-01-18T14:55:14
Rust
UTF-8
C
false
false
20,502
c
antenna.c
/* * Kubos API for ISIS Antenna Systems * Copyright (C) 2018 Kubos Corporation * * 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 <ants-api.h> #include <cmocka.h> /* Test Data */ #define ANTS_PRIMARY 0x31 #define ANTS_SECONDARY 0x32 #define ANT_COUNT 4 ants_telemetry system_telem = {.raw_temp = 574, .deploy_status = SYS_BURN_ACTIVE | ANT_2_STOPPED_TIME | ANT_2_NOT_DEPLOYED, .uptime = 9876 }; uint32_t uptime = 432; uint16_t deploy_status = SYS_ARMED | ANT_1_ACTIVE | ANT_4_NOT_DEPLOYED; uint16_t activation_time = 44; uint8_t activation_count = 3; /* End of Test Data */ static void test_init(void ** state) { will_return(__wrap_open, 1); assert_int_equal(k_ants_init("/dev/i2c-1", ANTS_PRIMARY, ANTS_SECONDARY, ANT_COUNT, 10), ANTS_OK); } static void test_no_init_arm(void ** arg) { assert_int_equal(k_ants_arm(), ANTS_ERROR); } static void test_reset(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, SYSTEM_RESET); expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, SYSTEM_RESET); ret = k_ants_reset(); assert_int_equal(ret, ANTS_OK); } static void test_watchdog_kick(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); ret = k_ants_watchdog_kick(); assert_int_equal(ret, ANTS_OK); } static void test_watchdog_thread(void ** arg) { KANTSStatus start_ret; KANTSStatus stop_ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); start_ret = k_ants_watchdog_start(); const struct timespec delay = {.tv_sec = 0, .tv_nsec = 2000001 }; nanosleep(&delay, NULL); stop_ret = k_ants_watchdog_stop(); assert_int_equal(start_ret, ANTS_OK); assert_int_equal(stop_ret, ANTS_OK); } static void test_watchdog_thread_twice(void ** arg) { KANTSStatus start_ret; KANTSStatus stop_ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); start_ret = k_ants_watchdog_start(); const struct timespec delay = {.tv_sec = 0, .tv_nsec = 2000001 }; nanosleep(&delay, NULL); stop_ret = k_ants_watchdog_stop(); assert_int_equal(start_ret, ANTS_OK); assert_int_equal(stop_ret, ANTS_OK); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, WATCHDOG_RESET); start_ret = k_ants_watchdog_start(); nanosleep(&delay, NULL); stop_ret = k_ants_watchdog_stop(); assert_int_equal(start_ret, ANTS_OK); assert_int_equal(stop_ret, ANTS_OK); } static void test_watchdog_stop_no_start(void ** arg) { KANTSStatus ret; ret = k_ants_watchdog_stop(); assert_int_equal(ret, ANTS_ERROR); } static void test_arm(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, ARM_ANTS); ret = k_ants_arm(); assert_int_equal(ret, ANTS_OK); } static void test_disarm(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DISARM_ANTS); ret = k_ants_disarm(); assert_int_equal(ret, ANTS_OK); } static void test_configure_primary(void ** arg) { KANTSStatus ret; ret = k_ants_configure(PRIMARY); /* * Two-part verification: * 1. Configuration should complete successfully */ assert_int_equal(ret, ANTS_OK); /* * 2. Commands now run against other address */ expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, ARM_ANTS); ret = k_ants_arm(); assert_int_equal(ret, ANTS_OK); } static void test_configure_secondary(void ** arg) { KANTSStatus ret; ret = k_ants_configure(SECONDARY); /* * Two-part verification: * 1. Configuration should complete successfully */ assert_int_equal(ret, ANTS_OK); /* * 2. Commands now run against other address */ expect_value(__wrap_ioctl, addr, ANTS_SECONDARY); expect_value(__wrap_write, cmd, ARM_ANTS); ret = k_ants_arm(); assert_int_equal(ret, ANTS_OK); } static void test_configure_fake(void ** arg) { KANTSStatus ret; ret = k_ants_configure(7); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_deploy_1_normal(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_1); ret = k_ants_deploy(ANT_1, false, 5); assert_int_equal(ret, ANTS_OK); } static void test_deploy_1_override(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_1_OVERRIDE); ret = k_ants_deploy(ANT_1, true, 10); assert_int_equal(ret, ANTS_OK); } static void test_deploy_2_normal(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_2); ret = k_ants_deploy(ANT_2, false, 5); assert_int_equal(ret, ANTS_OK); } static void test_deploy_2_override(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_2_OVERRIDE); ret = k_ants_deploy(ANT_2, true, 10); assert_int_equal(ret, ANTS_OK); } static void test_deploy_3_normal(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_3); ret = k_ants_deploy(ANT_3, false, 5); assert_int_equal(ret, ANTS_OK); } static void test_deploy_3_override(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_3_OVERRIDE); ret = k_ants_deploy(ANT_3, true, 10); assert_int_equal(ret, ANTS_OK); } static void test_deploy_4_normal(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_4); ret = k_ants_deploy(ANT_4, false, 2); assert_int_equal(ret, ANTS_OK); } static void test_deploy_4_override(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, DEPLOY_4_OVERRIDE); ret = k_ants_deploy(ANT_4, true, 0); assert_int_equal(ret, ANTS_OK); } static void test_deploy_fake(void ** arg) { KANTSStatus ret; ret = k_ants_deploy(6, true, 10); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_deploy_auto(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, AUTO_DEPLOY); ret = k_ants_auto_deploy(30); assert_int_equal(ret, ANTS_OK); } static void test_deploy_cancel(void ** arg) { KANTSStatus ret; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, CANCEL_DEPLOY); ret = k_ants_cancel_deploy(); assert_int_equal(ret, ANTS_OK); } static void test_get_deploy_status(void ** arg) { KANTSStatus ret; uint16_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_STATUS); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(deploy_status)); will_return(__wrap_read, &deploy_status); ret = k_ants_get_deploy_status(&resp); assert_int_equal(ret, ANTS_OK); } static void test_get_deploy_status_null(void ** arg) { KANTSStatus ret; ret = k_ants_get_deploy_status(NULL); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_uptime(void ** arg) { KANTSStatus ret; uint32_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_UPTIME_SYS); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(uptime)); will_return(__wrap_read, &uptime); ret = k_ants_get_uptime(&resp); assert_int_equal(ret, ANTS_OK); } static void test_get_uptime_null(void ** arg) { KANTSStatus ret; ret = k_ants_get_uptime(NULL); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_system_telemetry(void ** arg) { KANTSStatus ret; ants_telemetry resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_TELEMETRY); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(system_telem)); will_return(__wrap_read, &system_telem); ret = k_ants_get_system_telemetry(&resp); assert_int_equal(ret, ANTS_OK); } static void test_get_system_telemetry_null(void ** arg) { KANTSStatus ret; ret = k_ants_get_system_telemetry(NULL); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_activation_count_1(void ** arg) { KANTSStatus ret; uint8_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_COUNT_1); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_count)); will_return(__wrap_read, &activation_count); ret = k_ants_get_activation_count(ANT_1, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_count_2(void ** arg) { KANTSStatus ret; uint8_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_COUNT_2); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_count)); will_return(__wrap_read, &activation_count); ret = k_ants_get_activation_count(ANT_2, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_count_3(void ** arg) { KANTSStatus ret; uint8_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_COUNT_3); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_count)); will_return(__wrap_read, &activation_count); ret = k_ants_get_activation_count(ANT_3, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_count_4(void ** arg) { KANTSStatus ret; uint8_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_COUNT_4); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_count)); will_return(__wrap_read, &activation_count); ret = k_ants_get_activation_count(ANT_4, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_count_null(void ** arg) { KANTSStatus ret; ret = k_ants_get_activation_count(ANT_1, NULL); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_activation_count_fake(void ** arg) { KANTSStatus ret; uint8_t resp; ret = k_ants_get_activation_count(6, &resp); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_activation_time_1(void ** arg) { KANTSStatus ret; uint16_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_UPTIME_1); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_time)); will_return(__wrap_read, &activation_time); ret = k_ants_get_activation_time(ANT_1, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_time_2(void ** arg) { KANTSStatus ret; uint16_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_UPTIME_2); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_time)); will_return(__wrap_read, &activation_time); ret = k_ants_get_activation_time(ANT_2, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_time_3(void ** arg) { KANTSStatus ret; uint16_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_UPTIME_3); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_time)); will_return(__wrap_read, &activation_time); ret = k_ants_get_activation_time(ANT_3, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_time_4(void ** arg) { KANTSStatus ret; uint16_t resp; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, GET_UPTIME_4); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(activation_time)); will_return(__wrap_read, &activation_time); ret = k_ants_get_activation_time(ANT_4, &resp); assert_int_equal(ret, ANTS_OK); } static void test_get_activation_time_null(void ** arg) { KANTSStatus ret; ret = k_ants_get_activation_time(ANT_1, NULL); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_get_activation_time_fake(void ** arg) { KANTSStatus ret; uint16_t resp; ret = k_ants_get_activation_time(6, &resp); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_passthrough_null_tx(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0 }; uint8_t rx[1] = { 0 }; ret = k_ants_passthrough(NULL, sizeof(tx), rx, sizeof(rx)); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_passthrough_zero_tx_len(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0 }; uint8_t rx[1] = { 0 }; ret = k_ants_passthrough(tx, 0, rx, sizeof(rx)); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_passthrough_null_rx_nonzero_rx_len(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0 }; uint8_t rx[1] = { 0 }; ret = k_ants_passthrough(tx, sizeof(tx), NULL, sizeof(rx)); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_passthrough_nonnull_rx_zero_rx_len(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0 }; uint8_t rx[1] = { 0 }; ret = k_ants_passthrough(tx, sizeof(tx), rx, 0); assert_int_equal(ret, ANTS_ERROR_CONFIG); } static void test_passthrough_null_rx_zero_rx_len(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0x77 }; uint8_t rx[1] = { 0 }; /* * Valid test case. If rx==null and rx_len==0, * we're only writing to the I2C device */ expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, tx[0]); ret = k_ants_passthrough(tx, sizeof(tx), NULL, 0); assert_int_equal(ret, ANTS_OK); } static void test_passthrough(void ** arg) { KANTSStatus ret; uint8_t tx[1] = { 0x99 }; uint8_t rx[1] = { 0 }; expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); expect_value(__wrap_write, cmd, tx[0]); expect_value(__wrap_ioctl, addr, ANTS_PRIMARY); will_return(__wrap_read, sizeof(rx)); will_return(__wrap_read, "K"); ret = k_ants_passthrough(tx, sizeof(tx), rx, sizeof(rx)); assert_int_equal(ret, ANTS_OK); } /* Watchdog tests? */ static int init(void ** state) { will_return(__wrap_open, 1); k_ants_init("/dev/i2c-1", ANTS_PRIMARY, ANTS_SECONDARY, ANT_COUNT, 10); return 0; } static int term(void ** state) { will_return(__wrap_close, 0); k_ants_terminate(); return 0; } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_no_init_arm), cmocka_unit_test_teardown(test_init, term), cmocka_unit_test_setup_teardown(test_reset, init, term), cmocka_unit_test_setup_teardown(test_watchdog_kick, init, term), cmocka_unit_test_setup_teardown(test_watchdog_thread, init, term), cmocka_unit_test_setup_teardown(test_watchdog_thread_twice, init, term), cmocka_unit_test_setup_teardown(test_watchdog_stop_no_start, init, term), cmocka_unit_test_setup_teardown(test_arm, init, term), cmocka_unit_test_setup_teardown(test_disarm, init, term), cmocka_unit_test_setup_teardown(test_configure_primary, init, term), cmocka_unit_test_setup_teardown(test_configure_secondary, init, term), cmocka_unit_test_setup_teardown(test_configure_fake, init, term), cmocka_unit_test_setup_teardown(test_deploy_1_normal, init, term), cmocka_unit_test_setup_teardown(test_deploy_1_override, init, term), cmocka_unit_test_setup_teardown(test_deploy_2_normal, init, term), cmocka_unit_test_setup_teardown(test_deploy_2_override, init, term), cmocka_unit_test_setup_teardown(test_deploy_3_normal, init, term), cmocka_unit_test_setup_teardown(test_deploy_3_override, init, term), cmocka_unit_test_setup_teardown(test_deploy_4_normal, init, term), cmocka_unit_test_setup_teardown(test_deploy_4_override, init, term), cmocka_unit_test_setup_teardown(test_deploy_fake, init, term), cmocka_unit_test_setup_teardown(test_deploy_auto, init, term), cmocka_unit_test_setup_teardown(test_deploy_cancel, init, term), cmocka_unit_test_setup_teardown(test_get_deploy_status, init, term), cmocka_unit_test_setup_teardown(test_get_deploy_status_null, init, term), cmocka_unit_test_setup_teardown(test_get_uptime, init, term), cmocka_unit_test_setup_teardown(test_get_uptime_null, init, term), cmocka_unit_test_setup_teardown(test_get_system_telemetry, init, term), cmocka_unit_test_setup_teardown(test_get_system_telemetry_null, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_null, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_1, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_2, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_3, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_4, init, term), cmocka_unit_test_setup_teardown(test_get_activation_count_fake, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_null, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_1, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_2, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_3, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_4, init, term), cmocka_unit_test_setup_teardown(test_get_activation_time_fake, init, term), cmocka_unit_test_setup_teardown(test_passthrough_null_tx, init, term), cmocka_unit_test_setup_teardown(test_passthrough_zero_tx_len, init, term), cmocka_unit_test_setup_teardown( test_passthrough_null_rx_nonzero_rx_len, init, term), cmocka_unit_test_setup_teardown( test_passthrough_nonnull_rx_zero_rx_len, init, term), cmocka_unit_test_setup_teardown(test_passthrough_null_rx_zero_rx_len, init, term), cmocka_unit_test_setup_teardown(test_passthrough, init, term), }; return cmocka_run_group_tests(tests, NULL, NULL); }
1a4d0564b941ddf35e8ac4a169a927f5d0ba443e
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/sock/nointernet.c
7af468530136e637559f8bfd68d04274555bd2c9
[ "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
11,869
c
nointernet.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/bpf.internal.h" #include "libc/calls/struct/filter.internal.h" #include "libc/calls/struct/seccomp.internal.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/likely.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/msghdr.h" #include "libc/sock/struct/sockaddr.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/audit.h" #include "libc/sysv/consts/nr.h" #include "libc/sysv/consts/nrlinux.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/ptrace.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" #include "net/http/ip.h" #ifdef __x86_64__ #define ORIG_RAX 120 #define RAX 80 #define RDI 112 #define RSI 104 #define RDX 96 #define R8 72 #define R9 64 #define __WALL 0x40000000 #define OFF(f) offsetof(struct seccomp_data, f) #if 0 #define DEBUG(...) kprintf(__VA_ARGS__) #else #define DEBUG(...) donothing #endif #define ORDIE(x) \ do { \ if (UNLIKELY((x) == -1)) { \ DEBUG("%s:%d: %s failed %m\n", __FILE__, __LINE__, #x); \ notpossible; \ } \ } while (0) static const struct sock_filter kInetBpf[] = { // cargo culted architecture assertion BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)), BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS), // block system calls from the future BPF_STMT(BPF_LD + BPF_W + BPF_ABS, OFF(nr)), BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_linux_memfd_secret, 0, 1), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 38), // ENOSYS // only allow local and internet sockets BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_socket, 0, 5), BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])), BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x001, 2, 0), // AF_UNIX BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x002, 1, 0), // AF_INET BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 1), // EPERM BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)), // support for these not implemented yet BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x133, 0, 1), // sendmmsg BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | 1), // EPERM // trace syscalls with struct sockaddr BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02e, 3, 0), // sendmsg BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02c, 2, 0), // sendto BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x031, 1, 0), // bind BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02a, 0, 1), // connect BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRACE), // default course of action BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW), }; static int PeekData(int pid, long addr, void *buf, size_t size) { long i, j, w; for (i = 0; i < size; i += sizeof(long)) { if (sys_ptrace(PTRACE_PEEKTEXT, pid, addr + i, &w) != -1) { for (j = 0; i + j < size && j < sizeof(long); ++j) { ((char *)buf)[i + j] = w; w >>= 8; } } else { return -1; } } return 0; } static void LogProcessEvent(int main, int pid, int ws) { DEBUG("trace: %s%06d%s 0x%06x", // pid == main ? "\e[31;1m" : "", // pid, // pid == main ? "\e[0m" : "", // ws); if (WIFEXITED(ws)) { DEBUG(" exit %d", WEXITSTATUS(ws)); } if (WIFSIGNALED(ws)) { DEBUG(" sig %d", WTERMSIG(ws)); } if (WIFSTOPPED(ws)) { DEBUG(" stop %s %s", strsignal(WSTOPSIG(ws)), DescribePtraceEvent((ws & 0xff0000) >> 16)); } if (WIFCONTINUED(ws)) { DEBUG(" cont"); } if (WCOREDUMP(ws)) { DEBUG(" core"); } DEBUG("\n"); } static int Raise(int sig) { sigset_t mask; sigaction(sig, &(struct sigaction){0}, 0); sigfillset(&mask); sigprocmask(SIG_SETMASK, &mask, 0); kill(getpid(), sig); sigdelset(&mask, sig); sigprocmask(SIG_SETMASK, &mask, 0); _Exit(128 + sig); } static bool IsSockaddrAllowed(struct sockaddr_storage *addr) { uint32_t ip; if (addr->ss_family == AF_UNIX) { return true; } if (addr->ss_family == AF_INET) { ip = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr); if (IsPrivateIp(ip) || IsLoopbackIp(ip)) { return true; } else { kprintf("warning: attempted to communicate with public ip " "%hhd.%hhd.%hhd.%hhd\n", ip >> 24, ip >> 16, ip >> 8, ip); return false; } } DEBUG("bad family %d\n", addr->ss_family); return false; } static void OnSockaddrSyscall(int pid, int r1, int r2) { long si, dx; uint32_t addrlen; struct sockaddr_storage addr = {0}; ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, r1, &si)); ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, r2, &dx)); addrlen = dx; if (!si) { // if address isn't supplied, it's probably safe. for example, // send() is implemented in cosmo using sendto() with 0/0 addr return; } if (PeekData(pid, si, &addr, MIN(addrlen, sizeof(addr))) == -1) { DEBUG("failed to peek addr\n"); // probably an efault goto Deny; } if (IsSockaddrAllowed(&addr)) { return; } else { goto Deny; } Deny: ORDIE(sys_ptrace(PTRACE_POKEUSER, pid, ORIG_RAX, -1)); } static void OnSendmsg(int pid) { long si; struct msghdr msg = {0}; struct sockaddr_storage addr = {0}; ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, RSI, &si)); if (PeekData(pid, si, &msg, sizeof(msg)) == -1) { DEBUG("failed to peek msg\n"); // probably an efault goto Deny; } if (!msg.msg_name) { // if address isn't supplied, it's probably fine. return; } if (PeekData(pid, (long)msg.msg_name, &addr, MIN(msg.msg_namelen, sizeof(addr))) == -1) { DEBUG("failed to peek msg name\n"); // probably an efault goto Deny; } if (IsSockaddrAllowed(&addr)) { return; } else { goto Deny; } Deny: ORDIE(sys_ptrace(PTRACE_POKEUSER, pid, ORIG_RAX, -1)); } static void HandleSeccompTrace(int pid) { long ax; ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX, &ax)); switch (ax) { case 0x031: // bind case 0x02a: // connect OnSockaddrSyscall(pid, RSI, RDX); break; case 0x02c: // sendto OnSockaddrSyscall(pid, R8, R9); break; case 0x02e: // sendmsg OnSendmsg(pid); break; default: break; } } static int WaitForTrace(int main) { int ws, pid; for (;;) { // waits for state change on any child process or thread // eintr isn't possible since we're blocking all signals ORDIE(pid = waitpid(-1, &ws, __WALL)); LogProcessEvent(main, pid, ws); if (WIFEXITED(ws)) { if (pid == main) { _Exit(WEXITSTATUS(ws)); } } else if (WIFSIGNALED(ws)) { if (pid == main) { Raise(WTERMSIG(ws)); } } else if (WIFSTOPPED(ws)) { if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) { return pid; } else if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_EXEC << 8))) { ORDIE(ptrace(PTRACE_CONT, pid, 0, 0)); } else if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) || (ws >> 8) == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) || (ws >> 8) == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) { ORDIE(ptrace(PTRACE_CONT, pid, 0, 0)); } else { ORDIE(ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(ws))); } } } } /** * Disables internet access. * * Warning: This function uses ptrace to react to seccomp filter events. * This approach is effective, but it's not bulletproof, since a highly * motivated attacker could theoretically use threads to modify sockaddr * in the short time between it being monitored and the actual syscall. */ int nointernet(void) { int ws, act, main; sigset_t set, old; struct sock_fprog prog = {.filter = kInetBpf, .len = ARRAYLEN(kInetBpf)}; // seccomp bpf and ptrace are pretty much just linux for now. if (!IsLinux() || !__is_linux_2_6_23()) { return enosys(); } // prevent crash handlers from intercepting sigsegv ORDIE(sigfillset(&set)); ORDIE(sigprocmask(SIG_SETMASK, &set, &old)); // create traced child that'll replace this program if ((main = fork()) == -1) { ORDIE(sigprocmask(SIG_SETMASK, &old, 0)); return -1; } if (!main) { if (sys_ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) { // there can be only one // throw sigsegv on eperm // we're already being traced asm("hlt"); } prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); ORDIE(prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)); ORDIE(kill(getpid(), SIGSTOP)); ORDIE(sigprocmask(SIG_SETMASK, &old, 0)); // return to caller from child return 0; } // wait for child to stop itself ORDIE(waitpid(main, &ws, 0)); if (WIFSIGNALED(ws)) { // child couldn't enable ptrace or seccomp sigprocmask(SIG_SETMASK, &old, 0); return eperm(); } npassert(WIFSTOPPED(ws)); // parent process becomes monitor of subprocess tree. all signals // continue to be blocked since we assume they'll also be sent to // children, which will die, and then the monitor dies afterwards ORDIE(sys_ptrace(PTRACE_SETOPTIONS, main, 0, PTRACE_O_TRACESECCOMP | PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC)); for (act = main;;) { ORDIE(sys_ptrace(PTRACE_CONT, act, 0, 0)); act = WaitForTrace(main); HandleSeccompTrace(act); } } #endif /* __x86_64__ */
9241c565462e83b421355b5ac7481ab4eed3d782
1d8079c36ae47e832628e9b14b299f77f2ce4479
/c/fp12.c
e47ba252d1016e209e2391df357d1c71ac04da0c
[ "Apache-2.0" ]
permissive
miracl/core
1a71fe148426c6da453b1ccfe373143abcd4d46a
ec77b2817a0e360b1893affe4cfa44d19391efc7
refs/heads/master
2023-06-26T12:39:05.526122
2023-06-12T11:55:42
2023-06-12T11:55:42
189,997,925
182
74
Apache-2.0
2023-04-06T07:42:02
2019-06-03T12:09:24
C++
UTF-8
C
false
false
25,000
c
fp12.c
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * 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. */ /* CORE Fp^12 functions */ /* SU=m, m is Stack Usage (no lazy )*/ /* FP12 elements are of the form a+i.b+i^2.c */ #include "fp12_YYY.h" #include "config_curve_ZZZ.h" /* return 1 if b==c, no branching */ static int teq(sign32 b, sign32 c) { sign32 x = b ^ c; x -= 1; // if x=0, x now -1 return (int)((x >> 31) & 1); } /* Constant time select from pre-computed table */ static void FP12_YYY_select(FP12_YYY *f, FP12_YYY g[], sign32 b) { FP12_YYY invf; sign32 m = b >> 31; sign32 babs = (b ^ m) - m; babs = (babs - 1) / 2; FP12_YYY_cmove(f, &g[0], teq(babs, 0)); // conditional move FP12_YYY_cmove(f, &g[1], teq(babs, 1)); FP12_YYY_cmove(f, &g[2], teq(babs, 2)); FP12_YYY_cmove(f, &g[3], teq(babs, 3)); FP12_YYY_cmove(f, &g[4], teq(babs, 4)); FP12_YYY_cmove(f, &g[5], teq(babs, 5)); FP12_YYY_cmove(f, &g[6], teq(babs, 6)); FP12_YYY_cmove(f, &g[7], teq(babs, 7)); FP12_YYY_copy(&invf, f); FP12_YYY_conj(&invf, &invf); // 1/f FP12_YYY_cmove(f, &invf, (int)(m & 1)); } /* test x==0 ? */ /* SU= 8 */ int FP12_YYY_iszilch(FP12_YYY *x) { if (FP4_YYY_iszilch(&(x->a)) && FP4_YYY_iszilch(&(x->b)) && FP4_YYY_iszilch(&(x->c))) return 1; return 0; } /* test x==1 ? */ /* SU= 8 */ int FP12_YYY_isunity(FP12_YYY *x) { if (FP4_YYY_isunity(&(x->a)) && FP4_YYY_iszilch(&(x->b)) && FP4_YYY_iszilch(&(x->c))) return 1; return 0; } /* FP12 copy w=x */ /* SU= 16 */ void FP12_YYY_copy(FP12_YYY *w, FP12_YYY *x) { if (x == w) return; FP4_YYY_copy(&(w->a), &(x->a)); FP4_YYY_copy(&(w->b), &(x->b)); FP4_YYY_copy(&(w->c), &(x->c)); w->type = x->type; } /* FP12 w=1 */ /* SU= 8 */ void FP12_YYY_one(FP12_YYY *w) { FP4_YYY_one(&(w->a)); FP4_YYY_zero(&(w->b)); FP4_YYY_zero(&(w->c)); w->type = FP_UNITY; } void FP12_YYY_zero(FP12_YYY *w) { FP4_YYY_zero(&(w->a)); FP4_YYY_zero(&(w->b)); FP4_YYY_zero(&(w->c)); w->type = FP_ZILCH; } /* return 1 if x==y, else 0 */ /* SU= 16 */ int FP12_YYY_equals(FP12_YYY *x, FP12_YYY *y) { if (FP4_YYY_equals(&(x->a), &(y->a)) && FP4_YYY_equals(&(x->b), &(y->b)) && FP4_YYY_equals(&(x->c), &(y->c))) return 1; return 0; } /* Set w=conj(x) */ /* SU= 8 */ void FP12_YYY_conj(FP12_YYY *w, FP12_YYY *x) { FP12_YYY_copy(w, x); FP4_YYY_conj(&(w->a), &(w->a)); FP4_YYY_nconj(&(w->b), &(w->b)); FP4_YYY_conj(&(w->c), &(w->c)); } /* Create FP12 from FP4 */ /* SU= 8 */ void FP12_YYY_from_FP4(FP12_YYY *w, FP4_YYY *a) { FP4_YYY_copy(&(w->a), a); FP4_YYY_zero(&(w->b)); FP4_YYY_zero(&(w->c)); w->type = FP_SPARSEST; } /* Create FP12 from 3 FP4's */ /* SU= 16 */ void FP12_YYY_from_FP4s(FP12_YYY *w, FP4_YYY *a, FP4_YYY *b, FP4_YYY *c) { FP4_YYY_copy(&(w->a), a); FP4_YYY_copy(&(w->b), b); FP4_YYY_copy(&(w->c), c); w->type = FP_DENSE; } /* Granger-Scott Unitary Squaring. This does not benefit from lazy reduction */ /* SU= 600 */ void FP12_YYY_usqr(FP12_YYY *w, FP12_YYY *x) { FP4_YYY A, B, C, D; FP4_YYY_copy(&A, &(x->a)); FP4_YYY_sqr(&(w->a), &(x->a)); FP4_YYY_add(&D, &(w->a), &(w->a)); FP4_YYY_add(&(w->a), &D, &(w->a)); FP4_YYY_norm(&(w->a)); FP4_YYY_nconj(&A, &A); FP4_YYY_add(&A, &A, &A); FP4_YYY_add(&(w->a), &(w->a), &A); FP4_YYY_sqr(&B, &(x->c)); FP4_YYY_times_i(&B); FP4_YYY_add(&D, &B, &B); FP4_YYY_add(&B, &B, &D); FP4_YYY_norm(&B); FP4_YYY_sqr(&C, &(x->b)); FP4_YYY_add(&D, &C, &C); FP4_YYY_add(&C, &C, &D); FP4_YYY_norm(&C); FP4_YYY_conj(&(w->b), &(x->b)); FP4_YYY_add(&(w->b), &(w->b), &(w->b)); FP4_YYY_nconj(&(w->c), &(x->c)); FP4_YYY_add(&(w->c), &(w->c), &(w->c)); FP4_YYY_add(&(w->b), &B, &(w->b)); FP4_YYY_add(&(w->c), &C, &(w->c)); w->type = FP_DENSE; FP12_YYY_reduce(w); /* reduce here as in pow function repeated squarings would trigger multiple reductions */ } /* FP12 squaring w=x^2 */ /* SU= 600 */ void FP12_YYY_sqr(FP12_YYY *w, FP12_YYY *x) { /* Use Chung-Hasan SQR2 method from http://cacr.uwaterloo.ca/techreports/2006/cacr2006-24.pdf */ FP4_YYY A, B, C, D; if (x->type <= FP_UNITY) { FP12_YYY_copy(w, x); return; } FP4_YYY_sqr(&A, &(x->a)); FP4_YYY_mul(&B, &(x->b), &(x->c)); FP4_YYY_add(&B, &B, &B); FP4_YYY_norm(&B); FP4_YYY_sqr(&C, &(x->c)); FP4_YYY_mul(&D, &(x->a), &(x->b)); FP4_YYY_add(&D, &D, &D); FP4_YYY_add(&(w->c), &(x->a), &(x->c)); FP4_YYY_add(&(w->c), &(x->b), &(w->c)); FP4_YYY_norm(&(w->c)); FP4_YYY_sqr(&(w->c), &(w->c)); FP4_YYY_copy(&(w->a), &A); FP4_YYY_add(&A, &A, &B); FP4_YYY_norm(&A); FP4_YYY_add(&A, &A, &C); FP4_YYY_add(&A, &A, &D); FP4_YYY_norm(&A); FP4_YYY_neg(&A, &A); FP4_YYY_times_i(&B); FP4_YYY_times_i(&C); FP4_YYY_add(&(w->a), &(w->a), &B); FP4_YYY_add(&(w->b), &C, &D); FP4_YYY_add(&(w->c), &(w->c), &A); if (x->type == FP_SPARSER || x->type == FP_SPARSEST) w->type = FP_SPARSE; else w->type = FP_DENSE; FP12_YYY_norm(w); } /* FP12 full multiplication w=w*y */ /* SU= 896 */ /* FP12 full multiplication w=w*y */ void FP12_YYY_mul(FP12_YYY *w, FP12_YYY *y) { FP4_YYY z0, z1, z2, z3, t0, t1; FP4_YYY_mul(&z0, &(w->a), &(y->a)); FP4_YYY_mul(&z2, &(w->b), &(y->b)); // FP4_YYY_add(&t0, &(w->a), &(w->b)); FP4_YYY_add(&t1, &(y->a), &(y->b)); // FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&z1, &t0, &t1); FP4_YYY_add(&t0, &(w->b), &(w->c)); FP4_YYY_add(&t1, &(y->b), &(y->c)); // FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&z3, &t0, &t1); FP4_YYY_neg(&t0, &z0); FP4_YYY_neg(&t1, &z2); FP4_YYY_add(&z1, &z1, &t0); // z1=z1-z0 FP4_YYY_add(&(w->b), &z1, &t1); // z1=z1-z2 FP4_YYY_add(&z3, &z3, &t1); // z3=z3-z2 FP4_YYY_add(&z2, &z2, &t0); // z2=z2-z0 FP4_YYY_add(&t0, &(w->a), &(w->c)); FP4_YYY_add(&t1, &(y->a), &(y->c)); FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&t0, &t1, &t0); FP4_YYY_add(&z2, &z2, &t0); FP4_YYY_mul(&t0, &(w->c), &(y->c)); FP4_YYY_neg(&t1, &t0); FP4_YYY_add(&(w->c), &z2, &t1); FP4_YYY_add(&z3, &z3, &t1); FP4_YYY_times_i(&t0); FP4_YYY_add(&(w->b), &(w->b), &t0); FP4_YYY_norm(&z3); FP4_YYY_times_i(&z3); FP4_YYY_add(&(w->a), &z0, &z3); w->type = FP_DENSE; FP12_YYY_norm(w); } /* FP12 full multiplication w=w*y */ /* Supports sparse multiplicands */ /* Usually w is denser than y */ void FP12_YYY_ssmul(FP12_YYY *w, FP12_YYY *y) { FP4_YYY z0, z1, z2, z3, t0, t1; if (w->type == FP_UNITY) { FP12_YYY_copy(w, y); return; } if (y->type == FP_UNITY) return; if (y->type >= FP_SPARSE) { FP4_YYY_mul(&z0, &(w->a), &(y->a)); // xa.ya always 11x11 #if SEXTIC_TWIST_ZZZ == M_TYPE if (y->type == FP_SPARSE || w->type == FP_SPARSE) { FP2_YYY_mul(&z2.b, &(w->b).b, &(y->b).b); FP2_YYY_zero(&z2.a); if (y->type != FP_SPARSE) FP2_YYY_mul(&z2.a, &(w->b).b, &(y->b).a); if (w->type != FP_SPARSE) FP2_YYY_mul(&z2.a, &(w->b).a, &(y->b).b); FP4_YYY_times_i(&z2); } else #endif FP4_YYY_mul(&z2, &(w->b), &(y->b)); // xb.yb could be 00x00 or 01x01 or or 10x10 or 11x00 or 11x10 or 11x01 or 11x11 FP4_YYY_add(&t0, &(w->a), &(w->b)); // (xa+xb) FP4_YYY_add(&t1, &(y->a), &(y->b)); // (ya+yb) FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&z1, &t0, &t1); // (xa+xb)(ya+yb) always 11x11 FP4_YYY_add(&t0, &(w->b), &(w->c)); // (xb+xc) FP4_YYY_add(&t1, &(y->b), &(y->c)); // (yb+yc) FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&z3, &t0, &t1); // (xb+xc)(yb+yc) could be anything... FP4_YYY_neg(&t0, &z0); // -(xa.ya) FP4_YYY_neg(&t1, &z2); // -(xb.yb) FP4_YYY_add(&z1, &z1, &t0); FP4_YYY_add(&(w->b), &z1, &t1); // /wb = (xa+xb)(ya+yb) -(xa.ya) -(xb.yb) = xa.yb + xb.ya FP4_YYY_add(&z3, &z3, &t1); // (xb+xc)(yb+yc) -(xb.yb) FP4_YYY_add(&z2, &z2, &t0); // (xb.yb) - (xa.ya) FP4_YYY_add(&t0, &(w->a), &(w->c)); // (xa+xc) FP4_YYY_add(&t1, &(y->a), &(y->c)); // (ya+yc) FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&t0, &t1, &t0); // (xa+xc)(ya+yc) always 11x11 FP4_YYY_add(&z2, &z2, &t0); // (xb.yb) - (xa.ya) + (xa+xc)(ya+yc) #if SEXTIC_TWIST_ZZZ == D_TYPE if (y->type == FP_SPARSE || w->type == FP_SPARSE) { FP2_YYY_mul(&t0.a, &(w->c).a, &(y->c).a); FP2_YYY_zero(&t0.b); if (y->type != FP_SPARSE) FP2_YYY_mul(&t0.b, &(w->c).a, &(y->c).b); if (w->type != FP_SPARSE) FP2_YYY_mul(&t0.b, &(w->c).b, &(y->c).a); } else #endif FP4_YYY_mul(&t0, &(w->c), &(y->c)); // (xc.yc) could be anything FP4_YYY_neg(&t1, &t0); // -(xc.yc) FP4_YYY_add(&(w->c), &z2, &t1); // wc = (xb.yb) - (xa.ya) + (xa+xc)(ya+yc) - (xc.yc) = xb.yb + xc.ya + xa.yc FP4_YYY_add(&z3, &z3, &t1); // (xb+xc)(yb+yc) -(xb.yb) - (xc.yc) = xb.yc + xc.yb FP4_YYY_times_i(&t0); // i.(xc.yc) FP4_YYY_add(&(w->b), &(w->b), &t0); // wb = (xa+xb)(ya+yb) -(xa.ya) -(xb.yb) +i(xc.yc) FP4_YYY_norm(&z3); FP4_YYY_times_i(&z3); // i[(xb+xc)(yb+yc) -(xb.yb) - (xc.yc)] = i(xb.yc + xc.yb) FP4_YYY_add(&(w->a), &z0, &z3); // wa = xa.ya + i(xb.yc + xc.yb) } else { if (w->type == FP_SPARSER || w->type == FP_SPARSEST) { FP12_YYY_smul(w, y); return; } // dense by sparser - 13m #if SEXTIC_TWIST_ZZZ == D_TYPE FP4_YYY_copy(&z3, &(w->b)); FP4_YYY_mul(&z0, &(w->a), &(y->a)); if (y->type == FP_SPARSEST) FP4_YYY_qmul(&z2, &(w->b), &(y->b).a.a); else FP4_YYY_pmul(&z2, &(w->b), &(y->b).a); FP4_YYY_add(&(w->b), &(w->a), &(w->b)); FP4_YYY_copy(&t1, &(y->a)); FP2_YYY_add(&t1.a, &t1.a, &(y->b).a); FP4_YYY_norm(&t1); FP4_YYY_norm(&(w->b)); FP4_YYY_mul(&(w->b), &(w->b), &t1); FP4_YYY_add(&z3, &z3, &(w->c)); FP4_YYY_norm(&z3); if (y->type == FP_SPARSEST) FP4_YYY_qmul(&z3, &z3, &(y->b).a.a); else FP4_YYY_pmul(&z3, &z3, &(y->b).a); FP4_YYY_neg(&t0, &z0); FP4_YYY_neg(&t1, &z2); FP4_YYY_add(&(w->b), &(w->b), &t0); // z1=z1-z0 FP4_YYY_add(&(w->b), &(w->b), &t1); // z1=z1-z2 FP4_YYY_add(&z3, &z3, &t1); // z3=z3-z2 FP4_YYY_add(&z2, &z2, &t0); // z2=z2-z0 FP4_YYY_add(&t0, &(w->a), &(w->c)); FP4_YYY_norm(&t0); FP4_YYY_norm(&z3); FP4_YYY_mul(&t0, &(y->a), &t0); FP4_YYY_add(&(w->c), &z2, &t0); FP4_YYY_times_i(&z3); FP4_YYY_add(&(w->a), &z0, &z3); #endif #if SEXTIC_TWIST_ZZZ == M_TYPE FP4_YYY_mul(&z0, &(w->a), &(y->a)); FP4_YYY_add(&t0, &(w->a), &(w->b)); FP4_YYY_norm(&t0); FP4_YYY_mul(&z1, &t0, &(y->a)); FP4_YYY_add(&t0, &(w->b), &(w->c)); FP4_YYY_norm(&t0); if (y->type == FP_SPARSEST) FP4_YYY_qmul(&z3, &t0, &(y->c).b.a); else FP4_YYY_pmul(&z3, &t0, &(y->c).b); FP4_YYY_times_i(&z3); FP4_YYY_neg(&t0, &z0); FP4_YYY_add(&z1, &z1, &t0); // z1=z1-z0 FP4_YYY_copy(&(w->b), &z1); FP4_YYY_copy(&z2, &t0); FP4_YYY_add(&t0, &(w->a), &(w->c)); FP4_YYY_add(&t1, &(y->a), &(y->c)); FP4_YYY_norm(&t0); FP4_YYY_norm(&t1); FP4_YYY_mul(&t0, &t1, &t0); FP4_YYY_add(&z2, &z2, &t0); if (y->type == FP_SPARSEST) FP4_YYY_qmul(&t0, &(w->c), &(y->c).b.a); else FP4_YYY_pmul(&t0, &(w->c), &(y->c).b); FP4_YYY_times_i(&t0); FP4_YYY_neg(&t1, &t0); FP4_YYY_times_i(&t0); FP4_YYY_add(&(w->c), &z2, &t1); FP4_YYY_add(&z3, &z3, &t1); FP4_YYY_add(&(w->b), &(w->b), &t0); FP4_YYY_norm(&z3); FP4_YYY_times_i(&z3); FP4_YYY_add(&(w->a), &z0, &z3); #endif } w->type = FP_DENSE; FP12_YYY_norm(w); } /* FP12 multiplication w=w*y */ /* catering for special case that arises from special form of ATE pairing line function */ /* w and y are both sparser line functions - cost = 6m */ void FP12_YYY_smul(FP12_YYY *w, FP12_YYY *y) { FP2_YYY w1, w2, w3, ta, tb, tc, td, te, t; // if (type==D_TYPE) // { #if SEXTIC_TWIST_ZZZ == D_TYPE FP2_YYY_mul(&w1, &(w->a).a, &(y->a).a); // A1.A2 FP2_YYY_mul(&w2, &(w->a).b, &(y->a).b); // B1.B2 if (y->type == FP_SPARSEST || w->type == FP_SPARSEST) { if (y->type == FP_SPARSEST && w->type == FP_SPARSEST) { FP_YYY_mul(&w3.a, &(w->b).a.a, &(y->b).a.a); FP_YYY_zero(&w3.b); } else { if (y->type != FP_SPARSEST) FP2_YYY_pmul(&w3, &(y->b).a, &(w->b).a.a); if (w->type != FP_SPARSEST) FP2_YYY_pmul(&w3, &(w->b).a, &(y->b).a.a); } } else FP2_YYY_mul(&w3, &(w->b).a, &(y->b).a); // C1.C2 FP2_YYY_add(&ta, &(w->a).a, &(w->a).b); // A1+B1 FP2_YYY_add(&tb, &(y->a).a, &(y->a).b); // A2+B2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&tc, &ta, &tb); // (A1+B1)(A2+B2) FP2_YYY_add(&t, &w1, &w2); FP2_YYY_neg(&t, &t); FP2_YYY_add(&tc, &tc, &t); // (A1+B1)(A2+B2)-A1.A2-B1*B2 = (A1.B2+A2.B1) FP2_YYY_add(&ta, &(w->a).a, &(w->b).a); // A1+C1 FP2_YYY_add(&tb, &(y->a).a, &(y->b).a); // A2+C2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&td, &ta, &tb); // (A1+C1)(A2+C2) FP2_YYY_add(&t, &w1, &w3); FP2_YYY_neg(&t, &t); FP2_YYY_add(&td, &td, &t); // (A1+C1)(A2+C2)-A1.A2-C1*C2 = (A1.C2+A2.C1) FP2_YYY_add(&ta, &(w->a).b, &(w->b).a); // B1+C1 FP2_YYY_add(&tb, &(y->a).b, &(y->b).a); // B2+C2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&te, &ta, &tb); // (B1+C1)(B2+C2) FP2_YYY_add(&t, &w2, &w3); FP2_YYY_neg(&t, &t); FP2_YYY_add(&te, &te, &t); // (B1+C1)(B2+C2)-B1.B2-C1*C2 = (B1.C2+B2.C1) FP2_YYY_mul_ip(&w2); FP2_YYY_add(&w1, &w1, &w2); FP4_YYY_from_FP2s(&(w->a), &w1, &tc); FP4_YYY_from_FP2s(&(w->b), &td, &te); // only norm these 2 FP4_YYY_from_FP2(&(w->c), &w3); FP4_YYY_norm(&(w->a)); FP4_YYY_norm(&(w->b)); #endif // } else { #if SEXTIC_TWIST_ZZZ == M_TYPE FP2_YYY_mul(&w1, &(w->a).a, &(y->a).a); // A1.A2 FP2_YYY_mul(&w2, &(w->a).b, &(y->a).b); // B1.B2 if (y->type == FP_SPARSEST || w->type == FP_SPARSEST) { if (y->type == FP_SPARSEST && w->type == FP_SPARSEST) { FP_YYY_mul(&w3.a, &(w->c).b.a, &(y->c).b.a); FP_YYY_zero(&w3.b); } else { if (y->type != FP_SPARSEST) FP2_YYY_pmul(&w3, &(y->c).b, &(w->c).b.a); if (w->type != FP_SPARSEST) FP2_YYY_pmul(&w3, &(w->c).b, &(y->c).b.a); } } else FP2_YYY_mul(&w3, &(w->c).b, &(y->c).b); // F1.F2 FP2_YYY_add(&ta, &(w->a).a, &(w->a).b); // A1+B1 FP2_YYY_add(&tb, &(y->a).a, &(y->a).b); // A2+B2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&tc, &ta, &tb); // (A1+B1)(A2+B2) FP2_YYY_add(&t, &w1, &w2); FP2_YYY_neg(&t, &t); FP2_YYY_add(&tc, &tc, &t); // (A1+B1)(A2+B2)-A1.A2-B1*B2 = (A1.B2+A2.B1) FP2_YYY_add(&ta, &(w->a).a, &(w->c).b); // A1+F1 FP2_YYY_add(&tb, &(y->a).a, &(y->c).b); // A2+F2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&td, &ta, &tb); // (A1+F1)(A2+F2) FP2_YYY_add(&t, &w1, &w3); FP2_YYY_neg(&t, &t); FP2_YYY_add(&td, &td, &t); // (A1+F1)(A2+F2)-A1.A2-F1*F2 = (A1.F2+A2.F1) FP2_YYY_add(&ta, &(w->a).b, &(w->c).b); // B1+F1 FP2_YYY_add(&tb, &(y->a).b, &(y->c).b); // B2+F2 FP2_YYY_norm(&ta); FP2_YYY_norm(&tb); FP2_YYY_mul(&te, &ta, &tb); // (B1+F1)(B2+F2) FP2_YYY_add(&t, &w2, &w3); FP2_YYY_neg(&t, &t); FP2_YYY_add(&te, &te, &t); // (B1+F1)(B2+F2)-B1.B2-F1*F2 = (B1.F2+B2.F1) FP2_YYY_mul_ip(&w2); FP2_YYY_add(&w1, &w1, &w2); FP4_YYY_from_FP2s(&(w->a), &w1, &tc); FP2_YYY_mul_ip(&w3); FP2_YYY_norm(&w3); FP4_YYY_from_FP2H(&(w->b), &w3); FP2_YYY_norm(&te); FP2_YYY_mul_ip(&te); FP4_YYY_from_FP2s(&(w->c), &te, &td); FP4_YYY_norm(&(w->a)); FP4_YYY_norm(&(w->c)); #endif // } w->type = FP_SPARSE; } /* Set w=1/x */ /* SU= 600 */ void FP12_YYY_inv(FP12_YYY *w, FP12_YYY *x) { FP4_YYY f0, f1, f2, f3; FP4_YYY_sqr(&f0, &(x->a)); FP4_YYY_mul(&f1, &(x->b), &(x->c)); FP4_YYY_times_i(&f1); FP4_YYY_sub(&f0, &f0, &f1); /* y.a */ FP4_YYY_norm(&f0); FP4_YYY_sqr(&f1, &(x->c)); FP4_YYY_times_i(&f1); FP4_YYY_mul(&f2, &(x->a), &(x->b)); FP4_YYY_sub(&f1, &f1, &f2); /* y.b */ FP4_YYY_norm(&f1); FP4_YYY_sqr(&f2, &(x->b)); FP4_YYY_mul(&f3, &(x->a), &(x->c)); FP4_YYY_sub(&f2, &f2, &f3); /* y.c */ FP4_YYY_norm(&f2); FP4_YYY_mul(&f3, &(x->b), &f2); FP4_YYY_times_i(&f3); FP4_YYY_mul(&(w->a), &f0, &(x->a)); FP4_YYY_add(&f3, &(w->a), &f3); FP4_YYY_mul(&(w->c), &f1, &(x->c)); FP4_YYY_times_i(&(w->c)); FP4_YYY_add(&f3, &(w->c), &f3); FP4_YYY_norm(&f3); FP4_YYY_inv(&f3, &f3, NULL); FP4_YYY_mul(&(w->a), &f0, &f3); FP4_YYY_mul(&(w->b), &f1, &f3); FP4_YYY_mul(&(w->c), &f2, &f3); w->type = FP_DENSE; } /* constant time powering by small integer of max length bts */ void FP12_YYY_pinpow(FP12_YYY *r, int e, int bts) { int i, b; FP12_YYY R[2]; FP12_YYY_one(&R[0]); FP12_YYY_copy(&R[1], r); for (i = bts - 1; i >= 0; i--) { b = (e >> i) & 1; FP12_YYY_mul(&R[1 - b], &R[b]); FP12_YYY_usqr(&R[b], &R[b]); } FP12_YYY_copy(r, &R[0]); } /* Compressed powering of unitary elements y=x^(e mod r) */ void FP12_YYY_compow(FP4_YYY *c, FP12_YYY *x, BIG_XXX e, BIG_XXX r) { FP12_YYY g1, g2; FP4_YYY cp, cpm1, cpm2; FP2_YYY f; BIG_XXX q, a, b, m; BIG_XXX_rcopy(a, Fra_YYY); BIG_XXX_rcopy(b, Frb_YYY); FP2_YYY_from_BIGs(&f, a, b); BIG_XXX_rcopy(q, Modulus_YYY); FP12_YYY_copy(&g1, x); FP12_YYY_copy(&g2, x); BIG_XXX_copy(m, q); BIG_XXX_mod(m, r); BIG_XXX_copy(a, e); BIG_XXX_mod(a, m); BIG_XXX_copy(b, e); BIG_XXX_sdiv(b, m); FP12_YYY_trace(c, &g1); if (BIG_XXX_iszilch(b)) { FP4_YYY_xtr_pow(c, c, e); return; } FP12_YYY_frob(&g2, &f); FP12_YYY_trace(&cp, &g2); FP12_YYY_conj(&g1, &g1); FP12_YYY_mul(&g2, &g1); FP12_YYY_trace(&cpm1, &g2); FP12_YYY_mul(&g2, &g1); FP12_YYY_trace(&cpm2, &g2); FP4_YYY_xtr_pow2(c, &cp, c, &cpm1, &cpm2, a, b); } /* SU= 528 */ /* set r=a^b */ /* Note this is simple square and multiply, so not side-channel safe */ void FP12_YYY_pow(FP12_YYY *r, FP12_YYY *a, BIG_XXX b) { FP12_YYY w, sf; BIG_XXX b1, b3; int i, nb, bt; BIG_XXX_copy(b1, b); BIG_XXX_norm(b1); BIG_XXX_pmul(b3, b1, 3); BIG_XXX_norm(b3); FP12_YYY_copy(&sf, a); FP12_YYY_norm(&sf); FP12_YYY_copy(&w, &sf); if (BIG_XXX_iszilch(b3)) { FP12_YYY_one(r); return; } nb = BIG_XXX_nbits(b3); for (i = nb - 2; i >= 1; i--) { FP12_YYY_usqr(&w, &w); bt = BIG_XXX_bit(b3, i) - BIG_XXX_bit(b1, i); if (bt == 1) FP12_YYY_mul(&w, &sf); if (bt == -1) { FP12_YYY_conj(&sf, &sf); FP12_YYY_mul(&w, &sf); FP12_YYY_conj(&sf, &sf); } } FP12_YYY_copy(r, &w); FP12_YYY_reduce(r); } /* p=q0^u0.q1^u1.q2^u2.q3^u3 */ /* Side channel attack secure */ // Bos & Costello https://eprint.iacr.org/2013/458.pdf // Faz-Hernandez & Longa & Sanchez https://eprint.iacr.org/2013/158.pdf void FP12_YYY_pow4(FP12_YYY *p, FP12_YYY *q, BIG_XXX u[4]) { int i, j, k, nb, pb, bt; FP12_YYY g[8], r; BIG_XXX t[4], mt; sign8 w[NLEN_XXX * BASEBITS_XXX + 1]; sign8 s[NLEN_XXX * BASEBITS_XXX + 1]; for (i = 0; i < 4; i++) BIG_XXX_copy(t[i], u[i]); // Precomputed table FP12_YYY_copy(&g[0], &q[0]); // q[0] FP12_YYY_copy(&g[1], &g[0]); FP12_YYY_mul(&g[1], &q[1]); // q[0].q[1] FP12_YYY_copy(&g[2], &g[0]); FP12_YYY_mul(&g[2], &q[2]); // q[0].q[2] FP12_YYY_copy(&g[3], &g[1]); FP12_YYY_mul(&g[3], &q[2]); // q[0].q[1].q[2] FP12_YYY_copy(&g[4], &g[0]); FP12_YYY_mul(&g[4], &q[3]); // q[0].q[3] FP12_YYY_copy(&g[5], &g[1]); FP12_YYY_mul(&g[5], &q[3]); // q[0].q[1].q[3] FP12_YYY_copy(&g[6], &g[2]); FP12_YYY_mul(&g[6], &q[3]); // q[0].q[2].q[3] FP12_YYY_copy(&g[7], &g[3]); FP12_YYY_mul(&g[7], &q[3]); // q[0].q[1].q[2].q[3] // Make it odd pb = 1 - BIG_XXX_parity(t[0]); BIG_XXX_inc(t[0], pb); BIG_XXX_norm(t[0]); // Number of bits BIG_XXX_zero(mt); for (i = 0; i < 4; i++) { BIG_XXX_or(mt, mt, t[i]); } nb = 1 + BIG_XXX_nbits(mt); // Sign pivot s[nb - 1] = 1; for (i = 0; i < nb - 1; i++) { BIG_XXX_fshr(t[0], 1); s[i] = 2 * BIG_XXX_parity(t[0]) - 1; } // Recoded exponent for (i = 0; i < nb; i++) { w[i] = 0; k = 1; for (j = 1; j < 4; j++) { bt = s[i] * BIG_XXX_parity(t[j]); BIG_XXX_fshr(t[j], 1); BIG_XXX_dec(t[j], (bt >> 1)); BIG_XXX_norm(t[j]); w[i] += bt * k; k *= 2; } } // Main loop FP12_YYY_select(p, g, 2 * w[nb - 1] + 1); for (i = nb - 2; i >= 0; i--) { FP12_YYY_select(&r, g, 2 * w[i] + s[i]); FP12_YYY_usqr(p, p); FP12_YYY_mul(p, &r); } // apply correction FP12_YYY_conj(&r, &q[0]); FP12_YYY_mul(&r, p); FP12_YYY_cmove(p, &r, pb); FP12_YYY_reduce(p); } /* Set w=w^p using Frobenius */ /* SU= 160 */ void FP12_YYY_frob(FP12_YYY *w, FP2_YYY *f) { FP2_YYY f2, f3; FP2_YYY_sqr(&f2, f); /* f2=f^2 */ FP2_YYY_mul(&f3, &f2, f); /* f3=f^3 */ FP4_YYY_frob(&(w->a), &f3); FP4_YYY_frob(&(w->b), &f3); FP4_YYY_frob(&(w->c), &f3); FP4_YYY_pmul(&(w->b), &(w->b), f); FP4_YYY_pmul(&(w->c), &(w->c), &f2); w->type = FP_DENSE; } /* SU= 8 */ /* normalise all components of w */ void FP12_YYY_norm(FP12_YYY *w) { FP4_YYY_norm(&(w->a)); FP4_YYY_norm(&(w->b)); FP4_YYY_norm(&(w->c)); } /* SU= 8 */ /* reduce all components of w */ void FP12_YYY_reduce(FP12_YYY *w) { FP4_YYY_reduce(&(w->a)); FP4_YYY_reduce(&(w->b)); FP4_YYY_reduce(&(w->c)); } /* trace function w=trace(x) */ /* SU= 8 */ void FP12_YYY_trace(FP4_YYY *w, FP12_YYY *x) { FP4_YYY_imul(w, &(x->a), 3); FP4_YYY_reduce(w); } /* SU= 8 */ /* Output w in hex */ void FP12_YYY_output(FP12_YYY *w) { printf("["); FP4_YYY_output(&(w->a)); printf(","); FP4_YYY_output(&(w->b)); printf(","); FP4_YYY_output(&(w->c)); printf("]"); } /* SU= 64 */ /* Convert g to octet string w */ void FP12_YYY_toOctet(octet *W, FP12_YYY *g) { W->len = 12 * MODBYTES_XXX; FP4_YYY_toBytes(&(W->val[0]),&(g->c)); FP4_YYY_toBytes(&(W->val[4 * MODBYTES_XXX]),&(g->b)); FP4_YYY_toBytes(&(W->val[8 * MODBYTES_XXX]),&(g->a)); } /* SU= 24 */ /* Restore g from octet string w */ void FP12_YYY_fromOctet(FP12_YYY *g, octet *W) { FP4_YYY_fromBytes(&(g->c),&(W->val[0])); FP4_YYY_fromBytes(&(g->b),&(W->val[4 * MODBYTES_XXX])); FP4_YYY_fromBytes(&(g->a),&(W->val[8 * MODBYTES_XXX])); } /* Move b to a if d=1 */ void FP12_YYY_cmove(FP12_YYY *f, FP12_YYY *g, int d) { FP4_YYY_cmove(&(f->a), &(g->a), d); FP4_YYY_cmove(&(f->b), &(g->b), d); FP4_YYY_cmove(&(f->c), &(g->c), d); d = ~(d - 1); f->type ^= (f->type ^ g->type)&d; }
b2755b647084f0d7f12efc1abc13192078e864f1
549f66608f0cb4e50cee2e51c53206e798ab82cd
/test/Runtime/POSIX/Read1.c
72ad87ae69424057480697c645b816cde924090a
[ "NCSA" ]
permissive
klee/klee
c8da2f9668ee199af47cd2c784cea979017d7704
7082eafd05b4f268132ab94772c0243dbebf5087
refs/heads/master
2023-08-04T08:10:38.619540
2023-06-23T21:34:12
2023-07-21T09:00:02
11,568,417
2,339
679
NOASSERTION
2023-09-11T10:23:26
2013-07-21T22:03:03
C++
UTF-8
C
false
false
879
c
Read1.c
// RUN: %clang %s -emit-llvm %O0opt -c -o %t.bc // RUN: rm -rf %t.klee-out // RUN: %klee --output-dir=%t.klee-out --exit-on-error --posix-runtime %t.bc --sym-files 1 8 >%t.log #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <assert.h> int main(int argc, char** argv) { char buf[32]; // If count is zero, read() returns zero and has no other results. (man page) int x = read(0, 0, 0); assert(x == 0); int fd = open("A", O_RDONLY); assert(fd != -1); // EFAULT buf is outside your accessible address space. (man page) x = read(fd, 0, 1); assert(x == -1 && errno == EFAULT); // EBADF fd is not a valid file descriptor (man page) x = read(-1, buf, 1); assert(x == -1 && errno == EBADF); fd = open("A", O_RDONLY); assert(fd != -1); x = read(fd, buf, 1); assert(x == 1); }
685d33a8ce3cd29bf6864f64cdd734869f48e7ac
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/chip/mt_scp/clock.c
a6f1883d310eead1f18a7d4e029c5b9117983425
[ "BSD-3-Clause" ]
permissive
FrameworkComputer/EmbeddedController
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
f6d6b927eed71550d3475411cfc3e59abe5cef2a
refs/heads/hx20-hx30
2023-08-08T20:45:10.621169
2023-05-26T07:03:59
2023-05-26T07:03:59
447,021,040
846
48
BSD-3-Clause
2023-05-26T07:04:59
2022-01-12T00:11:14
C
UTF-8
C
false
false
9,548
c
clock.c
/* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Clocks, PLL and power settings */ #include "clock.h" #include "clock_chip.h" #include "common.h" #include "console.h" #include "registers.h" #include "task.h" #include "timer.h" #include "util.h" #define CPRINTF(format, args...) cprintf(CC_CLOCK, format, ## args) #define ULPOSC_DIV_MAX (1 << OSC_DIV_BITS) #define ULPOSC_CALI_MAX (1 << OSC_CALI_BITS) void clock_init(void) { /* Set VREQ to HW mode */ SCP_CPU_VREQ = CPU_VREQ_HW_MODE; SCP_SECURE_CTRL &= ~ENABLE_SPM_MASK_VREQ; /* Set DDREN auto mode */ SCP_SYS_CTRL |= AUTO_DDREN; /* Initialize 26MHz system clock counter reset value to 1. */ SCP_CLK_SYS_VAL = (SCP_CLK_SYS_VAL & ~CLK_SYS_VAL_MASK) | CLK_SYS_VAL(1); /* Initialize high frequency ULPOSC counter reset value to 1. */ SCP_CLK_HIGH_VAL = (SCP_CLK_HIGH_VAL & ~CLK_HIGH_VAL_MASK) | CLK_HIGH_VAL(1); /* Initialize sleep mode control VREQ counter. */ SCP_CLK_SLEEP_CTRL = (SCP_CLK_SLEEP_CTRL & ~VREQ_COUNTER_MASK) | VREQ_COUNTER_VAL(1); /* Set normal wake clock */ SCP_WAKE_CKSW &= ~WAKE_CKSW_SEL_NORMAL_MASK; /* Enable fast wakeup support */ SCP_CLK_SLEEP = 0; SCP_CLK_ON_CTRL = (SCP_CLK_ON_CTRL & ~HIGH_FINAL_VAL_MASK) | HIGH_FINAL_VAL_DEFAULT; SCP_FAST_WAKE_CNT_END = (SCP_FAST_WAKE_CNT_END & ~FAST_WAKE_CNT_END_MASK) | FAST_WAKE_CNT_END_DEFAULT; /* Set slow wake clock */ SCP_WAKE_CKSW = (SCP_WAKE_CKSW & ~WAKE_CKSW_SEL_SLOW_MASK) | WAKE_CKSW_SEL_SLOW_DEFAULT; /* Select CLK_HIGH as wakeup clock */ SCP_CLK_SLOW_SEL = (SCP_CLK_SLOW_SEL & ~(CKSW_SEL_SLOW_MASK | CKSW_SEL_SLOW_DIV_MASK)) | CKSW_SEL_SLOW_ULPOSC2_CLK; /* * Set legacy wakeup * - disable SPM sleep control * - disable SCP sleep mode */ SCP_CLK_SLEEP_CTRL &= ~(EN_SLEEP_CTRL | SPM_SLEEP_MODE); task_enable_irq(SCP_IRQ_CLOCK); task_enable_irq(SCP_IRQ_CLOCK2); } static void scp_ulposc_config(int osc, uint32_t osc_div, uint32_t osc_cali) { uint32_t val; /* Clear all bits */ val = 0; /* Enable CP */ val |= OSC_CP_EN; /* Set div */ val |= osc_div << 17; /* F-band = 0, I-band = 4 */ val |= 4 << 6; /* Set calibration */ val |= osc_cali; /* Set control register 1 */ AP_ULPOSC_CON02(osc) = val; /* Set control register 2, enable div2 */ AP_ULPOSC_CON13(osc) |= OSC_DIV2_EN; } static inline void busy_udelay(int usec) { /* * Delaying by busy-looping, for place that can't use udelay because of * the clock not configured yet. The value 28 is chosen approximately * from experiment. */ volatile int i = usec * 28; while (i--) ; } static unsigned int scp_measure_ulposc_freq(int osc) { unsigned int result = 0; int cnt; /* Before select meter clock input, bit[1:0] = b00 */ AP_CLK_DBG_CFG = (AP_CLK_DBG_CFG & ~DBG_MODE_MASK) | DBG_MODE_SET_CLOCK; /* Select source, bit[21:16] = clk_src */ AP_CLK_DBG_CFG = (AP_CLK_DBG_CFG & ~DBG_BIST_SOURCE_MASK) | (osc == 0 ? DBG_BIST_SOURCE_ULPOSC1 : DBG_BIST_SOURCE_ULPOSC2); /* Set meter divisor to 1, bit[31:24] = b00000000 */ AP_CLK_MISC_CFG_0 = (AP_CLK_MISC_CFG_0 & ~MISC_METER_DIVISOR_MASK) | MISC_METER_DIV_1; /* Enable frequency meter, without start */ AP_SCP_CFG_0 |= CFG_FREQ_METER_ENABLE; /* Trigger frequency meter start */ AP_SCP_CFG_0 |= CFG_FREQ_METER_RUN; /* * Frequency meter counts cycles in 1 / (26 * 1024) second period. * freq_in_hz = freq_counter * 26 * 1024 * * The hardware takes 38us to count cycles. Delay up to 100us, * as busy_udelay may not be accurate when sysclk is not 26Mhz * (e.g. when recalibrating/measuring after boot). */ for (cnt = 100; cnt; cnt--) { busy_udelay(1); if (!(AP_SCP_CFG_0 & CFG_FREQ_METER_RUN)) { result = CFG_FREQ_COUNTER(AP_SCP_CFG_1); break; } } /* Disable freq meter */ AP_SCP_CFG_0 &= ~CFG_FREQ_METER_ENABLE; return result; } static inline int signum(int v) { return (v > 0) - (v < 0); } static inline int abs(int v) { return (v >= 0) ? v : -v; } static int scp_ulposc_config_measure(int osc, int div, int cali) { int freq; scp_ulposc_config(osc, div, cali); freq = scp_measure_ulposc_freq(osc); CPRINTF("ULPOSC%d: %d %d %d (%dkHz)\n", osc + 1, div, cali, freq, freq * 26 * 1000 / 1024); return freq; } /** * Calibrate ULPOSC to target frequency. * * @param osc 0:ULPOSC1, 1:ULPOSC2 * @param target_mhz Target frequency to set * @return Frequency counter output * */ static int scp_calibrate_ulposc(int osc, int target_mhz) { int target_freq = DIV_ROUND_NEAREST(target_mhz * 1024, 26); struct ulposc { int div; /* frequency divisor/multiplier */ int cali; /* variable resistor calibrator */ int freq; /* frequency counter measure result */ } curr, prev = {0}; enum { STAGE_DIV, STAGE_CALI } stage = STAGE_DIV; int param, param_max; curr.div = ULPOSC_DIV_MAX / 2; curr.cali = ULPOSC_CALI_MAX / 2; param = curr.div; param_max = ULPOSC_DIV_MAX; /* * In the loop below, linear search closest div value to get desired * frequency counter value. Then adjust cali to get a better result. * Note that this doesn't give optimal output frequency, but it's * usually close enough. * TODO(b:120176040): See if we can efficiently calibrate the clock with * more precision by exploring more of the cali/div space. * * The frequency function follows. Note that f is positively correlated * with both div and cali: * f(div, cali) = k1 * (div + k2) / R(cali) * C * Where: * R(cali) = k3 / (1 + k4 * (cali - k4)) */ while (1) { curr.freq = scp_ulposc_config_measure(osc, curr.div, curr.cali); if (!curr.freq) return 0; /* * If previous and current are on either side of the desired * frequency, pick the closest one. */ if (prev.freq && signum(target_freq - curr.freq) != signum(target_freq - prev.freq)) { if (abs(target_freq - prev.freq) < abs(target_freq - curr.freq)) curr = prev; if (stage == STAGE_CALI) break; /* Switch to optimizing cali */ stage = STAGE_CALI; param = curr.cali; param_max = ULPOSC_CALI_MAX; } prev = curr; param += signum(target_freq - curr.freq); if (param < 0 || param >= param_max) return 0; if (stage == STAGE_DIV) curr.div = param; else curr.cali = param; } /* * It's possible we end up using prev, so reset the configuration and * measure again. */ return scp_ulposc_config_measure(osc, curr.div, curr.cali); } static void scp_clock_high_enable(int osc) { /* Enable high speed clock */ SCP_CLK_EN |= EN_CLK_HIGH; switch (osc) { case 0: /* After 25ms, enable ULPOSC */ busy_udelay(25 * MSEC); SCP_CLK_EN |= CG_CLK_HIGH; break; case 1: /* Turn off ULPOSC2 high-core-disable switch */ SCP_CLK_ON_CTRL &= ~HIGH_CORE_DIS_SUB; /* After 25ms, turn on ULPOSC2 high core clock gate */ busy_udelay(25 * MSEC); SCP_CLK_HIGH_CORE |= CLK_HIGH_CORE_CG; break; default: break; } } void scp_use_clock(enum scp_clock_source src) { /* * DIV2 divider takes precedence over clock selection to prevent * over-clocking. */ if (src == SCP_CLK_ULPOSC1) SCP_CLK_DIV_SEL = CLK_DIV2; SCP_CLK_SEL = src; if (src != SCP_CLK_ULPOSC1) SCP_CLK_DIV_SEL = CLK_DIV1; } void scp_enable_clock(void) { /* Select default CPU clock */ scp_use_clock(SCP_CLK_26M); /* VREQ */ SCP_CPU_VREQ = 0x10001; SCP_SECURE_CTRL &= ~ENABLE_SPM_MASK_VREQ; /* DDREN auto mode */ SCP_SYS_CTRL |= AUTO_DDREN; /* Set settle time */ SCP_CLK_SYS_VAL = 1; /* System clock */ SCP_CLK_HIGH_VAL = 1; /* ULPOSC */ SCP_CLK_SLEEP_CTRL = (SCP_CLK_SLEEP_CTRL & ~VREQ_COUNTER_MASK) | 2; /* Disable slow wake */ SCP_CLK_SLEEP = SLOW_WAKE_DISABLE; /* Disable SPM sleep control, disable sleep mode */ SCP_CLK_SLEEP_CTRL &= ~(SPM_SLEEP_MODE | EN_SLEEP_CTRL); /* Turn off ULPOSC2 */ SCP_CLK_ON_CTRL |= HIGH_CORE_DIS_SUB; scp_ulposc_config(0, 12, 32); scp_clock_high_enable(0); /* Turn on ULPOSC1 */ scp_ulposc_config(1, 16, 32); scp_clock_high_enable(1); /* Turn on ULPOSC2 */ /* Calibrate ULPOSC */ scp_calibrate_ulposc(0, ULPOSC1_CLOCK_MHZ); scp_calibrate_ulposc(1, ULPOSC2_CLOCK_MHZ); /* Select ULPOSC2 high speed CPU clock */ scp_use_clock(SCP_CLK_ULPOSC2); /* Enable default clock gate */ SCP_CLK_GATE |= CG_DMA_CH3 | CG_DMA_CH2 | CG_DMA_CH1 | CG_DMA_CH0 | CG_I2C_M | CG_MAD_M | CG_AP2P_M; /* Select pwrap_ulposc */ AP_CLK_CFG_5 = (AP_CLK_CFG_5 & ~PWRAP_ULPOSC_MASK) | OSC_D16; /* Enable pwrap_ulposc clock gate */ AP_CLK_CFG_5_CLR = PWRAP_ULPOSC_CG; } void clock_control_irq(void) { /* Read ack CLK_IRQ */ (SCP_CLK_IRQ_ACK); task_clear_pending_irq(SCP_IRQ_CLOCK); } DECLARE_IRQ(SCP_IRQ_CLOCK, clock_control_irq, 3); void clock_fast_wakeup_irq(void) { /* Ack fast wakeup */ SCP_SLEEP_IRQ2 = 1; task_clear_pending_irq(SCP_IRQ_CLOCK2); } DECLARE_IRQ(SCP_IRQ_CLOCK2, clock_fast_wakeup_irq, 3); /* Console command */ int command_ulposc(int argc, char *argv[]) { if (argc > 1 && !strncmp(argv[1], "cal", 3)) { scp_calibrate_ulposc(0, ULPOSC1_CLOCK_MHZ); scp_calibrate_ulposc(1, ULPOSC2_CLOCK_MHZ); } /* SCP clock meter counts every (26MHz / 1024) tick */ ccprintf("ULPOSC1 frequency: %u kHz\n", scp_measure_ulposc_freq(0) * 26 * 1000 / 1024); ccprintf("ULPOSC2 frequency: %u kHz\n", scp_measure_ulposc_freq(1) * 26 * 1000 / 1024); return EC_SUCCESS; } DECLARE_CONSOLE_COMMAND(ulposc, command_ulposc, "[calibrate]", "Calibrate ULPOSC frequency");
8fa642619e266eec1e1603d6d7de10ac86fbe725
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/shells/ast-ksh/files/patch-src_lib_libast_sfio_sfsize.c
0b05e2099c3790ca7c28c14bfa6f9be48a65f843
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
410
c
patch-src_lib_libast_sfio_sfsize.c
--- src/lib/libast/sfio/sfsize.c.orig 2016-02-28 17:09:23 UTC +++ src/lib/libast/sfio/sfsize.c @@ -80,12 +80,10 @@ Sfio_t* f; if(f->here != s && (f->mode&SF_READ) ) { /* buffered data is known to be invalid */ -#if _mmap_worthy if((f->bits&SF_MMAP) && f->data) { SFMUNMAP(f,f->data,f->endb-f->data); f->data = NIL(uchar*); } -#endif f->next = f->endb = f->endr = f->endw = f->data; }
e3ff41586b990aaa2e92691eddc37e80d8fbd16d
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/fs/adfs/dir.c
9cf874ce8336563b1d50d3276fab9832e977b781
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,761
c
dir.c
/* * linux/fs/adfs/dir.c * * Copyright (C) 1999-2000 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Common directory handling for ADFS */ #include "adfs.h" /* * For future. This should probably be per-directory. */ static DEFINE_RWLOCK(adfs_dir_lock); static int adfs_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct inode *inode = file_inode(filp); struct super_block *sb = inode->i_sb; struct adfs_dir_ops *ops = ADFS_SB(sb)->s_dir; struct object_info obj; struct adfs_dir dir; int ret = 0; if (filp->f_pos >> 32) goto out; ret = ops->read(sb, inode->i_ino, inode->i_size, &dir); if (ret) goto out; switch ((unsigned long)filp->f_pos) { case 0: if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR) < 0) goto free_out; filp->f_pos += 1; case 1: if (filldir(dirent, "..", 2, 1, dir.parent_id, DT_DIR) < 0) goto free_out; filp->f_pos += 1; default: break; } read_lock(&adfs_dir_lock); ret = ops->setpos(&dir, filp->f_pos - 2); if (ret) goto unlock_out; while (ops->getnext(&dir, &obj) == 0) { if (filldir(dirent, obj.name, obj.name_len, filp->f_pos, obj.file_id, DT_UNKNOWN) < 0) goto unlock_out; filp->f_pos += 1; } unlock_out: read_unlock(&adfs_dir_lock); free_out: ops->free(&dir); out: return ret; } int adfs_dir_update(struct super_block *sb, struct object_info *obj, int wait) { int ret = -EINVAL; #ifdef CONFIG_ADFS_FS_RW struct adfs_dir_ops *ops = ADFS_SB(sb)->s_dir; struct adfs_dir dir; printk(KERN_INFO "adfs_dir_update: object %06X in dir %06X\n", obj->file_id, obj->parent_id); if (!ops->update) { ret = -EINVAL; goto out; } ret = ops->read(sb, obj->parent_id, 0, &dir); if (ret) goto out; write_lock(&adfs_dir_lock); ret = ops->update(&dir, obj); write_unlock(&adfs_dir_lock); if (wait) { int err = ops->sync(&dir); if (!ret) ret = err; } ops->free(&dir); out: #endif return ret; } static int adfs_match(struct qstr *name, struct object_info *obj) { int i; if (name->len != obj->name_len) return 0; for (i = 0; i < name->len; i++) { char c1, c2; c1 = name->name[i]; c2 = obj->name[i]; if (c1 >= 'A' && c1 <= 'Z') c1 += 'a' - 'A'; if (c2 >= 'A' && c2 <= 'Z') c2 += 'a' - 'A'; if (c1 != c2) return 0; } return 1; } static int adfs_dir_lookup_byname(struct inode *inode, struct qstr *name, struct object_info *obj) { struct super_block *sb = inode->i_sb; struct adfs_dir_ops *ops = ADFS_SB(sb)->s_dir; struct adfs_dir dir; int ret; ret = ops->read(sb, inode->i_ino, inode->i_size, &dir); if (ret) goto out; if (ADFS_I(inode)->parent_id != dir.parent_id) { adfs_error(sb, "parent directory changed under me! (%lx but got %lx)\n", ADFS_I(inode)->parent_id, dir.parent_id); ret = -EIO; goto free_out; } obj->parent_id = inode->i_ino; /* * '.' is handled by reserved_lookup() in fs/namei.c */ if (name->len == 2 && name->name[0] == '.' && name->name[1] == '.') { /* * Currently unable to fill in the rest of 'obj', * but this is better than nothing. We need to * ascend one level to find it's parent. */ obj->name_len = 0; obj->file_id = obj->parent_id; goto free_out; } read_lock(&adfs_dir_lock); ret = ops->setpos(&dir, 0); if (ret) goto unlock_out; ret = -ENOENT; while (ops->getnext(&dir, obj) == 0) { if (adfs_match(name, obj)) { ret = 0; break; } } unlock_out: read_unlock(&adfs_dir_lock); free_out: ops->free(&dir); out: return ret; } const struct file_operations adfs_dir_operations = { .read = generic_read_dir, .llseek = generic_file_llseek, .readdir = adfs_readdir, .fsync = generic_file_fsync, }; static int adfs_hash(const struct dentry *parent, const struct inode *inode, struct qstr *qstr) { const unsigned int name_len = ADFS_SB(parent->d_sb)->s_namelen; const unsigned char *name; unsigned long hash; int i; if (qstr->len < name_len) return 0; /* * Truncate the name in place, avoids * having to define a compare function. */ qstr->len = i = name_len; name = qstr->name; hash = init_name_hash(); while (i--) { char c; c = *name++; if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; hash = partial_name_hash(c, hash); } qstr->hash = end_name_hash(hash); return 0; } /* * Compare two names, taking note of the name length * requirements of the underlying filesystem. */ static int adfs_compare(const struct dentry *parent, const struct inode *pinode, const struct dentry *dentry, const struct inode *inode, unsigned int len, const char *str, const struct qstr *name) { int i; if (len != name->len) return 1; for (i = 0; i < name->len; i++) { char a, b; a = str[i]; b = name->name[i]; if (a >= 'A' && a <= 'Z') a += 'a' - 'A'; if (b >= 'A' && b <= 'Z') b += 'a' - 'A'; if (a != b) return 1; } return 0; } const struct dentry_operations adfs_dentry_operations = { .d_hash = adfs_hash, .d_compare = adfs_compare, }; static struct dentry * adfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct inode *inode = NULL; struct object_info obj; int error; error = adfs_dir_lookup_byname(dir, &dentry->d_name, &obj); if (error == 0) { error = -EACCES; /* * This only returns NULL if get_empty_inode * fails. */ inode = adfs_iget(dir->i_sb, &obj); if (inode) error = 0; } d_add(dentry, inode); return ERR_PTR(error); } /* * directories can handle most operations... */ const struct inode_operations adfs_dir_inode_operations = { .lookup = adfs_lookup, .setattr = adfs_notify_change, };
7bef0d3fd31d25d78955472d96274eef13e08897
41c7328eadeab5ed7c0584b7db51996a05dd9f2d
/deprecated/F1/GPS/main.h
fb24c30ff28cbcbf9c90a949770ea15039b8fde6
[]
no_license
eddyem/stm32samples
1c00ccb8593ea270cae536c85f178a522f704ed5
dce73d358b1fca3e7fa397f5c6d0d5c1cb28aba0
refs/heads/master
2023-07-28T11:13:10.361942
2023-07-24T20:04:22
2023-07-24T20:04:22
32,647,425
152
42
null
null
null
null
UTF-8
C
false
false
2,054
h
main.h
/* * main.h * * Copyright 2014 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #pragma once #ifndef __MAIN_H__ #define __MAIN_H__ #include <stdlib.h> #include <libopencm3/stm32/exti.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/usart.h> #include <libopencm3/cm3/nvic.h> #include <libopencm3/usb/cdc.h> #include <libopencm3/usb/usbd.h> #include <libopencm3/cm3/systick.h> #include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/adc.h> #include <libopencm3/stm32/dma.h> #include <libopencm3/stm32/spi.h> #define ADC_CHANNELS_NUMBER (10) #include "sync.h" // mutexes #include "user_proto.h" extern void *memcpy(void *dest, const void *src, int n); #define _U_ __attribute__((__unused__)) #define U8(x) ((uint8_t) x) #define U16(x) ((uint16_t) x) #define U32(x) ((uint32_t) x) #define STK_RVR_DEFAULT_VAL (8999) #define TIMEZONE_GMT_PLUS (3) typedef struct{ uint8_t H; uint8_t M; uint8_t S; } curtime; extern curtime current_time; extern volatile uint32_t Timer; // global timer (milliseconds) extern volatile int clear_ST_on_connect; // flag for clearing Systick counter on next PPS extern volatile int need_sync; void Delay(uint16_t time); void set_time(uint8_t *buf); void print_time(curtime *T, uint32_t m); void print_curtime(); #endif // __MAIN_H__
a55a3b1a4af67530979d1662ac4341ff1bc825ad
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/any-windows-any/rpcdcep.h
3055aa6cc7118cc25dc5887018ccbdbc20aaefc4
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
13,895
h
rpcdcep.h
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef __RPCDCEP_H__ #define __RPCDCEP_H__ #include <_mingw_unicode.h> #ifdef __cplusplus extern "C" { #endif typedef struct _RPC_VERSION { unsigned short MajorVersion; unsigned short MinorVersion; } RPC_VERSION; typedef struct _RPC_SYNTAX_IDENTIFIER { GUID SyntaxGUID; RPC_VERSION SyntaxVersion; } RPC_SYNTAX_IDENTIFIER,*PRPC_SYNTAX_IDENTIFIER; typedef struct _RPC_MESSAGE { RPC_BINDING_HANDLE Handle; unsigned __LONG32 DataRepresentation; void *Buffer; unsigned int BufferLength; unsigned int ProcNum; PRPC_SYNTAX_IDENTIFIER TransferSyntax; void *RpcInterfaceInformation; void *ReservedForRuntime; RPC_MGR_EPV *ManagerEpv; void *ImportContext; unsigned __LONG32 RpcFlags; } RPC_MESSAGE,*PRPC_MESSAGE; typedef RPC_STATUS RPC_ENTRY RPC_FORWARD_FUNCTION(UUID *InterfaceId,RPC_VERSION *InterfaceVersion,UUID *ObjectId,unsigned char *Rpcpro,void **ppDestEndpoint); enum RPC_ADDRESS_CHANGE_TYPE { PROTOCOL_NOT_LOADED = 1,PROTOCOL_LOADED,PROTOCOL_ADDRESS_CHANGE }; typedef void RPC_ENTRY RPC_ADDRESS_CHANGE_FN(void *arg); #define RPC_CONTEXT_HANDLE_DEFAULT_GUARD ((void *) -4083) #define RPC_CONTEXT_HANDLE_DEFAULT_FLAGS __MSABI_LONG(0x00000000U) #define RPC_CONTEXT_HANDLE_FLAGS __MSABI_LONG(0x30000000U) #define RPC_CONTEXT_HANDLE_SERIALIZE __MSABI_LONG(0x10000000U) #define RPC_CONTEXT_HANDLE_DONT_SERIALIZE __MSABI_LONG(0x20000000U) #define RPC_NCA_FLAGS_DEFAULT 0x00000000 #define RPC_NCA_FLAGS_IDEMPOTENT 0x00000001 #define RPC_NCA_FLAGS_BROADCAST 0x00000002 #define RPC_NCA_FLAGS_MAYBE 0x00000004 #define RPC_BUFFER_COMPLETE 0x00001000 #define RPC_BUFFER_PARTIAL 0x00002000 #define RPC_BUFFER_EXTRA 0x00004000 #define RPC_BUFFER_ASYNC 0x00008000 #define RPC_BUFFER_NONOTIFY 0x00010000 #define RPCFLG_MESSAGE __MSABI_LONG(0x01000000U) #define RPCFLG_AUTO_COMPLETE __MSABI_LONG(0x08000000U) #define RPCFLG_LOCAL_CALL __MSABI_LONG(0x10000000U) #define RPCFLG_INPUT_SYNCHRONOUS __MSABI_LONG(0x20000000U) #define RPCFLG_ASYNCHRONOUS __MSABI_LONG(0x40000000U) #define RPCFLG_NON_NDR __MSABI_LONG(0x80000000U) #define RPCFLG_HAS_MULTI_SYNTAXES __MSABI_LONG(0x02000000U) #define RPCFLG_HAS_CALLBACK __MSABI_LONG(0x04000000U) #define RPC_FLAGS_VALID_BIT 0x00008000 typedef void (__RPC_STUB *RPC_DISPATCH_FUNCTION)(PRPC_MESSAGE Message); typedef struct { unsigned int DispatchTableCount; RPC_DISPATCH_FUNCTION *DispatchTable; LONG_PTR Reserved; } RPC_DISPATCH_TABLE,*PRPC_DISPATCH_TABLE; typedef struct _RPC_PROTSEQ_ENDPOINT { unsigned char *RpcProtocolSequence; unsigned char *Endpoint; } RPC_PROTSEQ_ENDPOINT,*PRPC_PROTSEQ_ENDPOINT; #define NT351_INTERFACE_SIZE 0x40 #define RPC_INTERFACE_HAS_PIPES 0x0001 typedef struct _RPC_SERVER_INTERFACE { unsigned int Length; RPC_SYNTAX_IDENTIFIER InterfaceId; RPC_SYNTAX_IDENTIFIER TransferSyntax; PRPC_DISPATCH_TABLE DispatchTable; unsigned int RpcProtseqEndpointCount; PRPC_PROTSEQ_ENDPOINT RpcProtseqEndpoint; RPC_MGR_EPV *DefaultManagerEpv; void const *InterpreterInfo; unsigned int Flags; } RPC_SERVER_INTERFACE,*PRPC_SERVER_INTERFACE; typedef struct _RPC_CLIENT_INTERFACE { unsigned int Length; RPC_SYNTAX_IDENTIFIER InterfaceId; RPC_SYNTAX_IDENTIFIER TransferSyntax; PRPC_DISPATCH_TABLE DispatchTable; unsigned int RpcProtseqEndpointCount; PRPC_PROTSEQ_ENDPOINT RpcProtseqEndpoint; ULONG_PTR Reserved; void const *InterpreterInfo; unsigned int Flags; } RPC_CLIENT_INTERFACE,*PRPC_CLIENT_INTERFACE; RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcNegotiateTransferSyntax(RPC_MESSAGE *Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcGetBuffer(RPC_MESSAGE *Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcGetBufferWithObject(RPC_MESSAGE *Message,UUID *ObjectUuid); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcSendReceive(RPC_MESSAGE *Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcFreeBuffer(RPC_MESSAGE *Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcSend(PRPC_MESSAGE Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcReceive(PRPC_MESSAGE Message,unsigned int Size); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcFreePipeBuffer(RPC_MESSAGE *Message); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcReallocPipeBuffer(PRPC_MESSAGE Message,unsigned int NewSize); typedef void *I_RPC_MUTEX; #define I_RpcNsBindingSetEntryName __MINGW_NAME_AW(I_RpcNsBindingSetEntryName) #define I_RpcServerUseProtseqEp2 __MINGW_NAME_AW(I_RpcServerUseProtseqEp2) #define I_RpcServerUseProtseq2 __MINGW_NAME_AW(I_RpcServerUseProtseq2) #define I_RpcBindingInqDynamicEndpoint __MINGW_NAME_AW(I_RpcBindingInqDynamicEndpoint) RPCRTAPI void RPC_ENTRY I_RpcRequestMutex(I_RPC_MUTEX *Mutex); RPCRTAPI void RPC_ENTRY I_RpcClearMutex(I_RPC_MUTEX Mutex); RPCRTAPI void RPC_ENTRY I_RpcDeleteMutex(I_RPC_MUTEX Mutex); RPCRTAPI void *RPC_ENTRY I_RpcAllocate(unsigned int Size); RPCRTAPI void RPC_ENTRY I_RpcFree(void *Object); RPCRTAPI void RPC_ENTRY I_RpcPauseExecution(unsigned __LONG32 Milliseconds); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcGetExtendedError(void); typedef void (__RPC_API *PRPC_RUNDOWN)(void *AssociationContext); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcMonitorAssociation(RPC_BINDING_HANDLE Handle,PRPC_RUNDOWN RundownRoutine,void *Context); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcStopMonitorAssociation(RPC_BINDING_HANDLE Handle); RPCRTAPI RPC_BINDING_HANDLE RPC_ENTRY I_RpcGetCurrentCallHandle(void); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcGetAssociationContext(RPC_BINDING_HANDLE BindingHandle,void **AssociationContext); RPCRTAPI void *RPC_ENTRY I_RpcGetServerContextList(RPC_BINDING_HANDLE BindingHandle); RPCRTAPI void RPC_ENTRY I_RpcSetServerContextList(RPC_BINDING_HANDLE BindingHandle,void *ServerContextList); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcNsInterfaceExported(unsigned __LONG32 EntryNameSyntax,unsigned short *EntryName,RPC_SERVER_INTERFACE *RpcInterfaceInformation); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcNsInterfaceUnexported(unsigned __LONG32 EntryNameSyntax,unsigned short *EntryName,RPC_SERVER_INTERFACE *RpcInterfaceInformation); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingToStaticStringBindingW(RPC_BINDING_HANDLE Binding,unsigned short **StringBinding); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqSecurityContext(RPC_BINDING_HANDLE Binding,void **SecurityContextHandle); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqWireIdForSnego(RPC_BINDING_HANDLE Binding,RPC_CSTR WireId); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqMarshalledTargetInfo (RPC_BINDING_HANDLE Binding,unsigned __LONG32 *MarshalledTargetInfoLength,RPC_CSTR *MarshalledTargetInfo); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqLocalClientPID(RPC_BINDING_HANDLE Binding,unsigned __LONG32 *Pid); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingHandleToAsyncHandle(RPC_BINDING_HANDLE Binding,void **AsyncHandle); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcNsBindingSetEntryNameW(RPC_BINDING_HANDLE Binding,unsigned __LONG32 EntryNameSyntax,RPC_WSTR EntryName); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcNsBindingSetEntryNameA(RPC_BINDING_HANDLE Binding,unsigned __LONG32 EntryNameSyntax,RPC_CSTR EntryName); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUseProtseqEp2A(RPC_CSTR NetworkAddress,RPC_CSTR Protseq,unsigned int MaxCalls,RPC_CSTR Endpoint,void *SecurityDescriptor,void *Policy); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUseProtseqEp2W(RPC_WSTR NetworkAddress,RPC_WSTR Protseq,unsigned int MaxCalls,RPC_WSTR Endpoint,void *SecurityDescriptor,void *Policy); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUseProtseq2W(RPC_WSTR NetworkAddress,RPC_WSTR Protseq,unsigned int MaxCalls,void *SecurityDescriptor,void *Policy); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUseProtseq2A(RPC_CSTR NetworkAddress,RPC_CSTR Protseq,unsigned int MaxCalls,void *SecurityDescriptor,void *Policy); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqDynamicEndpointW(RPC_BINDING_HANDLE Binding,RPC_WSTR *DynamicEndpoint); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqDynamicEndpointA(RPC_BINDING_HANDLE Binding,RPC_CSTR *DynamicEndpoint); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerCheckClientRestriction(RPC_BINDING_HANDLE Context); #define TRANSPORT_TYPE_CN 0x01 #define TRANSPORT_TYPE_DG 0x02 #define TRANSPORT_TYPE_LPC 0x04 #define TRANSPORT_TYPE_WMSG 0x08 RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqTransportType(RPC_BINDING_HANDLE Binding,unsigned int *Type); typedef struct _RPC_TRANSFER_SYNTAX { UUID Uuid; unsigned short VersMajor; unsigned short VersMinor; } RPC_TRANSFER_SYNTAX; RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcIfInqTransferSyntaxes(RPC_IF_HANDLE RpcIfHandle,RPC_TRANSFER_SYNTAX *TransferSyntaxes,unsigned int TransferSyntaxSize,unsigned int *TransferSyntaxCount); RPCRTAPI RPC_STATUS RPC_ENTRY I_UuidCreate(UUID *Uuid); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingCopy(RPC_BINDING_HANDLE SourceBinding,RPC_BINDING_HANDLE *DestinationBinding); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingIsClientLocal(RPC_BINDING_HANDLE BindingHandle,unsigned int *ClientLocalFlag); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingInqConnId(RPC_BINDING_HANDLE Binding,void **ConnId,int *pfFirstCall); RPCRTAPI void RPC_ENTRY I_RpcSsDontSerializeContext(void); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcLaunchDatagramReceiveThread(void *pAddress); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerRegisterForwardFunction(RPC_FORWARD_FUNCTION *pForwardFunction); RPC_ADDRESS_CHANGE_FN *RPC_ENTRY I_RpcServerInqAddressChangeFn(void); RPC_STATUS RPC_ENTRY I_RpcServerSetAddressChangeFn(RPC_ADDRESS_CHANGE_FN *pAddressChangeFn); #define RPC_P_ADDR_FORMAT_TCP_IPV4 1 #define RPC_P_ADDR_FORMAT_TCP_IPV6 2 RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerInqLocalConnAddress(RPC_BINDING_HANDLE Binding,void *Buffer,unsigned __LONG32 *BufferSize,unsigned __LONG32 *AddressFormat); RPCRTAPI void RPC_ENTRY I_RpcSessionStrictContextHandle(void); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcTurnOnEEInfoPropagation(void); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcConnectionInqSockBuffSize(unsigned __LONG32 *RecvBuffSize,unsigned __LONG32 *SendBuffSize); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcConnectionSetSockBuffSize(unsigned __LONG32 RecvBuffSize,unsigned __LONG32 SendBuffSize); typedef void (*RPCLT_PDU_FILTER_FUNC)(void *Buffer,unsigned int BufferLength,int fDatagram); typedef void (__cdecl *RPC_SETFILTER_FUNC)(RPCLT_PDU_FILTER_FUNC pfnFilter); #ifndef WINNT RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerStartListening(void *hWnd); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerStopListening(void); typedef RPC_STATUS (*RPC_BLOCKING_FN)(void *hWnd,void *Context,void *hSyncEvent); #define I_RpcServerUnregisterEndpoint __MINGW_NAME_AW(I_RpcServerUnregisterEndpoint) RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcBindingSetAsync(RPC_BINDING_HANDLE Binding,RPC_BLOCKING_FN BlockingFn,unsigned __LONG32 ServerTid); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcSetThreadParams(int fClientFree,void *Context,void *hWndClient); RPCRTAPI unsigned int RPC_ENTRY I_RpcWindowProc(void *hWnd,unsigned int Message,unsigned int wParam,unsigned __LONG32 lParam); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUnregisterEndpointA(RPC_CSTR Protseq,RPC_CSTR Endpoint); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerUnregisterEndpointW(RPC_WSTR Protseq,RPC_WSTR Endpoint); #endif RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcServerInqTransportType(unsigned int *Type); RPCRTAPI __LONG32 RPC_ENTRY I_RpcMapWin32Status(RPC_STATUS Status); typedef struct _RPC_C_OPT_METADATA_DESCRIPTOR { unsigned __LONG32 BufferSize; char *Buffer; } RPC_C_OPT_METADATA_DESCRIPTOR; typedef struct _RDR_CALLOUT_STATE { RPC_STATUS LastError; void *LastEEInfo; RPC_HTTP_REDIRECTOR_STAGE LastCalledStage; unsigned short *ServerName; unsigned short *ServerPort; unsigned short *RemoteUser; unsigned short *AuthType; unsigned char ResourceTypePresent; unsigned char MetadataPresent; unsigned char SessionIdPresent; unsigned char InterfacePresent; UUID ResourceType; RPC_C_OPT_METADATA_DESCRIPTOR Metadata; UUID SessionId; RPC_SYNTAX_IDENTIFIER Interface; void *CertContext; } RDR_CALLOUT_STATE; typedef RPC_STATUS (RPC_ENTRY *I_RpcProxyIsValidMachineFn)(char *pszMachine,char *pszDotMachine,unsigned __LONG32 dwPortNumber); typedef RPC_STATUS (RPC_ENTRY *I_RpcProxyGetClientAddressFn)(void *Context,char *Buffer,unsigned __LONG32 *BufferLength); typedef RPC_STATUS (RPC_ENTRY *I_RpcProxyGetConnectionTimeoutFn)(unsigned __LONG32 *ConnectionTimeout); typedef RPC_STATUS (RPC_ENTRY *I_RpcPerformCalloutFn)(void *Context,RDR_CALLOUT_STATE *CallOutState,RPC_HTTP_REDIRECTOR_STAGE Stage); typedef void (RPC_ENTRY *I_RpcFreeCalloutStateFn)(RDR_CALLOUT_STATE *CallOutState); typedef struct tagI_RpcProxyCallbackInterface { I_RpcProxyIsValidMachineFn IsValidMachineFn; I_RpcProxyGetClientAddressFn GetClientAddressFn; I_RpcProxyGetConnectionTimeoutFn GetConnectionTimeoutFn; I_RpcPerformCalloutFn PerformCalloutFn; I_RpcFreeCalloutStateFn FreeCalloutStateFn; } I_RpcProxyCallbackInterface; #define RPC_PROXY_CONNECTION_TYPE_IN_PROXY 0 #define RPC_PROXY_CONNECTION_TYPE_OUT_PROXY 1 RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcProxyNewConnection(unsigned __LONG32 ConnectionType,unsigned short *ServerAddress,unsigned short *ServerPort,unsigned short *MinConnTimeout,void *ConnectionParameter,RDR_CALLOUT_STATE *CallOutState,I_RpcProxyCallbackInterface *ProxyCallbackInterface); RPCRTAPI RPC_STATUS RPC_ENTRY I_RpcReplyToClientWithStatus(void *ConnectionParameter,RPC_STATUS RpcStatus); RPCRTAPI void RPC_ENTRY I_RpcRecordCalloutFailure(RPC_STATUS RpcStatus,RDR_CALLOUT_STATE *CallOutState,unsigned short *DllName); #ifdef __cplusplus } #endif #endif
4fa712462a7c82d45ab96322e009898f27bf7f2d
1cf86f3b8a75e4b9e2256a49dd7f904d1bc3667c
/src/wfc/Api.h
c3346464513bd941c50d05e7474c2db1aeed2fbe
[ "Zlib" ]
permissive
hugoam/two
bfaa6f0184e7e45e4f2fbc0e2d6257ed51dfe54d
d4b386f48c572da03ac5c89e702cf08f388d434d
refs/heads/master
2023-04-27T11:10:21.640620
2023-04-18T21:04:38
2023-04-18T21:04:38
116,430,022
717
63
Zlib
2019-05-11T16:04:24
2018-01-05T21:48:50
C++
UTF-8
C
false
false
69
h
Api.h
#include <wfc/Forward.h> #include <wfc/Types.h> #include <wfc/Wfc.h>
758c0bbeea636fbd88814601554ab30130454f58
248f9d022d678a8e12e84b9ed004d1f544b1962d
/include/appflags.h
cac63d6849770d55cc0ff33a8a2102b8d48bd1b2
[ "Apache-2.0" ]
permissive
LedgerHQ/nanos-secure-sdk
09893a7ed38adb1d814bec75216f6dc137e212e8
12e5f6f875bf5deb9464b944f50079aaca1a3b98
refs/heads/master
2023-09-04T10:38:06.237940
2023-09-01T11:37:06
2023-09-01T11:37:06
64,407,069
102
69
Apache-2.0
2023-06-28T07:13:03
2016-07-28T15:30:40
C
UTF-8
C
false
false
2,564
h
appflags.h
#pragma once /** * Base flag added to loaded application, to allow them to call all syscalls by * default (the one requiring no extra permission) */ #define APPLICATION_FLAG_MAIN 0x1 /** * Flag which combined with ::APPLICATION_FLAG_ISSUER. * The application is given full nvram access after the global seed has been * destroyed. */ #define APPLICATION_FLAG_BOLOS_UPGRADE 0x2 // this flag is set when a valid signature of the loaded application is // presented at the end of the bolos application load. #define APPLICATION_FLAG_SIGNED 0x4 // must be set on one application in the registry which is used #define APPLICATION_FLAG_BOLOS_UX 0x8 // application is allowed to use the raw master seed, if not set, at least a // level of derivation is required. #define APPLICATION_FLAG_DERIVE_MASTER 0x10 #define APPLICATION_FLAG_SHARED_NVRAM 0x20 #define APPLICATION_FLAG_GLOBAL_PIN 0x40 // This flag means the application is meant to be debugged and allows for dump // or core ARM register in case of a fault detection #define APPLICATION_FLAG_DEBUG 0x80 /** * Mark this application as defaultly booting along with the bootloader (no * application menu displayed) Only one application can have this at a time. It * is managed by the bootloader interface. */ #define APPLICATION_FLAG_AUTOBOOT 0x100 /** * Application is allowed to change the settings */ #define APPLICATION_FLAG_BOLOS_SETTINGS 0x200 #define APPLICATION_FLAG_CUSTOM_CA 0x400 /** * The application main can be called in two ways: * - with first arg (stored in r0) set to 0: The application is called from the * dashboard * - with first arg (stored in r0) set to != 0 (ram address likely): The * application is used as a library from another app. */ #define APPLICATION_FLAG_LIBRARY 0x800 /** * The application won't be shown on the dashboard (somewhat reasonable for pure * library) */ #define APPLICATION_FLAG_NO_RUN 0x1000 /** * Application has been loaded using a secure channel opened using the * bootloader's issuer public key. This application is ledger legit. */ #define APPLICATION_FLAG_ISSUER 0x4000 /** * Application is enabled (when not being updated or removed) */ #define APPLICATION_FLAG_ENABLED 0x8000 /** * Custom AEM flag to test AEM capabilities without standard UX permissions */ #if defined(BOLOS_DEBUG_UX_PERMISSION_FLAG) #define APPLICATION_FLAG_AEM_PIN APPLICATION_FLAG_GLOBAL_PIN #else #define APPLICATION_FLAG_AEM_PIN APPLICATION_FLAG_BOLOS_UX #endif // BOLOS_DEBUG_UX_PERMISSION_FLAG #define APPLICATION_FLAG_NEG_MASK 0xFFFF0000UL
a38eac98853c5ae275bd0ccdf63c978253724d91
4674b8088ffdf55905d44995f08a0792a3e4cd5c
/src/ap/ieee802_11.c
68bc333033e678d08c134556e63810da595a7e84
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
vanhoefm/krackattacks-scripts
41daca791638a92aa4cfa68a582e46119037560e
4b78669686f74efe664c6543b1b5b1616b22f902
refs/heads/research
2022-10-29T20:21:11.512335
2022-10-16T18:44:41
2022-10-16T18:44:41
107,408,514
2,184
577
NOASSERTION
2021-07-06T12:43:49
2017-10-18T12:58:08
C
UTF-8
C
false
false
128,455
c
ieee802_11.c
/* * hostapd / IEEE 802.11 Management * Copyright (c) 2002-2017, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #ifndef CONFIG_NATIVE_WINDOWS #include "utils/common.h" #include "utils/eloop.h" #include "crypto/crypto.h" #include "crypto/sha256.h" #include "crypto/sha384.h" #include "crypto/sha512.h" #include "crypto/random.h" #include "common/ieee802_11_defs.h" #include "common/ieee802_11_common.h" #include "common/wpa_ctrl.h" #include "common/sae.h" #include "radius/radius.h" #include "radius/radius_client.h" #include "p2p/p2p.h" #include "wps/wps.h" #include "fst/fst.h" #include "hostapd.h" #include "beacon.h" #include "ieee802_11_auth.h" #include "sta_info.h" #include "ieee802_1x.h" #include "wpa_auth.h" #include "pmksa_cache_auth.h" #include "wmm.h" #include "ap_list.h" #include "accounting.h" #include "ap_config.h" #include "ap_mlme.h" #include "p2p_hostapd.h" #include "ap_drv_ops.h" #include "wnm_ap.h" #include "hw_features.h" #include "ieee802_11.h" #include "dfs.h" #include "mbo_ap.h" #include "rrm.h" #include "taxonomy.h" #include "fils_hlp.h" #include "dpp_hostapd.h" #include "gas_query_ap.h" #ifdef CONFIG_FILS static struct wpabuf * prepare_auth_resp_fils(struct hostapd_data *hapd, struct sta_info *sta, u16 *resp, struct rsn_pmksa_cache_entry *pmksa, struct wpabuf *erp_resp, const u8 *msk, size_t msk_len, int *is_pub); #endif /* CONFIG_FILS */ u8 * hostapd_eid_supp_rates(struct hostapd_data *hapd, u8 *eid) { u8 *pos = eid; int i, num, count; if (hapd->iface->current_rates == NULL) return eid; *pos++ = WLAN_EID_SUPP_RATES; num = hapd->iface->num_rates; if (hapd->iconf->ieee80211n && hapd->iconf->require_ht) num++; if (hapd->iconf->ieee80211ac && hapd->iconf->require_vht) num++; if (num > 8) { /* rest of the rates are encoded in Extended supported * rates element */ num = 8; } *pos++ = num; for (i = 0, count = 0; i < hapd->iface->num_rates && count < num; i++) { count++; *pos = hapd->iface->current_rates[i].rate / 5; if (hapd->iface->current_rates[i].flags & HOSTAPD_RATE_BASIC) *pos |= 0x80; pos++; } if (hapd->iconf->ieee80211n && hapd->iconf->require_ht && count < 8) { count++; *pos++ = 0x80 | BSS_MEMBERSHIP_SELECTOR_HT_PHY; } if (hapd->iconf->ieee80211ac && hapd->iconf->require_vht && count < 8) { count++; *pos++ = 0x80 | BSS_MEMBERSHIP_SELECTOR_VHT_PHY; } return pos; } u8 * hostapd_eid_ext_supp_rates(struct hostapd_data *hapd, u8 *eid) { u8 *pos = eid; int i, num, count; if (hapd->iface->current_rates == NULL) return eid; num = hapd->iface->num_rates; if (hapd->iconf->ieee80211n && hapd->iconf->require_ht) num++; if (hapd->iconf->ieee80211ac && hapd->iconf->require_vht) num++; if (num <= 8) return eid; num -= 8; *pos++ = WLAN_EID_EXT_SUPP_RATES; *pos++ = num; for (i = 0, count = 0; i < hapd->iface->num_rates && count < num + 8; i++) { count++; if (count <= 8) continue; /* already in SuppRates IE */ *pos = hapd->iface->current_rates[i].rate / 5; if (hapd->iface->current_rates[i].flags & HOSTAPD_RATE_BASIC) *pos |= 0x80; pos++; } if (hapd->iconf->ieee80211n && hapd->iconf->require_ht) { count++; if (count > 8) *pos++ = 0x80 | BSS_MEMBERSHIP_SELECTOR_HT_PHY; } if (hapd->iconf->ieee80211ac && hapd->iconf->require_vht) { count++; if (count > 8) *pos++ = 0x80 | BSS_MEMBERSHIP_SELECTOR_VHT_PHY; } return pos; } u16 hostapd_own_capab_info(struct hostapd_data *hapd) { int capab = WLAN_CAPABILITY_ESS; int privacy; int dfs; int i; /* Check if any of configured channels require DFS */ dfs = hostapd_is_dfs_required(hapd->iface); if (dfs < 0) { wpa_printf(MSG_WARNING, "Failed to check if DFS is required; ret=%d", dfs); dfs = 0; } if (hapd->iface->num_sta_no_short_preamble == 0 && hapd->iconf->preamble == SHORT_PREAMBLE) capab |= WLAN_CAPABILITY_SHORT_PREAMBLE; privacy = hapd->conf->ssid.wep.keys_set; if (hapd->conf->ieee802_1x && (hapd->conf->default_wep_key_len || hapd->conf->individual_wep_key_len)) privacy = 1; if (hapd->conf->wpa) privacy = 1; #ifdef CONFIG_HS20 if (hapd->conf->osen) privacy = 1; #endif /* CONFIG_HS20 */ if (privacy) capab |= WLAN_CAPABILITY_PRIVACY; if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G && hapd->iface->num_sta_no_short_slot_time == 0) capab |= WLAN_CAPABILITY_SHORT_SLOT_TIME; /* * Currently, Spectrum Management capability bit is set when directly * requested in configuration by spectrum_mgmt_required or when AP is * running on DFS channel. * TODO: Also consider driver support for TPC to set Spectrum Mgmt bit */ if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211A && (hapd->iconf->spectrum_mgmt_required || dfs)) capab |= WLAN_CAPABILITY_SPECTRUM_MGMT; for (i = 0; i < RRM_CAPABILITIES_IE_LEN; i++) { if (hapd->conf->radio_measurements[i]) { capab |= IEEE80211_CAP_RRM; break; } } return capab; } #ifndef CONFIG_NO_RC4 static u16 auth_shared_key(struct hostapd_data *hapd, struct sta_info *sta, u16 auth_transaction, const u8 *challenge, int iswep) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "authentication (shared key, transaction %d)", auth_transaction); if (auth_transaction == 1) { if (!sta->challenge) { /* Generate a pseudo-random challenge */ u8 key[8]; sta->challenge = os_zalloc(WLAN_AUTH_CHALLENGE_LEN); if (sta->challenge == NULL) return WLAN_STATUS_UNSPECIFIED_FAILURE; if (os_get_random(key, sizeof(key)) < 0) { os_free(sta->challenge); sta->challenge = NULL; return WLAN_STATUS_UNSPECIFIED_FAILURE; } rc4_skip(key, sizeof(key), 0, sta->challenge, WLAN_AUTH_CHALLENGE_LEN); } return 0; } if (auth_transaction != 3) return WLAN_STATUS_UNSPECIFIED_FAILURE; /* Transaction 3 */ if (!iswep || !sta->challenge || !challenge || os_memcmp_const(sta->challenge, challenge, WLAN_AUTH_CHALLENGE_LEN)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "shared key authentication - invalid " "challenge-response"); return WLAN_STATUS_CHALLENGE_FAIL; } hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "authentication OK (shared key)"); sta->flags |= WLAN_STA_AUTH; wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH); os_free(sta->challenge); sta->challenge = NULL; return 0; } #endif /* CONFIG_NO_RC4 */ static int send_auth_reply(struct hostapd_data *hapd, const u8 *dst, const u8 *bssid, u16 auth_alg, u16 auth_transaction, u16 resp, const u8 *ies, size_t ies_len) { struct ieee80211_mgmt *reply; u8 *buf; size_t rlen; int reply_res = WLAN_STATUS_UNSPECIFIED_FAILURE; rlen = IEEE80211_HDRLEN + sizeof(reply->u.auth) + ies_len; buf = os_zalloc(rlen); if (buf == NULL) return -1; reply = (struct ieee80211_mgmt *) buf; reply->frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_AUTH); os_memcpy(reply->da, dst, ETH_ALEN); os_memcpy(reply->sa, hapd->own_addr, ETH_ALEN); os_memcpy(reply->bssid, bssid, ETH_ALEN); reply->u.auth.auth_alg = host_to_le16(auth_alg); reply->u.auth.auth_transaction = host_to_le16(auth_transaction); reply->u.auth.status_code = host_to_le16(resp); if (ies && ies_len) os_memcpy(reply->u.auth.variable, ies, ies_len); wpa_printf(MSG_DEBUG, "authentication reply: STA=" MACSTR " auth_alg=%d auth_transaction=%d resp=%d (IE len=%lu)", MAC2STR(dst), auth_alg, auth_transaction, resp, (unsigned long) ies_len); if (hostapd_drv_send_mlme(hapd, reply, rlen, 0) < 0) wpa_printf(MSG_INFO, "send_auth_reply: send failed"); else reply_res = WLAN_STATUS_SUCCESS; os_free(buf); return reply_res; } #ifdef CONFIG_IEEE80211R_AP static void handle_auth_ft_finish(void *ctx, const u8 *dst, const u8 *bssid, u16 auth_transaction, u16 status, const u8 *ies, size_t ies_len) { struct hostapd_data *hapd = ctx; struct sta_info *sta; int reply_res; reply_res = send_auth_reply(hapd, dst, bssid, WLAN_AUTH_FT, auth_transaction, status, ies, ies_len); sta = ap_get_sta(hapd, dst); if (sta == NULL) return; if (sta->added_unassoc && (reply_res != WLAN_STATUS_SUCCESS || status != WLAN_STATUS_SUCCESS)) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; return; } if (status != WLAN_STATUS_SUCCESS) return; hostapd_logger(hapd, dst, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "authentication OK (FT)"); sta->flags |= WLAN_STA_AUTH; mlme_authenticate_indication(hapd, sta); } #endif /* CONFIG_IEEE80211R_AP */ #ifdef CONFIG_SAE static void sae_set_state(struct sta_info *sta, enum sae_state state, const char *reason) { wpa_printf(MSG_DEBUG, "SAE: State %s -> %s for peer " MACSTR " (%s)", sae_state_txt(sta->sae->state), sae_state_txt(state), MAC2STR(sta->addr), reason); sta->sae->state = state; } static struct wpabuf * auth_build_sae_commit(struct hostapd_data *hapd, struct sta_info *sta, int update) { struct wpabuf *buf; const char *password; password = hapd->conf->sae_password; if (!password) password = hapd->conf->ssid.wpa_passphrase; if (!password) { wpa_printf(MSG_DEBUG, "SAE: No password available"); return NULL; } if (update && sae_prepare_commit(hapd->own_addr, sta->addr, (u8 *) password, os_strlen(password), sta->sae) < 0) { wpa_printf(MSG_DEBUG, "SAE: Could not pick PWE"); return NULL; } buf = wpabuf_alloc(SAE_COMMIT_MAX_LEN); if (buf == NULL) return NULL; sae_write_commit(sta->sae, buf, sta->sae->tmp ? sta->sae->tmp->anti_clogging_token : NULL); return buf; } static struct wpabuf * auth_build_sae_confirm(struct hostapd_data *hapd, struct sta_info *sta) { struct wpabuf *buf; buf = wpabuf_alloc(SAE_CONFIRM_MAX_LEN); if (buf == NULL) return NULL; sae_write_confirm(sta->sae, buf); return buf; } static int auth_sae_send_commit(struct hostapd_data *hapd, struct sta_info *sta, const u8 *bssid, int update) { struct wpabuf *data; int reply_res; data = auth_build_sae_commit(hapd, sta, update); if (data == NULL) return WLAN_STATUS_UNSPECIFIED_FAILURE; reply_res = send_auth_reply(hapd, sta->addr, bssid, WLAN_AUTH_SAE, 1, WLAN_STATUS_SUCCESS, wpabuf_head(data), wpabuf_len(data)); wpabuf_free(data); return reply_res; } static int auth_sae_send_confirm(struct hostapd_data *hapd, struct sta_info *sta, const u8 *bssid) { struct wpabuf *data; int reply_res; data = auth_build_sae_confirm(hapd, sta); if (data == NULL) return WLAN_STATUS_UNSPECIFIED_FAILURE; reply_res = send_auth_reply(hapd, sta->addr, bssid, WLAN_AUTH_SAE, 2, WLAN_STATUS_SUCCESS, wpabuf_head(data), wpabuf_len(data)); wpabuf_free(data); return reply_res; } static int use_sae_anti_clogging(struct hostapd_data *hapd) { struct sta_info *sta; unsigned int open = 0; if (hapd->conf->sae_anti_clogging_threshold == 0) return 1; for (sta = hapd->sta_list; sta; sta = sta->next) { if (!sta->sae) continue; if (sta->sae->state != SAE_COMMITTED && sta->sae->state != SAE_CONFIRMED) continue; open++; if (open >= hapd->conf->sae_anti_clogging_threshold) return 1; } return 0; } static int check_sae_token(struct hostapd_data *hapd, const u8 *addr, const u8 *token, size_t token_len) { u8 mac[SHA256_MAC_LEN]; if (token_len != SHA256_MAC_LEN) return -1; if (hmac_sha256(hapd->sae_token_key, sizeof(hapd->sae_token_key), addr, ETH_ALEN, mac) < 0 || os_memcmp_const(token, mac, SHA256_MAC_LEN) != 0) return -1; return 0; } static struct wpabuf * auth_build_token_req(struct hostapd_data *hapd, int group, const u8 *addr) { struct wpabuf *buf; u8 *token; struct os_reltime now; os_get_reltime(&now); if (!os_reltime_initialized(&hapd->last_sae_token_key_update) || os_reltime_expired(&now, &hapd->last_sae_token_key_update, 60)) { if (random_get_bytes(hapd->sae_token_key, sizeof(hapd->sae_token_key)) < 0) return NULL; wpa_hexdump(MSG_DEBUG, "SAE: Updated token key", hapd->sae_token_key, sizeof(hapd->sae_token_key)); hapd->last_sae_token_key_update = now; } buf = wpabuf_alloc(sizeof(le16) + SHA256_MAC_LEN); if (buf == NULL) return NULL; wpabuf_put_le16(buf, group); /* Finite Cyclic Group */ token = wpabuf_put(buf, SHA256_MAC_LEN); hmac_sha256(hapd->sae_token_key, sizeof(hapd->sae_token_key), addr, ETH_ALEN, token); return buf; } static int sae_check_big_sync(struct hostapd_data *hapd, struct sta_info *sta) { if (sta->sae->sync > hapd->conf->sae_sync) { sae_set_state(sta, SAE_NOTHING, "Sync > dot11RSNASAESync"); sta->sae->sync = 0; return -1; } return 0; } static void auth_sae_retransmit_timer(void *eloop_ctx, void *eloop_data) { struct hostapd_data *hapd = eloop_ctx; struct sta_info *sta = eloop_data; int ret; if (sae_check_big_sync(hapd, sta)) return; sta->sae->sync++; wpa_printf(MSG_DEBUG, "SAE: Auth SAE retransmit timer for " MACSTR " (sync=%d state=%s)", MAC2STR(sta->addr), sta->sae->sync, sae_state_txt(sta->sae->state)); switch (sta->sae->state) { case SAE_COMMITTED: ret = auth_sae_send_commit(hapd, sta, hapd->own_addr, 0); eloop_register_timeout(0, hapd->dot11RSNASAERetransPeriod * 1000, auth_sae_retransmit_timer, hapd, sta); break; case SAE_CONFIRMED: ret = auth_sae_send_confirm(hapd, sta, hapd->own_addr); eloop_register_timeout(0, hapd->dot11RSNASAERetransPeriod * 1000, auth_sae_retransmit_timer, hapd, sta); break; default: ret = -1; break; } if (ret != WLAN_STATUS_SUCCESS) wpa_printf(MSG_INFO, "SAE: Failed to retransmit: ret=%d", ret); } void sae_clear_retransmit_timer(struct hostapd_data *hapd, struct sta_info *sta) { eloop_cancel_timeout(auth_sae_retransmit_timer, hapd, sta); } static void sae_set_retransmit_timer(struct hostapd_data *hapd, struct sta_info *sta) { if (!(hapd->conf->mesh & MESH_ENABLED)) return; eloop_cancel_timeout(auth_sae_retransmit_timer, hapd, sta); eloop_register_timeout(0, hapd->dot11RSNASAERetransPeriod * 1000, auth_sae_retransmit_timer, hapd, sta); } void sae_accept_sta(struct hostapd_data *hapd, struct sta_info *sta) { sta->flags |= WLAN_STA_AUTH; sta->auth_alg = WLAN_AUTH_SAE; mlme_authenticate_indication(hapd, sta); wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH); sae_set_state(sta, SAE_ACCEPTED, "Accept Confirm"); wpa_auth_pmksa_add_sae(hapd->wpa_auth, sta->addr, sta->sae->pmk, sta->sae->pmkid); } static int sae_sm_step(struct hostapd_data *hapd, struct sta_info *sta, const u8 *bssid, u8 auth_transaction) { int ret; if (auth_transaction != 1 && auth_transaction != 2) return WLAN_STATUS_UNSPECIFIED_FAILURE; wpa_printf(MSG_DEBUG, "SAE: Peer " MACSTR " state=%s auth_trans=%u", MAC2STR(sta->addr), sae_state_txt(sta->sae->state), auth_transaction); switch (sta->sae->state) { case SAE_NOTHING: if (auth_transaction == 1) { ret = auth_sae_send_commit(hapd, sta, bssid, 1); if (ret) return ret; sae_set_state(sta, SAE_COMMITTED, "Sent Commit"); if (sae_process_commit(sta->sae) < 0) return WLAN_STATUS_UNSPECIFIED_FAILURE; /* * In mesh case, both Commit and Confirm can be sent * immediately. In infrastructure BSS, only a single * Authentication frame (Commit) is expected from the AP * here and the second one (Confirm) will be sent once * the STA has sent its second Authentication frame * (Confirm). */ if (hapd->conf->mesh & MESH_ENABLED) { /* * Send both Commit and Confirm immediately * based on SAE finite state machine * Nothing -> Confirm transition. */ ret = auth_sae_send_confirm(hapd, sta, bssid); if (ret) return ret; sae_set_state(sta, SAE_CONFIRMED, "Sent Confirm (mesh)"); } else { /* * For infrastructure BSS, send only the Commit * message now to get alternating sequence of * Authentication frames between the AP and STA. * Confirm will be sent in * Committed -> Confirmed/Accepted transition * when receiving Confirm from STA. */ } sta->sae->sync = 0; sae_set_retransmit_timer(hapd, sta); } else { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "SAE confirm before commit"); } break; case SAE_COMMITTED: sae_clear_retransmit_timer(hapd, sta); if (auth_transaction == 1) { if (sae_process_commit(sta->sae) < 0) return WLAN_STATUS_UNSPECIFIED_FAILURE; ret = auth_sae_send_confirm(hapd, sta, bssid); if (ret) return ret; sae_set_state(sta, SAE_CONFIRMED, "Sent Confirm"); sta->sae->sync = 0; sae_set_retransmit_timer(hapd, sta); } else if (hapd->conf->mesh & MESH_ENABLED) { /* * In mesh case, follow SAE finite state machine and * send Commit now, if sync count allows. */ if (sae_check_big_sync(hapd, sta)) return WLAN_STATUS_SUCCESS; sta->sae->sync++; ret = auth_sae_send_commit(hapd, sta, bssid, 0); if (ret) return ret; sae_set_retransmit_timer(hapd, sta); } else { /* * For instructure BSS, send the postponed Confirm from * Nothing -> Confirmed transition that was reduced to * Nothing -> Committed above. */ ret = auth_sae_send_confirm(hapd, sta, bssid); if (ret) return ret; sae_set_state(sta, SAE_CONFIRMED, "Sent Confirm"); /* * Since this was triggered on Confirm RX, run another * step to get to Accepted without waiting for * additional events. */ return sae_sm_step(hapd, sta, bssid, auth_transaction); } break; case SAE_CONFIRMED: sae_clear_retransmit_timer(hapd, sta); if (auth_transaction == 1) { if (sae_check_big_sync(hapd, sta)) return WLAN_STATUS_SUCCESS; sta->sae->sync++; ret = auth_sae_send_commit(hapd, sta, bssid, 1); if (ret) return ret; if (sae_process_commit(sta->sae) < 0) return WLAN_STATUS_UNSPECIFIED_FAILURE; ret = auth_sae_send_confirm(hapd, sta, bssid); if (ret) return ret; sae_set_retransmit_timer(hapd, sta); } else { sta->sae->send_confirm = 0xffff; sae_accept_sta(hapd, sta); } break; case SAE_ACCEPTED: if (auth_transaction == 1) { wpa_printf(MSG_DEBUG, "SAE: remove the STA (" MACSTR ") doing reauthentication", MAC2STR(sta->addr)); ap_free_sta(hapd, sta); wpa_auth_pmksa_remove(hapd->wpa_auth, sta->addr); } else { if (sae_check_big_sync(hapd, sta)) return WLAN_STATUS_SUCCESS; sta->sae->sync++; ret = auth_sae_send_confirm(hapd, sta, bssid); sae_clear_temp_data(sta->sae); if (ret) return ret; } break; default: wpa_printf(MSG_ERROR, "SAE: invalid state %d", sta->sae->state); return WLAN_STATUS_UNSPECIFIED_FAILURE; } return WLAN_STATUS_SUCCESS; } static void sae_pick_next_group(struct hostapd_data *hapd, struct sta_info *sta) { struct sae_data *sae = sta->sae; int i, *groups = hapd->conf->sae_groups; if (sae->state != SAE_COMMITTED) return; wpa_printf(MSG_DEBUG, "SAE: Previously selected group: %d", sae->group); for (i = 0; groups && groups[i] > 0; i++) { if (sae->group == groups[i]) break; } if (!groups || groups[i] <= 0) { wpa_printf(MSG_DEBUG, "SAE: Previously selected group not found from the current configuration"); return; } for (;;) { i++; if (groups[i] <= 0) { wpa_printf(MSG_DEBUG, "SAE: No alternative group enabled"); return; } if (sae_set_group(sae, groups[i]) < 0) continue; break; } wpa_printf(MSG_DEBUG, "SAE: Selected new group: %d", groups[i]); } static void handle_auth_sae(struct hostapd_data *hapd, struct sta_info *sta, const struct ieee80211_mgmt *mgmt, size_t len, u16 auth_transaction, u16 status_code) { int resp = WLAN_STATUS_SUCCESS; struct wpabuf *data = NULL; #ifdef CONFIG_TESTING_OPTIONS if (hapd->conf->sae_reflection_attack && auth_transaction == 1) { const u8 *pos, *end; wpa_printf(MSG_DEBUG, "SAE: TESTING - reflection attack"); pos = mgmt->u.auth.variable; end = ((const u8 *) mgmt) + len; send_auth_reply(hapd, mgmt->sa, mgmt->bssid, WLAN_AUTH_SAE, auth_transaction, resp, pos, end - pos); goto remove_sta; } if (hapd->conf->sae_commit_override && auth_transaction == 1) { wpa_printf(MSG_DEBUG, "SAE: TESTING - commit override"); send_auth_reply(hapd, mgmt->sa, mgmt->bssid, WLAN_AUTH_SAE, auth_transaction, resp, wpabuf_head(hapd->conf->sae_commit_override), wpabuf_len(hapd->conf->sae_commit_override)); goto remove_sta; } #endif /* CONFIG_TESTING_OPTIONS */ if (!sta->sae) { if (auth_transaction != 1 || status_code != WLAN_STATUS_SUCCESS) { resp = -1; goto remove_sta; } sta->sae = os_zalloc(sizeof(*sta->sae)); if (!sta->sae) { resp = -1; goto remove_sta; } sae_set_state(sta, SAE_NOTHING, "Init"); sta->sae->sync = 0; } if (sta->mesh_sae_pmksa_caching) { wpa_printf(MSG_DEBUG, "SAE: Cancel use of mesh PMKSA caching because peer starts SAE authentication"); wpa_auth_pmksa_remove(hapd->wpa_auth, sta->addr); sta->mesh_sae_pmksa_caching = 0; } if (auth_transaction == 1) { const u8 *token = NULL, *pos, *end; size_t token_len = 0; hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "start SAE authentication (RX commit, status=%u)", status_code); if ((hapd->conf->mesh & MESH_ENABLED) && status_code == WLAN_STATUS_ANTI_CLOGGING_TOKEN_REQ && sta->sae->tmp) { pos = mgmt->u.auth.variable; end = ((const u8 *) mgmt) + len; if (pos + sizeof(le16) > end) { wpa_printf(MSG_ERROR, "SAE: Too short anti-clogging token request"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto reply; } resp = sae_group_allowed(sta->sae, hapd->conf->sae_groups, WPA_GET_LE16(pos)); if (resp != WLAN_STATUS_SUCCESS) { wpa_printf(MSG_ERROR, "SAE: Invalid group in anti-clogging token request"); goto reply; } pos += sizeof(le16); wpabuf_free(sta->sae->tmp->anti_clogging_token); sta->sae->tmp->anti_clogging_token = wpabuf_alloc_copy(pos, end - pos); if (sta->sae->tmp->anti_clogging_token == NULL) { wpa_printf(MSG_ERROR, "SAE: Failed to alloc for anti-clogging token"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto remove_sta; } /* * IEEE Std 802.11-2012, 11.3.8.6.4: If the Status code * is 76, a new Commit Message shall be constructed * with the Anti-Clogging Token from the received * Authentication frame, and the commit-scalar and * COMMIT-ELEMENT previously sent. */ resp = auth_sae_send_commit(hapd, sta, mgmt->bssid, 0); if (resp != WLAN_STATUS_SUCCESS) { wpa_printf(MSG_ERROR, "SAE: Failed to send commit message"); goto remove_sta; } sae_set_state(sta, SAE_COMMITTED, "Sent Commit (anti-clogging token case in mesh)"); sta->sae->sync = 0; sae_set_retransmit_timer(hapd, sta); return; } if ((hapd->conf->mesh & MESH_ENABLED) && status_code == WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED && sta->sae->tmp) { wpa_printf(MSG_DEBUG, "SAE: Peer did not accept our SAE group"); sae_pick_next_group(hapd, sta); goto remove_sta; } if (status_code != WLAN_STATUS_SUCCESS) goto remove_sta; resp = sae_parse_commit(sta->sae, mgmt->u.auth.variable, ((const u8 *) mgmt) + len - mgmt->u.auth.variable, &token, &token_len, hapd->conf->sae_groups); if (resp == SAE_SILENTLY_DISCARD) { wpa_printf(MSG_DEBUG, "SAE: Drop commit message from " MACSTR " due to reflection attack", MAC2STR(sta->addr)); goto remove_sta; } if (token && check_sae_token(hapd, sta->addr, token, token_len) < 0) { wpa_printf(MSG_DEBUG, "SAE: Drop commit message with " "incorrect token from " MACSTR, MAC2STR(sta->addr)); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto remove_sta; } if (resp != WLAN_STATUS_SUCCESS) goto reply; if (!token && use_sae_anti_clogging(hapd)) { wpa_printf(MSG_DEBUG, "SAE: Request anti-clogging token from " MACSTR, MAC2STR(sta->addr)); data = auth_build_token_req(hapd, sta->sae->group, sta->addr); resp = WLAN_STATUS_ANTI_CLOGGING_TOKEN_REQ; if (hapd->conf->mesh & MESH_ENABLED) sae_set_state(sta, SAE_NOTHING, "Request anti-clogging token case in mesh"); goto reply; } resp = sae_sm_step(hapd, sta, mgmt->bssid, auth_transaction); } else if (auth_transaction == 2) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "SAE authentication (RX confirm, status=%u)", status_code); if (status_code != WLAN_STATUS_SUCCESS) goto remove_sta; if (sta->sae->state >= SAE_CONFIRMED || !(hapd->conf->mesh & MESH_ENABLED)) { const u8 *var; size_t var_len; u16 peer_send_confirm; var = mgmt->u.auth.variable; var_len = ((u8 *) mgmt) + len - mgmt->u.auth.variable; if (var_len < 2) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto reply; } peer_send_confirm = WPA_GET_LE16(var); if (sta->sae->state == SAE_ACCEPTED && (peer_send_confirm <= sta->sae->rc || peer_send_confirm == 0xffff)) { wpa_printf(MSG_DEBUG, "SAE: Silently ignore unexpected Confirm from peer " MACSTR " (peer-send-confirm=%u Rc=%u)", MAC2STR(sta->addr), peer_send_confirm, sta->sae->rc); return; } if (sae_check_confirm(sta->sae, var, var_len) < 0) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto reply; } sta->sae->rc = peer_send_confirm; } resp = sae_sm_step(hapd, sta, mgmt->bssid, auth_transaction); } else { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "unexpected SAE authentication transaction %u (status=%u)", auth_transaction, status_code); if (status_code != WLAN_STATUS_SUCCESS) goto remove_sta; resp = WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION; } reply: if (resp != WLAN_STATUS_SUCCESS) { send_auth_reply(hapd, mgmt->sa, mgmt->bssid, WLAN_AUTH_SAE, auth_transaction, resp, data ? wpabuf_head(data) : (u8 *) "", data ? wpabuf_len(data) : 0); } remove_sta: if (sta->added_unassoc && (resp != WLAN_STATUS_SUCCESS || status_code != WLAN_STATUS_SUCCESS)) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; } wpabuf_free(data); } /** * auth_sae_init_committed - Send COMMIT and start SAE in committed state * @hapd: BSS data for the device initiating the authentication * @sta: the peer to which commit authentication frame is sent * * This function implements Init event handling (IEEE Std 802.11-2012, * 11.3.8.6.3) in which initial COMMIT message is sent. Prior to calling, the * sta->sae structure should be initialized appropriately via a call to * sae_prepare_commit(). */ int auth_sae_init_committed(struct hostapd_data *hapd, struct sta_info *sta) { int ret; if (!sta->sae || !sta->sae->tmp) return -1; if (sta->sae->state != SAE_NOTHING) return -1; ret = auth_sae_send_commit(hapd, sta, hapd->own_addr, 0); if (ret) return -1; sae_set_state(sta, SAE_COMMITTED, "Init and sent commit"); sta->sae->sync = 0; sae_set_retransmit_timer(hapd, sta); return 0; } #endif /* CONFIG_SAE */ static u16 wpa_res_to_status_code(int res) { if (res == WPA_INVALID_GROUP) return WLAN_STATUS_GROUP_CIPHER_NOT_VALID; if (res == WPA_INVALID_PAIRWISE) return WLAN_STATUS_PAIRWISE_CIPHER_NOT_VALID; if (res == WPA_INVALID_AKMP) return WLAN_STATUS_AKMP_NOT_VALID; if (res == WPA_ALLOC_FAIL) return WLAN_STATUS_UNSPECIFIED_FAILURE; #ifdef CONFIG_IEEE80211W if (res == WPA_MGMT_FRAME_PROTECTION_VIOLATION) return WLAN_STATUS_ROBUST_MGMT_FRAME_POLICY_VIOLATION; if (res == WPA_INVALID_MGMT_GROUP_CIPHER) return WLAN_STATUS_CIPHER_REJECTED_PER_POLICY; #endif /* CONFIG_IEEE80211W */ if (res == WPA_INVALID_MDIE) return WLAN_STATUS_INVALID_MDIE; if (res == WPA_INVALID_PMKID) return WLAN_STATUS_INVALID_PMKID; if (res != WPA_IE_OK) return WLAN_STATUS_INVALID_IE; return WLAN_STATUS_SUCCESS; } #ifdef CONFIG_FILS static void handle_auth_fils_finish(struct hostapd_data *hapd, struct sta_info *sta, u16 resp, struct wpabuf *data, int pub); void handle_auth_fils(struct hostapd_data *hapd, struct sta_info *sta, const u8 *pos, size_t len, u16 auth_alg, u16 auth_transaction, u16 status_code, void (*cb)(struct hostapd_data *hapd, struct sta_info *sta, u16 resp, struct wpabuf *data, int pub)) { u16 resp = WLAN_STATUS_SUCCESS; const u8 *end; struct ieee802_11_elems elems; int res; struct wpa_ie_data rsn; struct rsn_pmksa_cache_entry *pmksa = NULL; if (auth_transaction != 1 || status_code != WLAN_STATUS_SUCCESS) return; end = pos + len; wpa_hexdump(MSG_DEBUG, "FILS: Authentication frame fields", pos, end - pos); /* TODO: FILS PK */ #ifdef CONFIG_FILS_SK_PFS if (auth_alg == WLAN_AUTH_FILS_SK_PFS) { u16 group; struct wpabuf *pub; size_t elem_len; /* Using FILS PFS */ /* Finite Cyclic Group */ if (end - pos < 2) { wpa_printf(MSG_DEBUG, "FILS: No room for Finite Cyclic Group"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } group = WPA_GET_LE16(pos); pos += 2; if (group != hapd->conf->fils_dh_group) { wpa_printf(MSG_DEBUG, "FILS: Unsupported Finite Cyclic Group: %u (expected %u)", group, hapd->conf->fils_dh_group); resp = WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED; goto fail; } crypto_ecdh_deinit(sta->fils_ecdh); sta->fils_ecdh = crypto_ecdh_init(group); if (!sta->fils_ecdh) { wpa_printf(MSG_INFO, "FILS: Could not initialize ECDH with group %d", group); resp = WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED; goto fail; } pub = crypto_ecdh_get_pubkey(sta->fils_ecdh, 1); if (!pub) { wpa_printf(MSG_DEBUG, "FILS: Failed to derive ECDH public key"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } elem_len = wpabuf_len(pub); wpabuf_free(pub); /* Element */ if ((size_t) (end - pos) < elem_len) { wpa_printf(MSG_DEBUG, "FILS: No room for Element"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpabuf_free(sta->fils_g_sta); sta->fils_g_sta = wpabuf_alloc_copy(pos, elem_len); wpabuf_clear_free(sta->fils_dh_ss); sta->fils_dh_ss = crypto_ecdh_set_peerkey(sta->fils_ecdh, 1, pos, elem_len); if (!sta->fils_dh_ss) { wpa_printf(MSG_DEBUG, "FILS: ECDH operation failed"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpa_hexdump_buf_key(MSG_DEBUG, "FILS: DH_SS", sta->fils_dh_ss); pos += elem_len; } else { crypto_ecdh_deinit(sta->fils_ecdh); sta->fils_ecdh = NULL; wpabuf_clear_free(sta->fils_dh_ss); sta->fils_dh_ss = NULL; } #endif /* CONFIG_FILS_SK_PFS */ wpa_hexdump(MSG_DEBUG, "FILS: Remaining IEs", pos, end - pos); if (ieee802_11_parse_elems(pos, end - pos, &elems, 1) == ParseFailed) { wpa_printf(MSG_DEBUG, "FILS: Could not parse elements"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } /* RSNE */ wpa_hexdump(MSG_DEBUG, "FILS: RSN element", elems.rsn_ie, elems.rsn_ie_len); if (!elems.rsn_ie || wpa_parse_wpa_ie_rsn(elems.rsn_ie - 2, elems.rsn_ie_len + 2, &rsn) < 0) { wpa_printf(MSG_DEBUG, "FILS: No valid RSN element"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (!sta->wpa_sm) sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr, NULL); if (!sta->wpa_sm) { wpa_printf(MSG_DEBUG, "FILS: Failed to initialize RSN state machine"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } res = wpa_validate_wpa_ie(hapd->wpa_auth, sta->wpa_sm, elems.rsn_ie - 2, elems.rsn_ie_len + 2, elems.mdie, elems.mdie_len, NULL, 0); resp = wpa_res_to_status_code(res); if (resp != WLAN_STATUS_SUCCESS) goto fail; if (!elems.fils_nonce) { wpa_printf(MSG_DEBUG, "FILS: No FILS Nonce field"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpa_hexdump(MSG_DEBUG, "FILS: SNonce", elems.fils_nonce, FILS_NONCE_LEN); os_memcpy(sta->fils_snonce, elems.fils_nonce, FILS_NONCE_LEN); /* PMKID List */ if (rsn.pmkid && rsn.num_pmkid > 0) { u8 num; const u8 *pmkid; wpa_hexdump(MSG_DEBUG, "FILS: PMKID List", rsn.pmkid, rsn.num_pmkid * PMKID_LEN); pmkid = rsn.pmkid; num = rsn.num_pmkid; while (num) { wpa_hexdump(MSG_DEBUG, "FILS: PMKID", pmkid, PMKID_LEN); pmksa = wpa_auth_pmksa_get(hapd->wpa_auth, sta->addr, pmkid); if (pmksa) break; pmksa = wpa_auth_pmksa_get_fils_cache_id(hapd->wpa_auth, sta->addr, pmkid); if (pmksa) break; pmkid += PMKID_LEN; num--; } } if (pmksa && wpa_auth_sta_key_mgmt(sta->wpa_sm) != pmksa->akmp) { wpa_printf(MSG_DEBUG, "FILS: Matching PMKSA cache entry has different AKMP (0x%x != 0x%x) - ignore", wpa_auth_sta_key_mgmt(sta->wpa_sm), pmksa->akmp); pmksa = NULL; } if (pmksa) wpa_printf(MSG_DEBUG, "FILS: Found matching PMKSA cache entry"); /* FILS Session */ if (!elems.fils_session) { wpa_printf(MSG_DEBUG, "FILS: No FILS Session element"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpa_hexdump(MSG_DEBUG, "FILS: FILS Session", elems.fils_session, FILS_SESSION_LEN); os_memcpy(sta->fils_session, elems.fils_session, FILS_SESSION_LEN); /* FILS Wrapped Data */ if (elems.fils_wrapped_data) { wpa_hexdump(MSG_DEBUG, "FILS: Wrapped Data", elems.fils_wrapped_data, elems.fils_wrapped_data_len); if (!pmksa) { #ifndef CONFIG_NO_RADIUS if (!sta->eapol_sm) { sta->eapol_sm = ieee802_1x_alloc_eapol_sm(hapd, sta); } wpa_printf(MSG_DEBUG, "FILS: Forward EAP-Initiate/Re-auth to authentication server"); ieee802_1x_encapsulate_radius( hapd, sta, elems.fils_wrapped_data, elems.fils_wrapped_data_len); sta->fils_pending_cb = cb; wpa_printf(MSG_DEBUG, "FILS: Will send Authentication frame once the response from authentication server is available"); sta->flags |= WLAN_STA_PENDING_FILS_ERP; /* Calculate pending PMKID here so that we do not need * to maintain a copy of the EAP-Initiate/Reauth * message. */ if (fils_pmkid_erp(wpa_auth_sta_key_mgmt(sta->wpa_sm), elems.fils_wrapped_data, elems.fils_wrapped_data_len, sta->fils_erp_pmkid) == 0) sta->fils_erp_pmkid_set = 1; return; #else /* CONFIG_NO_RADIUS */ resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; #endif /* CONFIG_NO_RADIUS */ } } fail: if (cb) { struct wpabuf *data; int pub = 0; data = prepare_auth_resp_fils(hapd, sta, &resp, pmksa, NULL, NULL, 0, &pub); if (!data) { wpa_printf(MSG_DEBUG, "%s: prepare_auth_resp_fils() returned failure", __func__); } cb(hapd, sta, resp, data, pub); } } static struct wpabuf * prepare_auth_resp_fils(struct hostapd_data *hapd, struct sta_info *sta, u16 *resp, struct rsn_pmksa_cache_entry *pmksa, struct wpabuf *erp_resp, const u8 *msk, size_t msk_len, int *is_pub) { u8 fils_nonce[FILS_NONCE_LEN]; size_t ielen; struct wpabuf *data = NULL; const u8 *ie; u8 *ie_buf = NULL; const u8 *pmk = NULL; size_t pmk_len = 0; u8 pmk_buf[PMK_LEN_MAX]; struct wpabuf *pub = NULL; if (*resp != WLAN_STATUS_SUCCESS) goto fail; ie = wpa_auth_get_wpa_ie(hapd->wpa_auth, &ielen); if (!ie) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (pmksa) { /* Add PMKID of the selected PMKSA into RSNE */ ie_buf = os_malloc(ielen + 2 + 2 + PMKID_LEN); if (!ie_buf) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } os_memcpy(ie_buf, ie, ielen); if (wpa_insert_pmkid(ie_buf, &ielen, pmksa->pmkid) < 0) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } ie = ie_buf; } if (random_get_bytes(fils_nonce, FILS_NONCE_LEN) < 0) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpa_hexdump(MSG_DEBUG, "RSN: Generated FILS Nonce", fils_nonce, FILS_NONCE_LEN); #ifdef CONFIG_FILS_SK_PFS if (sta->fils_dh_ss && sta->fils_ecdh) { pub = crypto_ecdh_get_pubkey(sta->fils_ecdh, 1); if (!pub) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } } #endif /* CONFIG_FILS_SK_PFS */ data = wpabuf_alloc(1000 + ielen + (pub ? wpabuf_len(pub) : 0)); if (!data) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } /* TODO: FILS PK */ #ifdef CONFIG_FILS_SK_PFS if (pub) { /* Finite Cyclic Group */ wpabuf_put_le16(data, hapd->conf->fils_dh_group); /* Element */ wpabuf_put_buf(data, pub); } #endif /* CONFIG_FILS_SK_PFS */ /* RSNE */ wpabuf_put_data(data, ie, ielen); /* MDE when using FILS+FT (already included in ie,ielen with RSNE) */ #ifdef CONFIG_IEEE80211R_AP if (wpa_key_mgmt_ft(wpa_auth_sta_key_mgmt(sta->wpa_sm))) { /* FTE[R1KH-ID,R0KH-ID] when using FILS+FT */ int res; res = wpa_auth_write_fte(hapd->wpa_auth, wpabuf_put(data, 0), wpabuf_tailroom(data)); if (res < 0) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpabuf_put(data, res); } #endif /* CONFIG_IEEE80211R_AP */ /* FILS Nonce */ wpabuf_put_u8(data, WLAN_EID_EXTENSION); /* Element ID */ wpabuf_put_u8(data, 1 + FILS_NONCE_LEN); /* Length */ /* Element ID Extension */ wpabuf_put_u8(data, WLAN_EID_EXT_FILS_NONCE); wpabuf_put_data(data, fils_nonce, FILS_NONCE_LEN); /* FILS Session */ wpabuf_put_u8(data, WLAN_EID_EXTENSION); /* Element ID */ wpabuf_put_u8(data, 1 + FILS_SESSION_LEN); /* Length */ /* Element ID Extension */ wpabuf_put_u8(data, WLAN_EID_EXT_FILS_SESSION); wpabuf_put_data(data, sta->fils_session, FILS_SESSION_LEN); /* FILS Wrapped Data */ if (!pmksa && erp_resp) { wpabuf_put_u8(data, WLAN_EID_EXTENSION); /* Element ID */ wpabuf_put_u8(data, 1 + wpabuf_len(erp_resp)); /* Length */ /* Element ID Extension */ wpabuf_put_u8(data, WLAN_EID_EXT_FILS_WRAPPED_DATA); wpabuf_put_buf(data, erp_resp); if (fils_rmsk_to_pmk(wpa_auth_sta_key_mgmt(sta->wpa_sm), msk, msk_len, sta->fils_snonce, fils_nonce, sta->fils_dh_ss ? wpabuf_head(sta->fils_dh_ss) : NULL, sta->fils_dh_ss ? wpabuf_len(sta->fils_dh_ss) : 0, pmk_buf, &pmk_len)) { wpa_printf(MSG_DEBUG, "FILS: Failed to derive PMK"); *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; wpabuf_free(data); data = NULL; goto fail; } pmk = pmk_buf; /* Don't use DHss in PTK derivation if PMKSA caching is not * used. */ wpabuf_clear_free(sta->fils_dh_ss); sta->fils_dh_ss = NULL; if (sta->fils_erp_pmkid_set) { /* TODO: get PMKLifetime from WPA parameters */ unsigned int dot11RSNAConfigPMKLifetime = 43200; sta->fils_erp_pmkid_set = 0; if (wpa_auth_pmksa_add2( hapd->wpa_auth, sta->addr, pmk, pmk_len, sta->fils_erp_pmkid, sta->session_timeout_set ? sta->session_timeout : dot11RSNAConfigPMKLifetime, wpa_auth_sta_key_mgmt(sta->wpa_sm)) < 0) { wpa_printf(MSG_ERROR, "FILS: Failed to add PMKSA cache entry based on ERP"); } } } else if (pmksa) { pmk = pmksa->pmk; pmk_len = pmksa->pmk_len; } if (!pmk) { wpa_printf(MSG_DEBUG, "FILS: No PMK available"); *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; wpabuf_free(data); data = NULL; goto fail; } if (fils_auth_pmk_to_ptk(sta->wpa_sm, pmk, pmk_len, sta->fils_snonce, fils_nonce, sta->fils_dh_ss ? wpabuf_head(sta->fils_dh_ss) : NULL, sta->fils_dh_ss ? wpabuf_len(sta->fils_dh_ss) : 0, sta->fils_g_sta, pub) < 0) { *resp = WLAN_STATUS_UNSPECIFIED_FAILURE; wpabuf_free(data); data = NULL; goto fail; } fail: if (is_pub) *is_pub = pub != NULL; os_free(ie_buf); wpabuf_free(pub); wpabuf_clear_free(sta->fils_dh_ss); sta->fils_dh_ss = NULL; #ifdef CONFIG_FILS_SK_PFS crypto_ecdh_deinit(sta->fils_ecdh); sta->fils_ecdh = NULL; #endif /* CONFIG_FILS_SK_PFS */ return data; } static void handle_auth_fils_finish(struct hostapd_data *hapd, struct sta_info *sta, u16 resp, struct wpabuf *data, int pub) { u16 auth_alg; auth_alg = (pub || resp == WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED) ? WLAN_AUTH_FILS_SK_PFS : WLAN_AUTH_FILS_SK; send_auth_reply(hapd, sta->addr, hapd->own_addr, auth_alg, 2, resp, data ? wpabuf_head(data) : (u8 *) "", data ? wpabuf_len(data) : 0); wpabuf_free(data); if (resp == WLAN_STATUS_SUCCESS) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "authentication OK (FILS)"); sta->flags |= WLAN_STA_AUTH; wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH); sta->auth_alg = pub ? WLAN_AUTH_FILS_SK_PFS : WLAN_AUTH_FILS_SK; mlme_authenticate_indication(hapd, sta); } } void ieee802_11_finish_fils_auth(struct hostapd_data *hapd, struct sta_info *sta, int success, struct wpabuf *erp_resp, const u8 *msk, size_t msk_len) { struct wpabuf *data; int pub = 0; u16 resp; sta->flags &= ~WLAN_STA_PENDING_FILS_ERP; if (!sta->fils_pending_cb) return; resp = success ? WLAN_STATUS_SUCCESS : WLAN_STATUS_UNSPECIFIED_FAILURE; data = prepare_auth_resp_fils(hapd, sta, &resp, NULL, erp_resp, msk, msk_len, &pub); if (!data) { wpa_printf(MSG_DEBUG, "%s: prepare_auth_resp_fils() returned failure", __func__); } sta->fils_pending_cb(hapd, sta, resp, data, pub); } #endif /* CONFIG_FILS */ int ieee802_11_allowed_address(struct hostapd_data *hapd, const u8 *addr, const u8 *msg, size_t len, u32 *session_timeout, u32 *acct_interim_interval, struct vlan_description *vlan_id, struct hostapd_sta_wpa_psk_short **psk, char **identity, char **radius_cui, int is_probe_req) { int res; os_memset(vlan_id, 0, sizeof(*vlan_id)); res = hostapd_allowed_address(hapd, addr, msg, len, session_timeout, acct_interim_interval, vlan_id, psk, identity, radius_cui, is_probe_req); if (res == HOSTAPD_ACL_REJECT) { wpa_printf(MSG_INFO, "Station " MACSTR " not allowed to authenticate", MAC2STR(addr)); return HOSTAPD_ACL_REJECT; } if (res == HOSTAPD_ACL_PENDING) { wpa_printf(MSG_DEBUG, "Authentication frame from " MACSTR " waiting for an external authentication", MAC2STR(addr)); /* Authentication code will re-send the authentication frame * after it has received (and cached) information from the * external source. */ return HOSTAPD_ACL_PENDING; } return res; } static int ieee802_11_set_radius_info(struct hostapd_data *hapd, struct sta_info *sta, int res, u32 session_timeout, u32 acct_interim_interval, struct vlan_description *vlan_id, struct hostapd_sta_wpa_psk_short **psk, char **identity, char **radius_cui) { if (vlan_id->notempty && !hostapd_vlan_valid(hapd->conf->vlan, vlan_id)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS, HOSTAPD_LEVEL_INFO, "Invalid VLAN %d%s received from RADIUS server", vlan_id->untagged, vlan_id->tagged[0] ? "+" : ""); return -1; } if (ap_sta_set_vlan(hapd, sta, vlan_id) < 0) return -1; if (sta->vlan_id) hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS, HOSTAPD_LEVEL_INFO, "VLAN ID %d", sta->vlan_id); hostapd_free_psk_list(sta->psk); if (hapd->conf->wpa_psk_radius != PSK_RADIUS_IGNORED) { sta->psk = *psk; *psk = NULL; } else { sta->psk = NULL; } sta->identity = *identity; *identity = NULL; sta->radius_cui = *radius_cui; *radius_cui = NULL; if (hapd->conf->acct_interim_interval == 0 && acct_interim_interval) sta->acct_interim_interval = acct_interim_interval; if (res == HOSTAPD_ACL_ACCEPT_TIMEOUT) ap_sta_session_timeout(hapd, sta, session_timeout); else ap_sta_no_session_timeout(hapd, sta); return 0; } static void handle_auth(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len) { u16 auth_alg, auth_transaction, status_code; u16 resp = WLAN_STATUS_SUCCESS; struct sta_info *sta = NULL; int res, reply_res; u16 fc; const u8 *challenge = NULL; u32 session_timeout, acct_interim_interval; struct vlan_description vlan_id; struct hostapd_sta_wpa_psk_short *psk = NULL; u8 resp_ies[2 + WLAN_AUTH_CHALLENGE_LEN]; size_t resp_ies_len = 0; char *identity = NULL; char *radius_cui = NULL; u16 seq_ctrl; if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.auth)) { wpa_printf(MSG_INFO, "handle_auth - too short payload (len=%lu)", (unsigned long) len); return; } #ifdef CONFIG_TESTING_OPTIONS if (hapd->iconf->ignore_auth_probability > 0.0 && drand48() < hapd->iconf->ignore_auth_probability) { wpa_printf(MSG_INFO, "TESTING: ignoring auth frame from " MACSTR, MAC2STR(mgmt->sa)); return; } #endif /* CONFIG_TESTING_OPTIONS */ auth_alg = le_to_host16(mgmt->u.auth.auth_alg); auth_transaction = le_to_host16(mgmt->u.auth.auth_transaction); status_code = le_to_host16(mgmt->u.auth.status_code); fc = le_to_host16(mgmt->frame_control); seq_ctrl = le_to_host16(mgmt->seq_ctrl); if (len >= IEEE80211_HDRLEN + sizeof(mgmt->u.auth) + 2 + WLAN_AUTH_CHALLENGE_LEN && mgmt->u.auth.variable[0] == WLAN_EID_CHALLENGE && mgmt->u.auth.variable[1] == WLAN_AUTH_CHALLENGE_LEN) challenge = &mgmt->u.auth.variable[2]; wpa_printf(MSG_DEBUG, "authentication: STA=" MACSTR " auth_alg=%d " "auth_transaction=%d status_code=%d wep=%d%s " "seq_ctrl=0x%x%s", MAC2STR(mgmt->sa), auth_alg, auth_transaction, status_code, !!(fc & WLAN_FC_ISWEP), challenge ? " challenge" : "", seq_ctrl, (fc & WLAN_FC_RETRY) ? " retry" : ""); #ifdef CONFIG_NO_RC4 if (auth_alg == WLAN_AUTH_SHARED_KEY) { wpa_printf(MSG_INFO, "Unsupported authentication algorithm (%d)", auth_alg); resp = WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG; goto fail; } #endif /* CONFIG_NO_RC4 */ if (hapd->tkip_countermeasures) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (!(((hapd->conf->auth_algs & WPA_AUTH_ALG_OPEN) && auth_alg == WLAN_AUTH_OPEN) || #ifdef CONFIG_IEEE80211R_AP (hapd->conf->wpa && wpa_key_mgmt_ft(hapd->conf->wpa_key_mgmt) && auth_alg == WLAN_AUTH_FT) || #endif /* CONFIG_IEEE80211R_AP */ #ifdef CONFIG_SAE (hapd->conf->wpa && wpa_key_mgmt_sae(hapd->conf->wpa_key_mgmt) && auth_alg == WLAN_AUTH_SAE) || #endif /* CONFIG_SAE */ #ifdef CONFIG_FILS (hapd->conf->wpa && wpa_key_mgmt_fils(hapd->conf->wpa_key_mgmt) && auth_alg == WLAN_AUTH_FILS_SK) || (hapd->conf->wpa && wpa_key_mgmt_fils(hapd->conf->wpa_key_mgmt) && hapd->conf->fils_dh_group && auth_alg == WLAN_AUTH_FILS_SK_PFS) || #endif /* CONFIG_FILS */ ((hapd->conf->auth_algs & WPA_AUTH_ALG_SHARED) && auth_alg == WLAN_AUTH_SHARED_KEY))) { wpa_printf(MSG_INFO, "Unsupported authentication algorithm (%d)", auth_alg); resp = WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG; goto fail; } if (!(auth_transaction == 1 || auth_alg == WLAN_AUTH_SAE || (auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 3))) { wpa_printf(MSG_INFO, "Unknown authentication transaction number (%d)", auth_transaction); resp = WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION; goto fail; } if (os_memcmp(mgmt->sa, hapd->own_addr, ETH_ALEN) == 0) { wpa_printf(MSG_INFO, "Station " MACSTR " not allowed to authenticate", MAC2STR(mgmt->sa)); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (hapd->conf->no_auth_if_seen_on) { struct hostapd_data *other; other = sta_track_seen_on(hapd->iface, mgmt->sa, hapd->conf->no_auth_if_seen_on); if (other) { u8 *pos; u32 info; u8 op_class, channel, phytype; wpa_printf(MSG_DEBUG, "%s: Reject authentication from " MACSTR " since STA has been seen on %s", hapd->conf->iface, MAC2STR(mgmt->sa), hapd->conf->no_auth_if_seen_on); resp = WLAN_STATUS_REJECTED_WITH_SUGGESTED_BSS_TRANSITION; pos = &resp_ies[0]; *pos++ = WLAN_EID_NEIGHBOR_REPORT; *pos++ = 13; os_memcpy(pos, other->own_addr, ETH_ALEN); pos += ETH_ALEN; info = 0; /* TODO: BSSID Information */ WPA_PUT_LE32(pos, info); pos += 4; if (other->iconf->hw_mode == HOSTAPD_MODE_IEEE80211AD) phytype = 8; /* dmg */ else if (other->iconf->ieee80211ac) phytype = 9; /* vht */ else if (other->iconf->ieee80211n) phytype = 7; /* ht */ else if (other->iconf->hw_mode == HOSTAPD_MODE_IEEE80211A) phytype = 4; /* ofdm */ else if (other->iconf->hw_mode == HOSTAPD_MODE_IEEE80211G) phytype = 6; /* erp */ else phytype = 5; /* hrdsss */ if (ieee80211_freq_to_channel_ext( hostapd_hw_get_freq(other, other->iconf->channel), other->iconf->secondary_channel, other->iconf->ieee80211ac, &op_class, &channel) == NUM_HOSTAPD_MODES) { op_class = 0; channel = other->iconf->channel; } *pos++ = op_class; *pos++ = channel; *pos++ = phytype; resp_ies_len = pos - &resp_ies[0]; goto fail; } } res = ieee802_11_allowed_address( hapd, mgmt->sa, (const u8 *) mgmt, len, &session_timeout, &acct_interim_interval, &vlan_id, &psk, &identity, &radius_cui, 0); if (res == HOSTAPD_ACL_REJECT) { wpa_msg(hapd->msg_ctx, MSG_DEBUG, "Ignore Authentication frame from " MACSTR " due to ACL reject", MAC2STR(mgmt->sa)); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (res == HOSTAPD_ACL_PENDING) return; sta = ap_get_sta(hapd, mgmt->sa); if (sta) { sta->flags &= ~WLAN_STA_PENDING_FILS_ERP; if ((fc & WLAN_FC_RETRY) && sta->last_seq_ctrl != WLAN_INVALID_MGMT_SEQ && sta->last_seq_ctrl == seq_ctrl && sta->last_subtype == WLAN_FC_STYPE_AUTH) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Drop repeated authentication frame seq_ctrl=0x%x", seq_ctrl); return; } #ifdef CONFIG_MESH if ((hapd->conf->mesh & MESH_ENABLED) && sta->plink_state == PLINK_BLOCKED) { wpa_printf(MSG_DEBUG, "Mesh peer " MACSTR " is blocked - drop Authentication frame", MAC2STR(mgmt->sa)); return; } #endif /* CONFIG_MESH */ } else { #ifdef CONFIG_MESH if (hapd->conf->mesh & MESH_ENABLED) { /* if the mesh peer is not available, we don't do auth. */ wpa_printf(MSG_DEBUG, "Mesh peer " MACSTR " not yet known - drop Authentication frame", MAC2STR(mgmt->sa)); /* * Save a copy of the frame so that it can be processed * if a new peer entry is added shortly after this. */ wpabuf_free(hapd->mesh_pending_auth); hapd->mesh_pending_auth = wpabuf_alloc_copy(mgmt, len); os_get_reltime(&hapd->mesh_pending_auth_time); return; } #endif /* CONFIG_MESH */ sta = ap_sta_add(hapd, mgmt->sa); if (!sta) { resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; goto fail; } } sta->last_seq_ctrl = seq_ctrl; sta->last_subtype = WLAN_FC_STYPE_AUTH; res = ieee802_11_set_radius_info( hapd, sta, res, session_timeout, acct_interim_interval, &vlan_id, &psk, &identity, &radius_cui); if (res) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } sta->flags &= ~WLAN_STA_PREAUTH; ieee802_1x_notify_pre_auth(sta->eapol_sm, 0); /* * If the driver supports full AP client state, add a station to the * driver before sending authentication reply to make sure the driver * has resources, and not to go through the entire authentication and * association handshake, and fail it at the end. * * If this is not the first transaction, in a multi-step authentication * algorithm, the station already exists in the driver * (sta->added_unassoc = 1) so skip it. * * In mesh mode, the station was already added to the driver when the * NEW_PEER_CANDIDATE event is received. * * If PMF was negotiated for the existing association, skip this to * avoid dropping the STA entry and the associated keys. This is needed * to allow the original connection work until the attempt can complete * (re)association, so that unprotected Authentication frame cannot be * used to bypass PMF protection. */ if (FULL_AP_CLIENT_STATE_SUPP(hapd->iface->drv_flags) && (!(sta->flags & WLAN_STA_MFP) || !ap_sta_is_authorized(sta)) && !(hapd->conf->mesh & MESH_ENABLED) && !(sta->added_unassoc)) { /* * If a station that is already associated to the AP, is trying * to authenticate again, remove the STA entry, in order to make * sure the STA PS state gets cleared and configuration gets * updated. To handle this, station's added_unassoc flag is * cleared once the station has completed association. */ hostapd_drv_sta_remove(hapd, sta->addr); sta->flags &= ~(WLAN_STA_ASSOC | WLAN_STA_AUTH | WLAN_STA_AUTHORIZED); if (hostapd_sta_add(hapd, sta->addr, 0, 0, NULL, 0, 0, NULL, NULL, sta->flags, 0, 0, 0, 0)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_NOTICE, "Could not add STA to kernel driver"); resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; goto fail; } sta->added_unassoc = 1; } switch (auth_alg) { case WLAN_AUTH_OPEN: hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "authentication OK (open system)"); sta->flags |= WLAN_STA_AUTH; wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH); sta->auth_alg = WLAN_AUTH_OPEN; mlme_authenticate_indication(hapd, sta); break; #ifndef CONFIG_NO_RC4 case WLAN_AUTH_SHARED_KEY: resp = auth_shared_key(hapd, sta, auth_transaction, challenge, fc & WLAN_FC_ISWEP); sta->auth_alg = WLAN_AUTH_SHARED_KEY; mlme_authenticate_indication(hapd, sta); if (sta->challenge && auth_transaction == 1) { resp_ies[0] = WLAN_EID_CHALLENGE; resp_ies[1] = WLAN_AUTH_CHALLENGE_LEN; os_memcpy(resp_ies + 2, sta->challenge, WLAN_AUTH_CHALLENGE_LEN); resp_ies_len = 2 + WLAN_AUTH_CHALLENGE_LEN; } break; #endif /* CONFIG_NO_RC4 */ #ifdef CONFIG_IEEE80211R_AP case WLAN_AUTH_FT: sta->auth_alg = WLAN_AUTH_FT; if (sta->wpa_sm == NULL) sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr, NULL); if (sta->wpa_sm == NULL) { wpa_printf(MSG_DEBUG, "FT: Failed to initialize WPA " "state machine"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } wpa_ft_process_auth(sta->wpa_sm, mgmt->bssid, auth_transaction, mgmt->u.auth.variable, len - IEEE80211_HDRLEN - sizeof(mgmt->u.auth), handle_auth_ft_finish, hapd); /* handle_auth_ft_finish() callback will complete auth. */ return; #endif /* CONFIG_IEEE80211R_AP */ #ifdef CONFIG_SAE case WLAN_AUTH_SAE: #ifdef CONFIG_MESH if (status_code == WLAN_STATUS_SUCCESS && hapd->conf->mesh & MESH_ENABLED) { if (sta->wpa_sm == NULL) sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr, NULL); if (sta->wpa_sm == NULL) { wpa_printf(MSG_DEBUG, "SAE: Failed to initialize WPA state machine"); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } } #endif /* CONFIG_MESH */ handle_auth_sae(hapd, sta, mgmt, len, auth_transaction, status_code); return; #endif /* CONFIG_SAE */ #ifdef CONFIG_FILS case WLAN_AUTH_FILS_SK: case WLAN_AUTH_FILS_SK_PFS: handle_auth_fils(hapd, sta, mgmt->u.auth.variable, len - IEEE80211_HDRLEN - sizeof(mgmt->u.auth), auth_alg, auth_transaction, status_code, handle_auth_fils_finish); return; #endif /* CONFIG_FILS */ } fail: os_free(identity); os_free(radius_cui); hostapd_free_psk_list(psk); reply_res = send_auth_reply(hapd, mgmt->sa, mgmt->bssid, auth_alg, auth_transaction + 1, resp, resp_ies, resp_ies_len); if (sta && sta->added_unassoc && (resp != WLAN_STATUS_SUCCESS || reply_res != WLAN_STATUS_SUCCESS)) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; } } int hostapd_get_aid(struct hostapd_data *hapd, struct sta_info *sta) { int i, j = 32, aid; /* get a unique AID */ if (sta->aid > 0) { wpa_printf(MSG_DEBUG, " old AID %d", sta->aid); return 0; } if (TEST_FAIL()) return -1; for (i = 0; i < AID_WORDS; i++) { if (hapd->sta_aid[i] == (u32) -1) continue; for (j = 0; j < 32; j++) { if (!(hapd->sta_aid[i] & BIT(j))) break; } if (j < 32) break; } if (j == 32) return -1; aid = i * 32 + j + 1; if (aid > 2007) return -1; sta->aid = aid; hapd->sta_aid[i] |= BIT(j); wpa_printf(MSG_DEBUG, " new AID %d", sta->aid); return 0; } static u16 check_ssid(struct hostapd_data *hapd, struct sta_info *sta, const u8 *ssid_ie, size_t ssid_ie_len) { if (ssid_ie == NULL) return WLAN_STATUS_UNSPECIFIED_FAILURE; if (ssid_ie_len != hapd->conf->ssid.ssid_len || os_memcmp(ssid_ie, hapd->conf->ssid.ssid, ssid_ie_len) != 0) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station tried to associate with unknown SSID " "'%s'", wpa_ssid_txt(ssid_ie, ssid_ie_len)); return WLAN_STATUS_UNSPECIFIED_FAILURE; } return WLAN_STATUS_SUCCESS; } static u16 check_wmm(struct hostapd_data *hapd, struct sta_info *sta, const u8 *wmm_ie, size_t wmm_ie_len) { sta->flags &= ~WLAN_STA_WMM; sta->qosinfo = 0; if (wmm_ie && hapd->conf->wmm_enabled) { struct wmm_information_element *wmm; if (!hostapd_eid_wmm_valid(hapd, wmm_ie, wmm_ie_len)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_WPA, HOSTAPD_LEVEL_DEBUG, "invalid WMM element in association " "request"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } sta->flags |= WLAN_STA_WMM; wmm = (struct wmm_information_element *) wmm_ie; sta->qosinfo = wmm->qos_info; } return WLAN_STATUS_SUCCESS; } static u16 copy_supp_rates(struct hostapd_data *hapd, struct sta_info *sta, struct ieee802_11_elems *elems) { /* Supported rates not used in IEEE 802.11ad/DMG */ if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211AD) return WLAN_STATUS_SUCCESS; if (!elems->supp_rates) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "No supported rates element in AssocReq"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } if (elems->supp_rates_len + elems->ext_supp_rates_len > sizeof(sta->supported_rates)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Invalid supported rates element length %d+%d", elems->supp_rates_len, elems->ext_supp_rates_len); return WLAN_STATUS_UNSPECIFIED_FAILURE; } sta->supported_rates_len = merge_byte_arrays( sta->supported_rates, sizeof(sta->supported_rates), elems->supp_rates, elems->supp_rates_len, elems->ext_supp_rates, elems->ext_supp_rates_len); return WLAN_STATUS_SUCCESS; } static u16 check_ext_capab(struct hostapd_data *hapd, struct sta_info *sta, const u8 *ext_capab_ie, size_t ext_capab_ie_len) { #ifdef CONFIG_INTERWORKING /* check for QoS Map support */ if (ext_capab_ie_len >= 5) { if (ext_capab_ie[4] & 0x01) sta->qos_map_enabled = 1; } #endif /* CONFIG_INTERWORKING */ if (ext_capab_ie_len > 0) { sta->ecsa_supported = !!(ext_capab_ie[0] & BIT(2)); os_free(sta->ext_capability); sta->ext_capability = os_malloc(1 + ext_capab_ie_len); if (sta->ext_capability) { sta->ext_capability[0] = ext_capab_ie_len; os_memcpy(sta->ext_capability + 1, ext_capab_ie, ext_capab_ie_len); } } return WLAN_STATUS_SUCCESS; } #ifdef CONFIG_OWE static int owe_group_supported(struct hostapd_data *hapd, u16 group) { int i; int *groups = hapd->conf->owe_groups; if (group != 19 && group != 20 && group != 21) return 0; if (!groups) return 1; for (i = 0; groups[i] > 0; i++) { if (groups[i] == group) return 1; } return 0; } static u16 owe_process_assoc_req(struct hostapd_data *hapd, struct sta_info *sta, const u8 *owe_dh, u8 owe_dh_len) { struct wpabuf *secret, *pub, *hkey; int res; u8 prk[SHA512_MAC_LEN], pmkid[SHA512_MAC_LEN]; const char *info = "OWE Key Generation"; const u8 *addr[2]; size_t len[2]; u16 group; size_t hash_len, prime_len; if (wpa_auth_sta_get_pmksa(sta->wpa_sm)) { wpa_printf(MSG_DEBUG, "OWE: Using PMKSA caching"); return WLAN_STATUS_SUCCESS; } group = WPA_GET_LE16(owe_dh); if (!owe_group_supported(hapd, group)) { wpa_printf(MSG_DEBUG, "OWE: Unsupported DH group %u", group); return WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED; } if (group == 19) prime_len = 32; else if (group == 20) prime_len = 48; else if (group == 21) prime_len = 66; else return WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED; crypto_ecdh_deinit(sta->owe_ecdh); sta->owe_ecdh = crypto_ecdh_init(group); if (!sta->owe_ecdh) return WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED; sta->owe_group = group; secret = crypto_ecdh_set_peerkey(sta->owe_ecdh, 0, owe_dh + 2, owe_dh_len - 2); secret = wpabuf_zeropad(secret, prime_len); if (!secret) { wpa_printf(MSG_DEBUG, "OWE: Invalid peer DH public key"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } wpa_hexdump_buf_key(MSG_DEBUG, "OWE: DH shared secret", secret); /* prk = HKDF-extract(C | A | group, z) */ pub = crypto_ecdh_get_pubkey(sta->owe_ecdh, 0); if (!pub) { wpabuf_clear_free(secret); return WLAN_STATUS_UNSPECIFIED_FAILURE; } /* PMKID = Truncate-128(Hash(C | A)) */ addr[0] = owe_dh + 2; len[0] = owe_dh_len - 2; addr[1] = wpabuf_head(pub); len[1] = wpabuf_len(pub); if (group == 19) { res = sha256_vector(2, addr, len, pmkid); hash_len = SHA256_MAC_LEN; } else if (group == 20) { res = sha384_vector(2, addr, len, pmkid); hash_len = SHA384_MAC_LEN; } else if (group == 21) { res = sha512_vector(2, addr, len, pmkid); hash_len = SHA512_MAC_LEN; } else { wpabuf_free(pub); wpabuf_clear_free(secret); return WLAN_STATUS_UNSPECIFIED_FAILURE; } pub = wpabuf_zeropad(pub, prime_len); if (res < 0 || !pub) { wpabuf_free(pub); wpabuf_clear_free(secret); return WLAN_STATUS_UNSPECIFIED_FAILURE; } hkey = wpabuf_alloc(owe_dh_len - 2 + wpabuf_len(pub) + 2); if (!hkey) { wpabuf_free(pub); wpabuf_clear_free(secret); return WLAN_STATUS_UNSPECIFIED_FAILURE; } wpabuf_put_data(hkey, owe_dh + 2, owe_dh_len - 2); /* C */ wpabuf_put_buf(hkey, pub); /* A */ wpabuf_free(pub); wpabuf_put_le16(hkey, group); /* group */ if (group == 19) res = hmac_sha256(wpabuf_head(hkey), wpabuf_len(hkey), wpabuf_head(secret), wpabuf_len(secret), prk); else if (group == 20) res = hmac_sha384(wpabuf_head(hkey), wpabuf_len(hkey), wpabuf_head(secret), wpabuf_len(secret), prk); else if (group == 21) res = hmac_sha512(wpabuf_head(hkey), wpabuf_len(hkey), wpabuf_head(secret), wpabuf_len(secret), prk); wpabuf_clear_free(hkey); wpabuf_clear_free(secret); if (res < 0) return WLAN_STATUS_UNSPECIFIED_FAILURE; wpa_hexdump_key(MSG_DEBUG, "OWE: prk", prk, hash_len); /* PMK = HKDF-expand(prk, "OWE Key Generation", n) */ os_free(sta->owe_pmk); sta->owe_pmk = os_malloc(hash_len); if (!sta->owe_pmk) { os_memset(prk, 0, SHA512_MAC_LEN); return WLAN_STATUS_UNSPECIFIED_FAILURE; } if (group == 19) res = hmac_sha256_kdf(prk, hash_len, NULL, (const u8 *) info, os_strlen(info), sta->owe_pmk, hash_len); else if (group == 20) res = hmac_sha384_kdf(prk, hash_len, NULL, (const u8 *) info, os_strlen(info), sta->owe_pmk, hash_len); else if (group == 21) res = hmac_sha512_kdf(prk, hash_len, NULL, (const u8 *) info, os_strlen(info), sta->owe_pmk, hash_len); os_memset(prk, 0, SHA512_MAC_LEN); if (res < 0) { os_free(sta->owe_pmk); sta->owe_pmk = NULL; return WLAN_STATUS_UNSPECIFIED_FAILURE; } sta->owe_pmk_len = hash_len; wpa_hexdump_key(MSG_DEBUG, "OWE: PMK", sta->owe_pmk, sta->owe_pmk_len); wpa_hexdump(MSG_DEBUG, "OWE: PMKID", pmkid, PMKID_LEN); wpa_auth_pmksa_add2(hapd->wpa_auth, sta->addr, sta->owe_pmk, sta->owe_pmk_len, pmkid, 0, WPA_KEY_MGMT_OWE); return WLAN_STATUS_SUCCESS; } #endif /* CONFIG_OWE */ static u16 check_assoc_ies(struct hostapd_data *hapd, struct sta_info *sta, const u8 *ies, size_t ies_len, int reassoc) { struct ieee802_11_elems elems; u16 resp; const u8 *wpa_ie; size_t wpa_ie_len; const u8 *p2p_dev_addr = NULL; if (ieee802_11_parse_elems(ies, ies_len, &elems, 1) == ParseFailed) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station sent an invalid " "association request"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } resp = check_ssid(hapd, sta, elems.ssid, elems.ssid_len); if (resp != WLAN_STATUS_SUCCESS) return resp; resp = check_wmm(hapd, sta, elems.wmm, elems.wmm_len); if (resp != WLAN_STATUS_SUCCESS) return resp; resp = check_ext_capab(hapd, sta, elems.ext_capab, elems.ext_capab_len); if (resp != WLAN_STATUS_SUCCESS) return resp; resp = copy_supp_rates(hapd, sta, &elems); if (resp != WLAN_STATUS_SUCCESS) return resp; #ifdef CONFIG_IEEE80211N resp = copy_sta_ht_capab(hapd, sta, elems.ht_capabilities); if (resp != WLAN_STATUS_SUCCESS) return resp; if (hapd->iconf->ieee80211n && hapd->iconf->require_ht && !(sta->flags & WLAN_STA_HT)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station does not support " "mandatory HT PHY - reject association"); return WLAN_STATUS_ASSOC_DENIED_NO_HT; } #endif /* CONFIG_IEEE80211N */ #ifdef CONFIG_IEEE80211AC if (hapd->iconf->ieee80211ac) { resp = copy_sta_vht_capab(hapd, sta, elems.vht_capabilities); if (resp != WLAN_STATUS_SUCCESS) return resp; resp = set_sta_vht_opmode(hapd, sta, elems.vht_opmode_notif); if (resp != WLAN_STATUS_SUCCESS) return resp; } if (hapd->iconf->ieee80211ac && hapd->iconf->require_vht && !(sta->flags & WLAN_STA_VHT)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station does not support " "mandatory VHT PHY - reject association"); return WLAN_STATUS_ASSOC_DENIED_NO_VHT; } if (hapd->conf->vendor_vht && !elems.vht_capabilities) { resp = copy_sta_vendor_vht(hapd, sta, elems.vendor_vht, elems.vendor_vht_len); if (resp != WLAN_STATUS_SUCCESS) return resp; } #endif /* CONFIG_IEEE80211AC */ #ifdef CONFIG_P2P if (elems.p2p) { wpabuf_free(sta->p2p_ie); sta->p2p_ie = ieee802_11_vendor_ie_concat(ies, ies_len, P2P_IE_VENDOR_TYPE); if (sta->p2p_ie) p2p_dev_addr = p2p_get_go_dev_addr(sta->p2p_ie); } else { wpabuf_free(sta->p2p_ie); sta->p2p_ie = NULL; } #endif /* CONFIG_P2P */ if ((hapd->conf->wpa & WPA_PROTO_RSN) && elems.rsn_ie) { wpa_ie = elems.rsn_ie; wpa_ie_len = elems.rsn_ie_len; } else if ((hapd->conf->wpa & WPA_PROTO_WPA) && elems.wpa_ie) { wpa_ie = elems.wpa_ie; wpa_ie_len = elems.wpa_ie_len; } else { wpa_ie = NULL; wpa_ie_len = 0; } #ifdef CONFIG_WPS sta->flags &= ~(WLAN_STA_WPS | WLAN_STA_MAYBE_WPS | WLAN_STA_WPS2); if (hapd->conf->wps_state && elems.wps_ie) { wpa_printf(MSG_DEBUG, "STA included WPS IE in (Re)Association " "Request - assume WPS is used"); sta->flags |= WLAN_STA_WPS; wpabuf_free(sta->wps_ie); sta->wps_ie = ieee802_11_vendor_ie_concat(ies, ies_len, WPS_IE_VENDOR_TYPE); if (sta->wps_ie && wps_is_20(sta->wps_ie)) { wpa_printf(MSG_DEBUG, "WPS: STA supports WPS 2.0"); sta->flags |= WLAN_STA_WPS2; } wpa_ie = NULL; wpa_ie_len = 0; if (sta->wps_ie && wps_validate_assoc_req(sta->wps_ie) < 0) { wpa_printf(MSG_DEBUG, "WPS: Invalid WPS IE in " "(Re)Association Request - reject"); return WLAN_STATUS_INVALID_IE; } } else if (hapd->conf->wps_state && wpa_ie == NULL) { wpa_printf(MSG_DEBUG, "STA did not include WPA/RSN IE in " "(Re)Association Request - possible WPS use"); sta->flags |= WLAN_STA_MAYBE_WPS; } else #endif /* CONFIG_WPS */ if (hapd->conf->wpa && wpa_ie == NULL) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "No WPA/RSN IE in association request"); return WLAN_STATUS_INVALID_IE; } if (hapd->conf->wpa && wpa_ie) { int res; wpa_ie -= 2; wpa_ie_len += 2; if (sta->wpa_sm == NULL) sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr, p2p_dev_addr); if (sta->wpa_sm == NULL) { wpa_printf(MSG_WARNING, "Failed to initialize WPA " "state machine"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } res = wpa_validate_wpa_ie(hapd->wpa_auth, sta->wpa_sm, wpa_ie, wpa_ie_len, elems.mdie, elems.mdie_len, elems.owe_dh, elems.owe_dh_len); resp = wpa_res_to_status_code(res); if (resp != WLAN_STATUS_SUCCESS) return resp; #ifdef CONFIG_IEEE80211W if ((sta->flags & WLAN_STA_MFP) && !sta->sa_query_timed_out && sta->sa_query_count > 0) ap_check_sa_query_timeout(hapd, sta); if ((sta->flags & WLAN_STA_MFP) && !sta->sa_query_timed_out && (!reassoc || sta->auth_alg != WLAN_AUTH_FT)) { /* * STA has already been associated with MFP and SA * Query timeout has not been reached. Reject the * association attempt temporarily and start SA Query, * if one is not pending. */ if (sta->sa_query_count == 0) ap_sta_start_sa_query(hapd, sta); return WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY; } if (wpa_auth_uses_mfp(sta->wpa_sm)) sta->flags |= WLAN_STA_MFP; else sta->flags &= ~WLAN_STA_MFP; #endif /* CONFIG_IEEE80211W */ #ifdef CONFIG_IEEE80211R_AP if (sta->auth_alg == WLAN_AUTH_FT) { if (!reassoc) { wpa_printf(MSG_DEBUG, "FT: " MACSTR " tried " "to use association (not " "re-association) with FT auth_alg", MAC2STR(sta->addr)); return WLAN_STATUS_UNSPECIFIED_FAILURE; } resp = wpa_ft_validate_reassoc(sta->wpa_sm, ies, ies_len); if (resp != WLAN_STATUS_SUCCESS) return resp; } #endif /* CONFIG_IEEE80211R_AP */ #ifdef CONFIG_SAE if (wpa_auth_uses_sae(sta->wpa_sm) && sta->sae && sta->sae->state == SAE_ACCEPTED) wpa_auth_add_sae_pmkid(sta->wpa_sm, sta->sae->pmkid); if (wpa_auth_uses_sae(sta->wpa_sm) && sta->auth_alg == WLAN_AUTH_OPEN) { struct rsn_pmksa_cache_entry *sa; sa = wpa_auth_sta_get_pmksa(sta->wpa_sm); if (!sa || sa->akmp != WPA_KEY_MGMT_SAE) { wpa_printf(MSG_DEBUG, "SAE: No PMKSA cache entry found for " MACSTR, MAC2STR(sta->addr)); return WLAN_STATUS_INVALID_PMKID; } wpa_printf(MSG_DEBUG, "SAE: " MACSTR " using PMKSA caching", MAC2STR(sta->addr)); } else if (wpa_auth_uses_sae(sta->wpa_sm) && sta->auth_alg != WLAN_AUTH_SAE && !(sta->auth_alg == WLAN_AUTH_FT && wpa_auth_uses_ft_sae(sta->wpa_sm))) { wpa_printf(MSG_DEBUG, "SAE: " MACSTR " tried to use " "SAE AKM after non-SAE auth_alg %u", MAC2STR(sta->addr), sta->auth_alg); return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG; } #endif /* CONFIG_SAE */ #ifdef CONFIG_OWE if ((hapd->conf->wpa_key_mgmt & WPA_KEY_MGMT_OWE) && wpa_auth_sta_key_mgmt(sta->wpa_sm) == WPA_KEY_MGMT_OWE && elems.owe_dh) { resp = owe_process_assoc_req(hapd, sta, elems.owe_dh, elems.owe_dh_len); if (resp != WLAN_STATUS_SUCCESS) return resp; } #endif /* CONFIG_OWE */ #ifdef CONFIG_IEEE80211N if ((sta->flags & (WLAN_STA_HT | WLAN_STA_VHT)) && wpa_auth_get_pairwise(sta->wpa_sm) == WPA_CIPHER_TKIP) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station tried to use TKIP with HT " "association"); return WLAN_STATUS_CIPHER_REJECTED_PER_POLICY; } #endif /* CONFIG_IEEE80211N */ #ifdef CONFIG_HS20 } else if (hapd->conf->osen) { if (elems.osen == NULL) { hostapd_logger( hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "No HS 2.0 OSEN element in association request"); return WLAN_STATUS_INVALID_IE; } wpa_printf(MSG_DEBUG, "HS 2.0: OSEN association"); if (sta->wpa_sm == NULL) sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr, NULL); if (sta->wpa_sm == NULL) { wpa_printf(MSG_WARNING, "Failed to initialize WPA " "state machine"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } if (wpa_validate_osen(hapd->wpa_auth, sta->wpa_sm, elems.osen - 2, elems.osen_len + 2) < 0) return WLAN_STATUS_INVALID_IE; #endif /* CONFIG_HS20 */ } else wpa_auth_sta_no_wpa(sta->wpa_sm); #ifdef CONFIG_P2P p2p_group_notif_assoc(hapd->p2p_group, sta->addr, ies, ies_len); #endif /* CONFIG_P2P */ #ifdef CONFIG_HS20 wpabuf_free(sta->hs20_ie); if (elems.hs20 && elems.hs20_len > 4) { sta->hs20_ie = wpabuf_alloc_copy(elems.hs20 + 4, elems.hs20_len - 4); } else sta->hs20_ie = NULL; #endif /* CONFIG_HS20 */ #ifdef CONFIG_FST wpabuf_free(sta->mb_ies); if (hapd->iface->fst) sta->mb_ies = mb_ies_by_info(&elems.mb_ies); else sta->mb_ies = NULL; #endif /* CONFIG_FST */ #ifdef CONFIG_MBO mbo_ap_check_sta_assoc(hapd, sta, &elems); if (hapd->conf->mbo_enabled && (hapd->conf->wpa & 2) && elems.mbo && sta->cell_capa && !(sta->flags & WLAN_STA_MFP) && hapd->conf->ieee80211w != NO_MGMT_FRAME_PROTECTION) { wpa_printf(MSG_INFO, "MBO: Reject WPA2 association without PMF"); return WLAN_STATUS_UNSPECIFIED_FAILURE; } #endif /* CONFIG_MBO */ ap_copy_sta_supp_op_classes(sta, elems.supp_op_classes, elems.supp_op_classes_len); if ((sta->capability & WLAN_CAPABILITY_RADIO_MEASUREMENT) && elems.rrm_enabled && elems.rrm_enabled_len >= sizeof(sta->rrm_enabled_capa)) os_memcpy(sta->rrm_enabled_capa, elems.rrm_enabled, sizeof(sta->rrm_enabled_capa)); if (elems.power_capab) { sta->min_tx_power = elems.power_capab[0]; sta->max_tx_power = elems.power_capab[1]; sta->power_capab = 1; } else { sta->power_capab = 0; } return WLAN_STATUS_SUCCESS; } static void send_deauth(struct hostapd_data *hapd, const u8 *addr, u16 reason_code) { int send_len; struct ieee80211_mgmt reply; os_memset(&reply, 0, sizeof(reply)); reply.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_DEAUTH); os_memcpy(reply.da, addr, ETH_ALEN); os_memcpy(reply.sa, hapd->own_addr, ETH_ALEN); os_memcpy(reply.bssid, hapd->own_addr, ETH_ALEN); send_len = IEEE80211_HDRLEN + sizeof(reply.u.deauth); reply.u.deauth.reason_code = host_to_le16(reason_code); if (hostapd_drv_send_mlme(hapd, &reply, send_len, 0) < 0) wpa_printf(MSG_INFO, "Failed to send deauth: %s", strerror(errno)); } static int add_associated_sta(struct hostapd_data *hapd, struct sta_info *sta) { struct ieee80211_ht_capabilities ht_cap; struct ieee80211_vht_capabilities vht_cap; int set = 1; /* * Remove the STA entry to ensure the STA PS state gets cleared and * configuration gets updated. This is relevant for cases, such as * FT-over-the-DS, where a station re-associates back to the same AP but * skips the authentication flow, or if working with a driver that * does not support full AP client state. * * Skip this if the STA has already completed FT reassociation and the * TK has been configured since the TX/RX PN must not be reset to 0 for * the same key. */ if (!sta->added_unassoc && (!(sta->flags & WLAN_STA_AUTHORIZED) || (!wpa_auth_sta_ft_tk_already_set(sta->wpa_sm) && !wpa_auth_sta_fils_tk_already_set(sta->wpa_sm)))) { hostapd_drv_sta_remove(hapd, sta->addr); wpa_auth_sm_event(sta->wpa_sm, WPA_DRV_STA_REMOVED); set = 0; } #ifdef CONFIG_IEEE80211N if (sta->flags & WLAN_STA_HT) hostapd_get_ht_capab(hapd, sta->ht_capabilities, &ht_cap); #endif /* CONFIG_IEEE80211N */ #ifdef CONFIG_IEEE80211AC if (sta->flags & WLAN_STA_VHT) hostapd_get_vht_capab(hapd, sta->vht_capabilities, &vht_cap); #endif /* CONFIG_IEEE80211AC */ /* * Add the station with forced WLAN_STA_ASSOC flag. The sta->flags * will be set when the ACK frame for the (Re)Association Response frame * is processed (TX status driver event). */ if (hostapd_sta_add(hapd, sta->addr, sta->aid, sta->capability, sta->supported_rates, sta->supported_rates_len, sta->listen_interval, sta->flags & WLAN_STA_HT ? &ht_cap : NULL, sta->flags & WLAN_STA_VHT ? &vht_cap : NULL, sta->flags | WLAN_STA_ASSOC, sta->qosinfo, sta->vht_opmode, sta->p2p_ie ? 1 : 0, set)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_NOTICE, "Could not %s STA to kernel driver", set ? "set" : "add"); if (sta->added_unassoc) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; } return -1; } sta->added_unassoc = 0; return 0; } static u16 send_assoc_resp(struct hostapd_data *hapd, struct sta_info *sta, const u8 *addr, u16 status_code, int reassoc, const u8 *ies, size_t ies_len) { int send_len; u8 *buf; size_t buflen; struct ieee80211_mgmt *reply; u8 *p; u16 res = WLAN_STATUS_SUCCESS; buflen = sizeof(struct ieee80211_mgmt) + 1024; #ifdef CONFIG_FILS if (sta && sta->fils_hlp_resp) buflen += wpabuf_len(sta->fils_hlp_resp); #endif /* CONFIG_FILS */ #ifdef CONFIG_OWE if (sta && (hapd->conf->wpa_key_mgmt & WPA_KEY_MGMT_OWE)) buflen += 150; #endif /* CONFIG_OWE */ buf = os_zalloc(buflen); if (!buf) { res = WLAN_STATUS_UNSPECIFIED_FAILURE; goto done; } reply = (struct ieee80211_mgmt *) buf; reply->frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT, (reassoc ? WLAN_FC_STYPE_REASSOC_RESP : WLAN_FC_STYPE_ASSOC_RESP)); os_memcpy(reply->da, addr, ETH_ALEN); os_memcpy(reply->sa, hapd->own_addr, ETH_ALEN); os_memcpy(reply->bssid, hapd->own_addr, ETH_ALEN); send_len = IEEE80211_HDRLEN; send_len += sizeof(reply->u.assoc_resp); reply->u.assoc_resp.capab_info = host_to_le16(hostapd_own_capab_info(hapd)); reply->u.assoc_resp.status_code = host_to_le16(status_code); reply->u.assoc_resp.aid = host_to_le16((sta ? sta->aid : 0) | BIT(14) | BIT(15)); /* Supported rates */ p = hostapd_eid_supp_rates(hapd, reply->u.assoc_resp.variable); /* Extended supported rates */ p = hostapd_eid_ext_supp_rates(hapd, p); #ifdef CONFIG_IEEE80211R_AP if (sta && status_code == WLAN_STATUS_SUCCESS) { /* IEEE 802.11r: Mobility Domain Information, Fast BSS * Transition Information, RSN, [RIC Response] */ p = wpa_sm_write_assoc_resp_ies(sta->wpa_sm, p, buf + buflen - p, sta->auth_alg, ies, ies_len); } #endif /* CONFIG_IEEE80211R_AP */ #ifdef CONFIG_OWE if (sta && (hapd->conf->wpa_key_mgmt & WPA_KEY_MGMT_OWE)) p = wpa_auth_write_assoc_resp_owe(sta->wpa_sm, p, buf + buflen - p, ies, ies_len); #endif /* CONFIG_OWE */ #ifdef CONFIG_IEEE80211W if (sta && status_code == WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY) p = hostapd_eid_assoc_comeback_time(hapd, sta, p); #endif /* CONFIG_IEEE80211W */ #ifdef CONFIG_IEEE80211N p = hostapd_eid_ht_capabilities(hapd, p); p = hostapd_eid_ht_operation(hapd, p); #endif /* CONFIG_IEEE80211N */ #ifdef CONFIG_IEEE80211AC if (hapd->iconf->ieee80211ac && !hapd->conf->disable_11ac) { u32 nsts = 0, sta_nsts; if (sta && hapd->conf->use_sta_nsts && sta->vht_capabilities) { struct ieee80211_vht_capabilities *capa; nsts = (hapd->iface->conf->vht_capab >> VHT_CAP_BEAMFORMEE_STS_OFFSET) & 7; capa = sta->vht_capabilities; sta_nsts = (le_to_host32(capa->vht_capabilities_info) >> VHT_CAP_BEAMFORMEE_STS_OFFSET) & 7; if (nsts < sta_nsts) nsts = 0; else nsts = sta_nsts; } p = hostapd_eid_vht_capabilities(hapd, p, nsts); p = hostapd_eid_vht_operation(hapd, p); } #endif /* CONFIG_IEEE80211AC */ p = hostapd_eid_ext_capab(hapd, p); p = hostapd_eid_bss_max_idle_period(hapd, p); if (sta && sta->qos_map_enabled) p = hostapd_eid_qos_map_set(hapd, p); #ifdef CONFIG_FST if (hapd->iface->fst_ies) { os_memcpy(p, wpabuf_head(hapd->iface->fst_ies), wpabuf_len(hapd->iface->fst_ies)); p += wpabuf_len(hapd->iface->fst_ies); } #endif /* CONFIG_FST */ #ifdef CONFIG_IEEE80211AC if (sta && hapd->conf->vendor_vht && (sta->flags & WLAN_STA_VENDOR_VHT)) p = hostapd_eid_vendor_vht(hapd, p); #endif /* CONFIG_IEEE80211AC */ if (sta && (sta->flags & WLAN_STA_WMM)) p = hostapd_eid_wmm(hapd, p); #ifdef CONFIG_WPS if (sta && ((sta->flags & WLAN_STA_WPS) || ((sta->flags & WLAN_STA_MAYBE_WPS) && hapd->conf->wpa))) { struct wpabuf *wps = wps_build_assoc_resp_ie(); if (wps) { os_memcpy(p, wpabuf_head(wps), wpabuf_len(wps)); p += wpabuf_len(wps); wpabuf_free(wps); } } #endif /* CONFIG_WPS */ #ifdef CONFIG_P2P if (sta && sta->p2p_ie && hapd->p2p_group) { struct wpabuf *p2p_resp_ie; enum p2p_status_code status; switch (status_code) { case WLAN_STATUS_SUCCESS: status = P2P_SC_SUCCESS; break; case WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA: status = P2P_SC_FAIL_LIMIT_REACHED; break; default: status = P2P_SC_FAIL_INVALID_PARAMS; break; } p2p_resp_ie = p2p_group_assoc_resp_ie(hapd->p2p_group, status); if (p2p_resp_ie) { os_memcpy(p, wpabuf_head(p2p_resp_ie), wpabuf_len(p2p_resp_ie)); p += wpabuf_len(p2p_resp_ie); wpabuf_free(p2p_resp_ie); } } #endif /* CONFIG_P2P */ #ifdef CONFIG_P2P_MANAGER if (hapd->conf->p2p & P2P_MANAGE) p = hostapd_eid_p2p_manage(hapd, p); #endif /* CONFIG_P2P_MANAGER */ p = hostapd_eid_mbo(hapd, p, buf + buflen - p); if (hapd->conf->assocresp_elements && (size_t) (buf + buflen - p) >= wpabuf_len(hapd->conf->assocresp_elements)) { os_memcpy(p, wpabuf_head(hapd->conf->assocresp_elements), wpabuf_len(hapd->conf->assocresp_elements)); p += wpabuf_len(hapd->conf->assocresp_elements); } send_len += p - reply->u.assoc_resp.variable; #ifdef CONFIG_FILS if (sta && (sta->auth_alg == WLAN_AUTH_FILS_SK || sta->auth_alg == WLAN_AUTH_FILS_SK_PFS || sta->auth_alg == WLAN_AUTH_FILS_PK) && status_code == WLAN_STATUS_SUCCESS) { struct ieee802_11_elems elems; if (ieee802_11_parse_elems(ies, ies_len, &elems, 0) == ParseFailed || !elems.fils_session) { res = WLAN_STATUS_UNSPECIFIED_FAILURE; goto done; } /* FILS Session */ *p++ = WLAN_EID_EXTENSION; /* Element ID */ *p++ = 1 + FILS_SESSION_LEN; /* Length */ *p++ = WLAN_EID_EXT_FILS_SESSION; /* Element ID Extension */ os_memcpy(p, elems.fils_session, FILS_SESSION_LEN); send_len += 2 + 1 + FILS_SESSION_LEN; send_len = fils_encrypt_assoc(sta->wpa_sm, buf, send_len, buflen, sta->fils_hlp_resp); if (send_len < 0) { res = WLAN_STATUS_UNSPECIFIED_FAILURE; goto done; } } #endif /* CONFIG_FILS */ #ifdef CONFIG_OWE if ((hapd->conf->wpa_key_mgmt & WPA_KEY_MGMT_OWE) && sta && sta->owe_ecdh && wpa_auth_sta_key_mgmt(sta->wpa_sm) == WPA_KEY_MGMT_OWE) { struct wpabuf *pub; pub = crypto_ecdh_get_pubkey(sta->owe_ecdh, 0); if (!pub) { res = WLAN_STATUS_UNSPECIFIED_FAILURE; goto done; } /* OWE Diffie-Hellman Parameter element */ *p++ = WLAN_EID_EXTENSION; /* Element ID */ *p++ = 1 + 2 + wpabuf_len(pub); /* Length */ *p++ = WLAN_EID_EXT_OWE_DH_PARAM; /* Element ID Extension */ WPA_PUT_LE16(p, sta->owe_group); p += 2; os_memcpy(p, wpabuf_head(pub), wpabuf_len(pub)); p += wpabuf_len(pub); send_len += 3 + 2 + wpabuf_len(pub); wpabuf_free(pub); } #endif /* CONFIG_OWE */ if (hostapd_drv_send_mlme(hapd, reply, send_len, 0) < 0) { wpa_printf(MSG_INFO, "Failed to send assoc resp: %s", strerror(errno)); res = WLAN_STATUS_UNSPECIFIED_FAILURE; } done: os_free(buf); return res; } #ifdef CONFIG_OWE u8 * owe_assoc_req_process(struct hostapd_data *hapd, struct sta_info *sta, const u8 *owe_dh, u8 owe_dh_len, u8 *owe_buf, size_t owe_buf_len, u16 *reason) { #ifdef CONFIG_TESTING_OPTIONS if (hapd->conf->own_ie_override) { wpa_printf(MSG_DEBUG, "OWE: Using IE override"); *reason = WLAN_STATUS_SUCCESS; return wpa_auth_write_assoc_resp_owe(sta->wpa_sm, owe_buf, owe_buf_len, NULL, 0); } #endif /* CONFIG_TESTING_OPTIONS */ if (wpa_auth_sta_get_pmksa(sta->wpa_sm)) { wpa_printf(MSG_DEBUG, "OWE: Using PMKSA caching"); owe_buf = wpa_auth_write_assoc_resp_owe(sta->wpa_sm, owe_buf, owe_buf_len, NULL, 0); *reason = WLAN_STATUS_SUCCESS; return owe_buf; } *reason = owe_process_assoc_req(hapd, sta, owe_dh, owe_dh_len); if (*reason != WLAN_STATUS_SUCCESS) return NULL; owe_buf = wpa_auth_write_assoc_resp_owe(sta->wpa_sm, owe_buf, owe_buf_len, NULL, 0); if (sta->owe_ecdh && owe_buf) { struct wpabuf *pub; pub = crypto_ecdh_get_pubkey(sta->owe_ecdh, 0); if (!pub) { *reason = WLAN_STATUS_UNSPECIFIED_FAILURE; return owe_buf; } /* OWE Diffie-Hellman Parameter element */ *owe_buf++ = WLAN_EID_EXTENSION; /* Element ID */ *owe_buf++ = 1 + 2 + wpabuf_len(pub); /* Length */ *owe_buf++ = WLAN_EID_EXT_OWE_DH_PARAM; /* Element ID Extension */ WPA_PUT_LE16(owe_buf, sta->owe_group); owe_buf += 2; os_memcpy(owe_buf, wpabuf_head(pub), wpabuf_len(pub)); owe_buf += wpabuf_len(pub); wpabuf_free(pub); } return owe_buf; } #endif /* CONFIG_OWE */ #ifdef CONFIG_FILS void fils_hlp_finish_assoc(struct hostapd_data *hapd, struct sta_info *sta) { u16 reply_res; wpa_printf(MSG_DEBUG, "FILS: Finish association with " MACSTR, MAC2STR(sta->addr)); eloop_cancel_timeout(fils_hlp_timeout, hapd, sta); if (!sta->fils_pending_assoc_req) return; reply_res = send_assoc_resp(hapd, sta, sta->addr, WLAN_STATUS_SUCCESS, sta->fils_pending_assoc_is_reassoc, sta->fils_pending_assoc_req, sta->fils_pending_assoc_req_len); os_free(sta->fils_pending_assoc_req); sta->fils_pending_assoc_req = NULL; sta->fils_pending_assoc_req_len = 0; wpabuf_free(sta->fils_hlp_resp); sta->fils_hlp_resp = NULL; wpabuf_free(sta->hlp_dhcp_discover); sta->hlp_dhcp_discover = NULL; /* * Remove the station in case transmission of a success response fails. * At this point the station was already added associated to the driver. */ if (reply_res != WLAN_STATUS_SUCCESS) hostapd_drv_sta_remove(hapd, sta->addr); } void fils_hlp_timeout(void *eloop_ctx, void *eloop_data) { struct hostapd_data *hapd = eloop_ctx; struct sta_info *sta = eloop_data; wpa_printf(MSG_DEBUG, "FILS: HLP response timeout - continue with association response for " MACSTR, MAC2STR(sta->addr)); if (sta->fils_drv_assoc_finish) hostapd_notify_assoc_fils_finish(hapd, sta); else fils_hlp_finish_assoc(hapd, sta); } #endif /* CONFIG_FILS */ static void handle_assoc(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int reassoc) { u16 capab_info, listen_interval, seq_ctrl, fc; u16 resp = WLAN_STATUS_SUCCESS, reply_res; const u8 *pos; int left, i; struct sta_info *sta; u8 *tmp = NULL; struct hostapd_sta_wpa_psk_short *psk = NULL; char *identity = NULL; char *radius_cui = NULL; #ifdef CONFIG_FILS int delay_assoc = 0; #endif /* CONFIG_FILS */ if (len < IEEE80211_HDRLEN + (reassoc ? sizeof(mgmt->u.reassoc_req) : sizeof(mgmt->u.assoc_req))) { wpa_printf(MSG_INFO, "handle_assoc(reassoc=%d) - too short payload (len=%lu)", reassoc, (unsigned long) len); return; } #ifdef CONFIG_TESTING_OPTIONS if (reassoc) { if (hapd->iconf->ignore_reassoc_probability > 0.0 && drand48() < hapd->iconf->ignore_reassoc_probability) { wpa_printf(MSG_INFO, "TESTING: ignoring reassoc request from " MACSTR, MAC2STR(mgmt->sa)); return; } } else { if (hapd->iconf->ignore_assoc_probability > 0.0 && drand48() < hapd->iconf->ignore_assoc_probability) { wpa_printf(MSG_INFO, "TESTING: ignoring assoc request from " MACSTR, MAC2STR(mgmt->sa)); return; } } #endif /* CONFIG_TESTING_OPTIONS */ fc = le_to_host16(mgmt->frame_control); seq_ctrl = le_to_host16(mgmt->seq_ctrl); if (reassoc) { capab_info = le_to_host16(mgmt->u.reassoc_req.capab_info); listen_interval = le_to_host16( mgmt->u.reassoc_req.listen_interval); wpa_printf(MSG_DEBUG, "reassociation request: STA=" MACSTR " capab_info=0x%02x listen_interval=%d current_ap=" MACSTR " seq_ctrl=0x%x%s", MAC2STR(mgmt->sa), capab_info, listen_interval, MAC2STR(mgmt->u.reassoc_req.current_ap), seq_ctrl, (fc & WLAN_FC_RETRY) ? " retry" : ""); left = len - (IEEE80211_HDRLEN + sizeof(mgmt->u.reassoc_req)); pos = mgmt->u.reassoc_req.variable; } else { capab_info = le_to_host16(mgmt->u.assoc_req.capab_info); listen_interval = le_to_host16( mgmt->u.assoc_req.listen_interval); wpa_printf(MSG_DEBUG, "association request: STA=" MACSTR " capab_info=0x%02x listen_interval=%d " "seq_ctrl=0x%x%s", MAC2STR(mgmt->sa), capab_info, listen_interval, seq_ctrl, (fc & WLAN_FC_RETRY) ? " retry" : ""); left = len - (IEEE80211_HDRLEN + sizeof(mgmt->u.assoc_req)); pos = mgmt->u.assoc_req.variable; } sta = ap_get_sta(hapd, mgmt->sa); #ifdef CONFIG_IEEE80211R_AP if (sta && sta->auth_alg == WLAN_AUTH_FT && (sta->flags & WLAN_STA_AUTH) == 0) { wpa_printf(MSG_DEBUG, "FT: Allow STA " MACSTR " to associate " "prior to authentication since it is using " "over-the-DS FT", MAC2STR(mgmt->sa)); /* * Mark station as authenticated, to avoid adding station * entry in the driver as associated and not authenticated */ sta->flags |= WLAN_STA_AUTH; } else #endif /* CONFIG_IEEE80211R_AP */ if (sta == NULL || (sta->flags & WLAN_STA_AUTH) == 0) { if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211AD) { int acl_res; u32 session_timeout, acct_interim_interval; struct vlan_description vlan_id; acl_res = ieee802_11_allowed_address( hapd, mgmt->sa, (const u8 *) mgmt, len, &session_timeout, &acct_interim_interval, &vlan_id, &psk, &identity, &radius_cui, 0); if (acl_res == HOSTAPD_ACL_REJECT) { wpa_msg(hapd->msg_ctx, MSG_DEBUG, "Ignore Association Request frame from " MACSTR " due to ACL reject", MAC2STR(mgmt->sa)); resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (acl_res == HOSTAPD_ACL_PENDING) return; /* DMG/IEEE 802.11ad does not use authentication. * Allocate sta entry upon association. */ sta = ap_sta_add(hapd, mgmt->sa); if (!sta) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Failed to add STA"); resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; goto fail; } acl_res = ieee802_11_set_radius_info( hapd, sta, acl_res, session_timeout, acct_interim_interval, &vlan_id, &psk, &identity, &radius_cui); if (acl_res) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Skip authentication for DMG/IEEE 802.11ad"); sta->flags |= WLAN_STA_AUTH; wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH); sta->auth_alg = WLAN_AUTH_OPEN; } else { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "Station tried to associate before authentication (aid=%d flags=0x%x)", sta ? sta->aid : -1, sta ? sta->flags : 0); send_deauth(hapd, mgmt->sa, WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA); return; } } if ((fc & WLAN_FC_RETRY) && sta->last_seq_ctrl != WLAN_INVALID_MGMT_SEQ && sta->last_seq_ctrl == seq_ctrl && sta->last_subtype == (reassoc ? WLAN_FC_STYPE_REASSOC_REQ : WLAN_FC_STYPE_ASSOC_REQ)) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Drop repeated association frame seq_ctrl=0x%x", seq_ctrl); return; } sta->last_seq_ctrl = seq_ctrl; sta->last_subtype = reassoc ? WLAN_FC_STYPE_REASSOC_REQ : WLAN_FC_STYPE_ASSOC_REQ; if (hapd->tkip_countermeasures) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (listen_interval > hapd->conf->max_listen_interval) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Too large Listen Interval (%d)", listen_interval); resp = WLAN_STATUS_ASSOC_DENIED_LISTEN_INT_TOO_LARGE; goto fail; } #ifdef CONFIG_MBO if (hapd->conf->mbo_enabled && hapd->mbo_assoc_disallow) { resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; goto fail; } #endif /* CONFIG_MBO */ /* * sta->capability is used in check_assoc_ies() for RRM enabled * capability element. */ sta->capability = capab_info; #ifdef CONFIG_FILS if (sta->auth_alg == WLAN_AUTH_FILS_SK || sta->auth_alg == WLAN_AUTH_FILS_SK_PFS || sta->auth_alg == WLAN_AUTH_FILS_PK) { int res; /* The end of the payload is encrypted. Need to decrypt it * before parsing. */ tmp = os_memdup(pos, left); if (!tmp) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } res = fils_decrypt_assoc(sta->wpa_sm, sta->fils_session, mgmt, len, tmp, left); if (res < 0) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } pos = tmp; left = res; } #endif /* CONFIG_FILS */ /* followed by SSID and Supported rates; and HT capabilities if 802.11n * is used */ resp = check_assoc_ies(hapd, sta, pos, left, reassoc); if (resp != WLAN_STATUS_SUCCESS) goto fail; if (hostapd_get_aid(hapd, sta) < 0) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "No room for more AIDs"); resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; goto fail; } sta->listen_interval = listen_interval; if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G) sta->flags |= WLAN_STA_NONERP; for (i = 0; i < sta->supported_rates_len; i++) { if ((sta->supported_rates[i] & 0x7f) > 22) { sta->flags &= ~WLAN_STA_NONERP; break; } } if (sta->flags & WLAN_STA_NONERP && !sta->nonerp_set) { sta->nonerp_set = 1; hapd->iface->num_sta_non_erp++; if (hapd->iface->num_sta_non_erp == 1) ieee802_11_set_beacons(hapd->iface); } if (!(sta->capability & WLAN_CAPABILITY_SHORT_SLOT_TIME) && !sta->no_short_slot_time_set) { sta->no_short_slot_time_set = 1; hapd->iface->num_sta_no_short_slot_time++; if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G && hapd->iface->num_sta_no_short_slot_time == 1) ieee802_11_set_beacons(hapd->iface); } if (sta->capability & WLAN_CAPABILITY_SHORT_PREAMBLE) sta->flags |= WLAN_STA_SHORT_PREAMBLE; else sta->flags &= ~WLAN_STA_SHORT_PREAMBLE; if (!(sta->capability & WLAN_CAPABILITY_SHORT_PREAMBLE) && !sta->no_short_preamble_set) { sta->no_short_preamble_set = 1; hapd->iface->num_sta_no_short_preamble++; if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G && hapd->iface->num_sta_no_short_preamble == 1) ieee802_11_set_beacons(hapd->iface); } #ifdef CONFIG_IEEE80211N update_ht_state(hapd, sta); #endif /* CONFIG_IEEE80211N */ hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "association OK (aid %d)", sta->aid); /* Station will be marked associated, after it acknowledges AssocResp */ sta->flags |= WLAN_STA_ASSOC_REQ_OK; #ifdef CONFIG_IEEE80211W if ((sta->flags & WLAN_STA_MFP) && sta->sa_query_timed_out) { wpa_printf(MSG_DEBUG, "Allowing %sassociation after timed out " "SA Query procedure", reassoc ? "re" : ""); /* TODO: Send a protected Disassociate frame to the STA using * the old key and Reason Code "Previous Authentication no * longer valid". Make sure this is only sent protected since * unprotected frame would be received by the STA that is now * trying to associate. */ } #endif /* CONFIG_IEEE80211W */ /* Make sure that the previously registered inactivity timer will not * remove the STA immediately. */ sta->timeout_next = STA_NULLFUNC; #ifdef CONFIG_TAXONOMY taxonomy_sta_info_assoc_req(hapd, sta, pos, left); #endif /* CONFIG_TAXONOMY */ sta->pending_wds_enable = 0; #ifdef CONFIG_FILS if (sta->auth_alg == WLAN_AUTH_FILS_SK || sta->auth_alg == WLAN_AUTH_FILS_SK_PFS || sta->auth_alg == WLAN_AUTH_FILS_PK) { if (fils_process_hlp(hapd, sta, pos, left) > 0) delay_assoc = 1; } #endif /* CONFIG_FILS */ fail: os_free(identity); os_free(radius_cui); hostapd_free_psk_list(psk); /* * In case of a successful response, add the station to the driver. * Otherwise, the kernel may ignore Data frames before we process the * ACK frame (TX status). In case of a failure, this station will be * removed. * * Note that this is not compliant with the IEEE 802.11 standard that * states that a non-AP station should transition into the * authenticated/associated state only after the station acknowledges * the (Re)Association Response frame. However, still do this as: * * 1. In case the station does not acknowledge the (Re)Association * Response frame, it will be removed. * 2. Data frames will be dropped in the kernel until the station is * set into authorized state, and there are no significant known * issues with processing other non-Data Class 3 frames during this * window. */ if (resp == WLAN_STATUS_SUCCESS && sta && add_associated_sta(hapd, sta)) resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; #ifdef CONFIG_FILS if (sta) { eloop_cancel_timeout(fils_hlp_timeout, hapd, sta); os_free(sta->fils_pending_assoc_req); sta->fils_pending_assoc_req = NULL; sta->fils_pending_assoc_req_len = 0; wpabuf_free(sta->fils_hlp_resp); sta->fils_hlp_resp = NULL; } if (sta && delay_assoc && resp == WLAN_STATUS_SUCCESS) { sta->fils_pending_assoc_req = tmp; sta->fils_pending_assoc_req_len = left; sta->fils_pending_assoc_is_reassoc = reassoc; sta->fils_drv_assoc_finish = 0; wpa_printf(MSG_DEBUG, "FILS: Waiting for HLP processing before sending (Re)Association Response frame to " MACSTR, MAC2STR(sta->addr)); eloop_cancel_timeout(fils_hlp_timeout, hapd, sta); eloop_register_timeout(0, hapd->conf->fils_hlp_wait_time * 1024, fils_hlp_timeout, hapd, sta); return; } #endif /* CONFIG_FILS */ reply_res = send_assoc_resp(hapd, sta, mgmt->sa, resp, reassoc, pos, left); os_free(tmp); /* * Remove the station in case tranmission of a success response fails * (the STA was added associated to the driver) or if the station was * previously added unassociated. */ if (sta && ((reply_res != WLAN_STATUS_SUCCESS && resp == WLAN_STATUS_SUCCESS) || sta->added_unassoc)) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; } } static void handle_disassoc(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len) { struct sta_info *sta; if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.disassoc)) { wpa_printf(MSG_INFO, "handle_disassoc - too short payload (len=%lu)", (unsigned long) len); return; } wpa_printf(MSG_DEBUG, "disassocation: STA=" MACSTR " reason_code=%d", MAC2STR(mgmt->sa), le_to_host16(mgmt->u.disassoc.reason_code)); sta = ap_get_sta(hapd, mgmt->sa); if (sta == NULL) { wpa_printf(MSG_INFO, "Station " MACSTR " trying to disassociate, but it is not associated", MAC2STR(mgmt->sa)); return; } ap_sta_set_authorized(hapd, sta, 0); sta->last_seq_ctrl = WLAN_INVALID_MGMT_SEQ; sta->flags &= ~(WLAN_STA_ASSOC | WLAN_STA_ASSOC_REQ_OK); wpa_auth_sm_event(sta->wpa_sm, WPA_DISASSOC); hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "disassociated"); sta->acct_terminate_cause = RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST; ieee802_1x_notify_port_enabled(sta->eapol_sm, 0); /* Stop Accounting and IEEE 802.1X sessions, but leave the STA * authenticated. */ accounting_sta_stop(hapd, sta); ieee802_1x_free_station(hapd, sta); if (sta->ipaddr) hostapd_drv_br_delete_ip_neigh(hapd, 4, (u8 *) &sta->ipaddr); ap_sta_ip6addr_del(hapd, sta); hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; if (sta->timeout_next == STA_NULLFUNC || sta->timeout_next == STA_DISASSOC) { sta->timeout_next = STA_DEAUTH; eloop_cancel_timeout(ap_handle_timer, hapd, sta); eloop_register_timeout(AP_DEAUTH_DELAY, 0, ap_handle_timer, hapd, sta); } mlme_disassociate_indication( hapd, sta, le_to_host16(mgmt->u.disassoc.reason_code)); /* DMG/IEEE 802.11ad does not use deauthication. Deallocate sta upon * disassociation. */ if (hapd->iface->current_mode && hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211AD) { sta->flags &= ~WLAN_STA_AUTH; wpa_auth_sm_event(sta->wpa_sm, WPA_DEAUTH); hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "deauthenticated"); ap_free_sta(hapd, sta); } } static void handle_deauth(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len) { struct sta_info *sta; if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.deauth)) { wpa_msg(hapd->msg_ctx, MSG_DEBUG, "handle_deauth - too short " "payload (len=%lu)", (unsigned long) len); return; } wpa_msg(hapd->msg_ctx, MSG_DEBUG, "deauthentication: STA=" MACSTR " reason_code=%d", MAC2STR(mgmt->sa), le_to_host16(mgmt->u.deauth.reason_code)); sta = ap_get_sta(hapd, mgmt->sa); if (sta == NULL) { wpa_msg(hapd->msg_ctx, MSG_DEBUG, "Station " MACSTR " trying " "to deauthenticate, but it is not authenticated", MAC2STR(mgmt->sa)); return; } ap_sta_set_authorized(hapd, sta, 0); sta->last_seq_ctrl = WLAN_INVALID_MGMT_SEQ; sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC | WLAN_STA_ASSOC_REQ_OK); wpa_auth_sm_event(sta->wpa_sm, WPA_DEAUTH); hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "deauthenticated"); mlme_deauthenticate_indication( hapd, sta, le_to_host16(mgmt->u.deauth.reason_code)); sta->acct_terminate_cause = RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST; ieee802_1x_notify_port_enabled(sta->eapol_sm, 0); ap_free_sta(hapd, sta); } static void handle_beacon(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, struct hostapd_frame_info *fi) { struct ieee802_11_elems elems; if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.beacon)) { wpa_printf(MSG_INFO, "handle_beacon - too short payload (len=%lu)", (unsigned long) len); return; } (void) ieee802_11_parse_elems(mgmt->u.beacon.variable, len - (IEEE80211_HDRLEN + sizeof(mgmt->u.beacon)), &elems, 0); ap_list_process_beacon(hapd->iface, mgmt, &elems, fi); } #ifdef CONFIG_IEEE80211W static int hostapd_sa_query_action(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len) { const u8 *end; end = mgmt->u.action.u.sa_query_resp.trans_id + WLAN_SA_QUERY_TR_ID_LEN; if (((u8 *) mgmt) + len < end) { wpa_printf(MSG_DEBUG, "IEEE 802.11: Too short SA Query Action " "frame (len=%lu)", (unsigned long) len); return 0; } ieee802_11_sa_query_action(hapd, mgmt->sa, mgmt->u.action.u.sa_query_resp.action, mgmt->u.action.u.sa_query_resp.trans_id); return 1; } static int robust_action_frame(u8 category) { return category != WLAN_ACTION_PUBLIC && category != WLAN_ACTION_HT; } #endif /* CONFIG_IEEE80211W */ static int handle_action(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, unsigned int freq) { struct sta_info *sta; sta = ap_get_sta(hapd, mgmt->sa); if (len < IEEE80211_HDRLEN + 1) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "handle_action - too short payload (len=%lu)", (unsigned long) len); return 0; } if (mgmt->u.action.category != WLAN_ACTION_PUBLIC && (sta == NULL || !(sta->flags & WLAN_STA_ASSOC))) { wpa_printf(MSG_DEBUG, "IEEE 802.11: Ignored Action " "frame (category=%u) from unassociated STA " MACSTR, mgmt->u.action.category, MAC2STR(mgmt->sa)); return 0; } #ifdef CONFIG_IEEE80211W if (sta && (sta->flags & WLAN_STA_MFP) && !(mgmt->frame_control & host_to_le16(WLAN_FC_ISWEP)) && robust_action_frame(mgmt->u.action.category)) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Dropped unprotected Robust Action frame from " "an MFP STA"); return 0; } #endif /* CONFIG_IEEE80211W */ if (sta) { u16 fc = le_to_host16(mgmt->frame_control); u16 seq_ctrl = le_to_host16(mgmt->seq_ctrl); if ((fc & WLAN_FC_RETRY) && sta->last_seq_ctrl != WLAN_INVALID_MGMT_SEQ && sta->last_seq_ctrl == seq_ctrl && sta->last_subtype == WLAN_FC_STYPE_ACTION) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "Drop repeated action frame seq_ctrl=0x%x", seq_ctrl); return 1; } sta->last_seq_ctrl = seq_ctrl; sta->last_subtype = WLAN_FC_STYPE_ACTION; } switch (mgmt->u.action.category) { #ifdef CONFIG_IEEE80211R_AP case WLAN_ACTION_FT: if (!sta || wpa_ft_action_rx(sta->wpa_sm, (u8 *) &mgmt->u.action, len - IEEE80211_HDRLEN)) break; return 1; #endif /* CONFIG_IEEE80211R_AP */ case WLAN_ACTION_WMM: hostapd_wmm_action(hapd, mgmt, len); return 1; #ifdef CONFIG_IEEE80211W case WLAN_ACTION_SA_QUERY: return hostapd_sa_query_action(hapd, mgmt, len); #endif /* CONFIG_IEEE80211W */ #ifdef CONFIG_WNM_AP case WLAN_ACTION_WNM: ieee802_11_rx_wnm_action_ap(hapd, mgmt, len); return 1; #endif /* CONFIG_WNM_AP */ #ifdef CONFIG_FST case WLAN_ACTION_FST: if (hapd->iface->fst) fst_rx_action(hapd->iface->fst, mgmt, len); else wpa_printf(MSG_DEBUG, "FST: Ignore FST Action frame - no FST attached"); return 1; #endif /* CONFIG_FST */ case WLAN_ACTION_PUBLIC: case WLAN_ACTION_PROTECTED_DUAL: #ifdef CONFIG_IEEE80211N if (len >= IEEE80211_HDRLEN + 2 && mgmt->u.action.u.public_action.action == WLAN_PA_20_40_BSS_COEX) { hostapd_2040_coex_action(hapd, mgmt, len); return 1; } #endif /* CONFIG_IEEE80211N */ #ifdef CONFIG_DPP if (len >= IEEE80211_HDRLEN + 6 && mgmt->u.action.u.vs_public_action.action == WLAN_PA_VENDOR_SPECIFIC && WPA_GET_BE24(mgmt->u.action.u.vs_public_action.oui) == OUI_WFA && mgmt->u.action.u.vs_public_action.variable[0] == DPP_OUI_TYPE) { const u8 *pos, *end; pos = mgmt->u.action.u.vs_public_action.oui; end = ((const u8 *) mgmt) + len; hostapd_dpp_rx_action(hapd, mgmt->sa, pos, end - pos, freq); return 1; } if (len >= IEEE80211_HDRLEN + 2 && (mgmt->u.action.u.public_action.action == WLAN_PA_GAS_INITIAL_RESP || mgmt->u.action.u.public_action.action == WLAN_PA_GAS_COMEBACK_RESP)) { const u8 *pos, *end; pos = &mgmt->u.action.u.public_action.action; end = ((const u8 *) mgmt) + len; gas_query_ap_rx(hapd->gas, mgmt->sa, mgmt->u.action.category, pos, end - pos, hapd->iface->freq); return 1; } #endif /* CONFIG_DPP */ if (hapd->public_action_cb) { hapd->public_action_cb(hapd->public_action_cb_ctx, (u8 *) mgmt, len, hapd->iface->freq); } if (hapd->public_action_cb2) { hapd->public_action_cb2(hapd->public_action_cb2_ctx, (u8 *) mgmt, len, hapd->iface->freq); } if (hapd->public_action_cb || hapd->public_action_cb2) return 1; break; case WLAN_ACTION_VENDOR_SPECIFIC: if (hapd->vendor_action_cb) { if (hapd->vendor_action_cb(hapd->vendor_action_cb_ctx, (u8 *) mgmt, len, hapd->iface->freq) == 0) return 1; } break; case WLAN_ACTION_RADIO_MEASUREMENT: hostapd_handle_radio_measurement(hapd, (const u8 *) mgmt, len); return 1; } hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "handle_action - unknown action category %d or invalid " "frame", mgmt->u.action.category); if (!is_multicast_ether_addr(mgmt->da) && !(mgmt->u.action.category & 0x80) && !is_multicast_ether_addr(mgmt->sa)) { struct ieee80211_mgmt *resp; /* * IEEE 802.11-REVma/D9.0 - 7.3.1.11 * Return the Action frame to the source without change * except that MSB of the Category set to 1. */ wpa_printf(MSG_DEBUG, "IEEE 802.11: Return unknown Action " "frame back to sender"); resp = os_memdup(mgmt, len); if (resp == NULL) return 0; os_memcpy(resp->da, resp->sa, ETH_ALEN); os_memcpy(resp->sa, hapd->own_addr, ETH_ALEN); os_memcpy(resp->bssid, hapd->own_addr, ETH_ALEN); resp->u.action.category |= 0x80; if (hostapd_drv_send_mlme(hapd, resp, len, 0) < 0) { wpa_printf(MSG_ERROR, "IEEE 802.11: Failed to send " "Action frame"); } os_free(resp); } return 1; } /** * ieee802_11_mgmt - process incoming IEEE 802.11 management frames * @hapd: hostapd BSS data structure (the BSS to which the management frame was * sent to) * @buf: management frame data (starting from IEEE 802.11 header) * @len: length of frame data in octets * @fi: meta data about received frame (signal level, etc.) * * Process all incoming IEEE 802.11 management frames. This will be called for * each frame received from the kernel driver through wlan#ap interface. In * addition, it can be called to re-inserted pending frames (e.g., when using * external RADIUS server as an MAC ACL). */ int ieee802_11_mgmt(struct hostapd_data *hapd, const u8 *buf, size_t len, struct hostapd_frame_info *fi) { struct ieee80211_mgmt *mgmt; u16 fc, stype; int ret = 0; unsigned int freq; int ssi_signal = fi ? fi->ssi_signal : 0; if (len < 24) return 0; if (fi && fi->freq) freq = fi->freq; else freq = hapd->iface->freq; mgmt = (struct ieee80211_mgmt *) buf; fc = le_to_host16(mgmt->frame_control); stype = WLAN_FC_GET_STYPE(fc); if (stype == WLAN_FC_STYPE_BEACON) { handle_beacon(hapd, mgmt, len, fi); return 1; } if (!is_broadcast_ether_addr(mgmt->bssid) && #ifdef CONFIG_P2P /* Invitation responses can be sent with the peer MAC as BSSID */ !((hapd->conf->p2p & P2P_GROUP_OWNER) && stype == WLAN_FC_STYPE_ACTION) && #endif /* CONFIG_P2P */ #ifdef CONFIG_MESH !(hapd->conf->mesh & MESH_ENABLED) && #endif /* CONFIG_MESH */ os_memcmp(mgmt->bssid, hapd->own_addr, ETH_ALEN) != 0) { wpa_printf(MSG_INFO, "MGMT: BSSID=" MACSTR " not our address", MAC2STR(mgmt->bssid)); return 0; } if (stype == WLAN_FC_STYPE_PROBE_REQ) { handle_probe_req(hapd, mgmt, len, ssi_signal); return 1; } if ((!is_broadcast_ether_addr(mgmt->da) || stype != WLAN_FC_STYPE_ACTION) && os_memcmp(mgmt->da, hapd->own_addr, ETH_ALEN) != 0) { hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "MGMT: DA=" MACSTR " not our address", MAC2STR(mgmt->da)); return 0; } if (hapd->iconf->track_sta_max_num) sta_track_add(hapd->iface, mgmt->sa, ssi_signal); switch (stype) { case WLAN_FC_STYPE_AUTH: wpa_printf(MSG_DEBUG, "mgmt::auth"); handle_auth(hapd, mgmt, len); ret = 1; break; case WLAN_FC_STYPE_ASSOC_REQ: wpa_printf(MSG_DEBUG, "mgmt::assoc_req"); handle_assoc(hapd, mgmt, len, 0); ret = 1; break; case WLAN_FC_STYPE_REASSOC_REQ: wpa_printf(MSG_DEBUG, "mgmt::reassoc_req"); handle_assoc(hapd, mgmt, len, 1); ret = 1; break; case WLAN_FC_STYPE_DISASSOC: wpa_printf(MSG_DEBUG, "mgmt::disassoc"); handle_disassoc(hapd, mgmt, len); ret = 1; break; case WLAN_FC_STYPE_DEAUTH: wpa_msg(hapd->msg_ctx, MSG_DEBUG, "mgmt::deauth"); handle_deauth(hapd, mgmt, len); ret = 1; break; case WLAN_FC_STYPE_ACTION: wpa_printf(MSG_DEBUG, "mgmt::action"); ret = handle_action(hapd, mgmt, len, freq); break; default: hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "unknown mgmt frame subtype %d", stype); break; } return ret; } static void handle_auth_cb(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int ok) { u16 auth_alg, auth_transaction, status_code; struct sta_info *sta; sta = ap_get_sta(hapd, mgmt->da); if (!sta) { wpa_printf(MSG_INFO, "handle_auth_cb: STA " MACSTR " not found", MAC2STR(mgmt->da)); return; } auth_alg = le_to_host16(mgmt->u.auth.auth_alg); auth_transaction = le_to_host16(mgmt->u.auth.auth_transaction); status_code = le_to_host16(mgmt->u.auth.status_code); if (!ok) { hostapd_logger(hapd, mgmt->da, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_NOTICE, "did not acknowledge authentication response"); goto fail; } if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.auth)) { wpa_printf(MSG_INFO, "handle_auth_cb - too short payload (len=%lu)", (unsigned long) len); goto fail; } if (status_code == WLAN_STATUS_SUCCESS && ((auth_alg == WLAN_AUTH_OPEN && auth_transaction == 2) || (auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 4))) { hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "authenticated"); sta->flags |= WLAN_STA_AUTH; if (sta->added_unassoc) hostapd_set_sta_flags(hapd, sta); return; } fail: if (status_code != WLAN_STATUS_SUCCESS && sta->added_unassoc) { hostapd_drv_sta_remove(hapd, sta->addr); sta->added_unassoc = 0; } } static void hostapd_set_wds_encryption(struct hostapd_data *hapd, struct sta_info *sta, char *ifname_wds) { int i; struct hostapd_ssid *ssid = &hapd->conf->ssid; if (hapd->conf->ieee802_1x || hapd->conf->wpa) return; for (i = 0; i < 4; i++) { if (ssid->wep.key[i] && hostapd_drv_set_key(ifname_wds, hapd, WPA_ALG_WEP, NULL, i, i == ssid->wep.idx, NULL, 0, ssid->wep.key[i], ssid->wep.len[i])) { wpa_printf(MSG_WARNING, "Could not set WEP keys for WDS interface; %s", ifname_wds); break; } } } static void handle_assoc_cb(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int reassoc, int ok) { u16 status; struct sta_info *sta; int new_assoc = 1; sta = ap_get_sta(hapd, mgmt->da); if (!sta) { wpa_printf(MSG_INFO, "handle_assoc_cb: STA " MACSTR " not found", MAC2STR(mgmt->da)); return; } if (len < IEEE80211_HDRLEN + (reassoc ? sizeof(mgmt->u.reassoc_resp) : sizeof(mgmt->u.assoc_resp))) { wpa_printf(MSG_INFO, "handle_assoc_cb(reassoc=%d) - too short payload (len=%lu)", reassoc, (unsigned long) len); hostapd_drv_sta_remove(hapd, sta->addr); return; } if (reassoc) status = le_to_host16(mgmt->u.reassoc_resp.status_code); else status = le_to_host16(mgmt->u.assoc_resp.status_code); if (!ok) { hostapd_logger(hapd, mgmt->da, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_DEBUG, "did not acknowledge association response"); sta->flags &= ~WLAN_STA_ASSOC_REQ_OK; /* The STA is added only in case of SUCCESS */ if (status == WLAN_STATUS_SUCCESS) hostapd_drv_sta_remove(hapd, sta->addr); return; } if (status != WLAN_STATUS_SUCCESS) return; /* Stop previous accounting session, if one is started, and allocate * new session id for the new session. */ accounting_sta_stop(hapd, sta); hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_INFO, "associated (aid %d)", sta->aid); if (sta->flags & WLAN_STA_ASSOC) new_assoc = 0; sta->flags |= WLAN_STA_ASSOC; sta->flags &= ~WLAN_STA_WNM_SLEEP_MODE; if ((!hapd->conf->ieee802_1x && !hapd->conf->wpa && !hapd->conf->osen) || sta->auth_alg == WLAN_AUTH_FILS_SK || sta->auth_alg == WLAN_AUTH_FILS_SK_PFS || sta->auth_alg == WLAN_AUTH_FILS_PK || sta->auth_alg == WLAN_AUTH_FT) { /* * Open, static WEP, FT protocol, or FILS; no separate * authorization step. */ ap_sta_set_authorized(hapd, sta, 1); } if (reassoc) mlme_reassociate_indication(hapd, sta); else mlme_associate_indication(hapd, sta); #ifdef CONFIG_IEEE80211W sta->sa_query_timed_out = 0; #endif /* CONFIG_IEEE80211W */ if (sta->eapol_sm == NULL) { /* * This STA does not use RADIUS server for EAP authentication, * so bind it to the selected VLAN interface now, since the * interface selection is not going to change anymore. */ if (ap_sta_bind_vlan(hapd, sta) < 0) return; } else if (sta->vlan_id) { /* VLAN ID already set (e.g., by PMKSA caching), so bind STA */ if (ap_sta_bind_vlan(hapd, sta) < 0) return; } hostapd_set_sta_flags(hapd, sta); if (!(sta->flags & WLAN_STA_WDS) && sta->pending_wds_enable) { wpa_printf(MSG_DEBUG, "Enable 4-address WDS mode for STA " MACSTR " based on pending request", MAC2STR(sta->addr)); sta->pending_wds_enable = 0; sta->flags |= WLAN_STA_WDS; } if (sta->flags & WLAN_STA_WDS) { int ret; char ifname_wds[IFNAMSIZ + 1]; wpa_printf(MSG_DEBUG, "Reenable 4-address WDS mode for STA " MACSTR " (aid %u)", MAC2STR(sta->addr), sta->aid); ret = hostapd_set_wds_sta(hapd, ifname_wds, sta->addr, sta->aid, 1); if (!ret) hostapd_set_wds_encryption(hapd, sta, ifname_wds); } if (sta->auth_alg == WLAN_AUTH_FT) wpa_auth_sm_event(sta->wpa_sm, WPA_ASSOC_FT); else wpa_auth_sm_event(sta->wpa_sm, WPA_ASSOC); hapd->new_assoc_sta_cb(hapd, sta, !new_assoc); ieee802_1x_notify_port_enabled(sta->eapol_sm, 1); #ifdef CONFIG_FILS if ((sta->auth_alg == WLAN_AUTH_FILS_SK || sta->auth_alg == WLAN_AUTH_FILS_SK_PFS || sta->auth_alg == WLAN_AUTH_FILS_PK) && fils_set_tk(sta->wpa_sm) < 0) { wpa_printf(MSG_DEBUG, "FILS: TK configuration failed"); ap_sta_disconnect(hapd, sta, sta->addr, WLAN_REASON_UNSPECIFIED); return; } #endif /* CONFIG_FILS */ if (sta->pending_eapol_rx) { struct os_reltime now, age; os_get_reltime(&now); os_reltime_sub(&now, &sta->pending_eapol_rx->rx_time, &age); if (age.sec == 0 && age.usec < 200000) { wpa_printf(MSG_DEBUG, "Process pending EAPOL frame that was received from " MACSTR " just before association notification", MAC2STR(sta->addr)); ieee802_1x_receive( hapd, mgmt->da, wpabuf_head(sta->pending_eapol_rx->buf), wpabuf_len(sta->pending_eapol_rx->buf)); } wpabuf_free(sta->pending_eapol_rx->buf); os_free(sta->pending_eapol_rx); sta->pending_eapol_rx = NULL; } } static void handle_deauth_cb(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int ok) { struct sta_info *sta; if (is_multicast_ether_addr(mgmt->da)) return; sta = ap_get_sta(hapd, mgmt->da); if (!sta) { wpa_printf(MSG_DEBUG, "handle_deauth_cb: STA " MACSTR " not found", MAC2STR(mgmt->da)); return; } if (ok) wpa_printf(MSG_DEBUG, "STA " MACSTR " acknowledged deauth", MAC2STR(sta->addr)); else wpa_printf(MSG_DEBUG, "STA " MACSTR " did not acknowledge " "deauth", MAC2STR(sta->addr)); ap_sta_deauth_cb(hapd, sta); } static void handle_disassoc_cb(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int ok) { struct sta_info *sta; if (is_multicast_ether_addr(mgmt->da)) return; sta = ap_get_sta(hapd, mgmt->da); if (!sta) { wpa_printf(MSG_DEBUG, "handle_disassoc_cb: STA " MACSTR " not found", MAC2STR(mgmt->da)); return; } if (ok) wpa_printf(MSG_DEBUG, "STA " MACSTR " acknowledged disassoc", MAC2STR(sta->addr)); else wpa_printf(MSG_DEBUG, "STA " MACSTR " did not acknowledge " "disassoc", MAC2STR(sta->addr)); ap_sta_disassoc_cb(hapd, sta); } static void handle_action_cb(struct hostapd_data *hapd, const struct ieee80211_mgmt *mgmt, size_t len, int ok) { struct sta_info *sta; const struct rrm_measurement_report_element *report; if (is_multicast_ether_addr(mgmt->da)) return; #ifdef CONFIG_DPP if (len >= IEEE80211_HDRLEN + 6 && mgmt->u.action.category == WLAN_ACTION_PUBLIC && mgmt->u.action.u.vs_public_action.action == WLAN_PA_VENDOR_SPECIFIC && WPA_GET_BE24(mgmt->u.action.u.vs_public_action.oui) == OUI_WFA && mgmt->u.action.u.vs_public_action.variable[0] == DPP_OUI_TYPE) { const u8 *pos, *end; pos = &mgmt->u.action.u.vs_public_action.variable[1]; end = ((const u8 *) mgmt) + len; hostapd_dpp_tx_status(hapd, mgmt->da, pos, end - pos, ok); return; } if (len >= IEEE80211_HDRLEN + 2 && mgmt->u.action.category == WLAN_ACTION_PUBLIC && (mgmt->u.action.u.public_action.action == WLAN_PA_GAS_INITIAL_REQ || mgmt->u.action.u.public_action.action == WLAN_PA_GAS_COMEBACK_REQ)) { const u8 *pos, *end; pos = mgmt->u.action.u.public_action.variable; end = ((const u8 *) mgmt) + len; gas_query_ap_tx_status(hapd->gas, mgmt->da, pos, end - pos, ok); return; } #endif /* CONFIG_DPP */ sta = ap_get_sta(hapd, mgmt->da); if (!sta) { wpa_printf(MSG_DEBUG, "handle_action_cb: STA " MACSTR " not found", MAC2STR(mgmt->da)); return; } if (len < 24 + 5 + sizeof(*report)) return; report = (const struct rrm_measurement_report_element *) &mgmt->u.action.u.rrm.variable[2]; if (mgmt->u.action.category == WLAN_ACTION_RADIO_MEASUREMENT && mgmt->u.action.u.rrm.action == WLAN_RRM_RADIO_MEASUREMENT_REQUEST && report->eid == WLAN_EID_MEASURE_REQUEST && report->len >= 3 && report->type == MEASURE_TYPE_BEACON) hostapd_rrm_beacon_req_tx_status(hapd, mgmt, len, ok); } /** * ieee802_11_mgmt_cb - Process management frame TX status callback * @hapd: hostapd BSS data structure (the BSS from which the management frame * was sent from) * @buf: management frame data (starting from IEEE 802.11 header) * @len: length of frame data in octets * @stype: management frame subtype from frame control field * @ok: Whether the frame was ACK'ed */ void ieee802_11_mgmt_cb(struct hostapd_data *hapd, const u8 *buf, size_t len, u16 stype, int ok) { const struct ieee80211_mgmt *mgmt; mgmt = (const struct ieee80211_mgmt *) buf; #ifdef CONFIG_TESTING_OPTIONS if (hapd->ext_mgmt_frame_handling) { size_t hex_len = 2 * len + 1; char *hex = os_malloc(hex_len); if (hex) { wpa_snprintf_hex(hex, hex_len, buf, len); wpa_msg(hapd->msg_ctx, MSG_INFO, "MGMT-TX-STATUS stype=%u ok=%d buf=%s", stype, ok, hex); os_free(hex); } return; } #endif /* CONFIG_TESTING_OPTIONS */ switch (stype) { case WLAN_FC_STYPE_AUTH: wpa_printf(MSG_DEBUG, "mgmt::auth cb"); handle_auth_cb(hapd, mgmt, len, ok); break; case WLAN_FC_STYPE_ASSOC_RESP: wpa_printf(MSG_DEBUG, "mgmt::assoc_resp cb"); handle_assoc_cb(hapd, mgmt, len, 0, ok); break; case WLAN_FC_STYPE_REASSOC_RESP: wpa_printf(MSG_DEBUG, "mgmt::reassoc_resp cb"); handle_assoc_cb(hapd, mgmt, len, 1, ok); break; case WLAN_FC_STYPE_PROBE_RESP: wpa_printf(MSG_EXCESSIVE, "mgmt::proberesp cb ok=%d", ok); break; case WLAN_FC_STYPE_DEAUTH: wpa_printf(MSG_DEBUG, "mgmt::deauth cb"); handle_deauth_cb(hapd, mgmt, len, ok); break; case WLAN_FC_STYPE_DISASSOC: wpa_printf(MSG_DEBUG, "mgmt::disassoc cb"); handle_disassoc_cb(hapd, mgmt, len, ok); break; case WLAN_FC_STYPE_ACTION: wpa_printf(MSG_DEBUG, "mgmt::action cb ok=%d", ok); handle_action_cb(hapd, mgmt, len, ok); break; default: wpa_printf(MSG_INFO, "unknown mgmt cb frame subtype %d", stype); break; } } int ieee802_11_get_mib(struct hostapd_data *hapd, char *buf, size_t buflen) { /* TODO */ return 0; } int ieee802_11_get_mib_sta(struct hostapd_data *hapd, struct sta_info *sta, char *buf, size_t buflen) { /* TODO */ return 0; } void hostapd_tx_status(struct hostapd_data *hapd, const u8 *addr, const u8 *buf, size_t len, int ack) { struct sta_info *sta; struct hostapd_iface *iface = hapd->iface; sta = ap_get_sta(hapd, addr); if (sta == NULL && iface->num_bss > 1) { size_t j; for (j = 0; j < iface->num_bss; j++) { hapd = iface->bss[j]; sta = ap_get_sta(hapd, addr); if (sta) break; } } if (sta == NULL || !(sta->flags & WLAN_STA_ASSOC)) return; if (sta->flags & WLAN_STA_PENDING_POLL) { wpa_printf(MSG_DEBUG, "STA " MACSTR " %s pending " "activity poll", MAC2STR(sta->addr), ack ? "ACKed" : "did not ACK"); if (ack) sta->flags &= ~WLAN_STA_PENDING_POLL; } ieee802_1x_tx_status(hapd, sta, buf, len, ack); } void hostapd_eapol_tx_status(struct hostapd_data *hapd, const u8 *dst, const u8 *data, size_t len, int ack) { struct sta_info *sta; struct hostapd_iface *iface = hapd->iface; sta = ap_get_sta(hapd, dst); if (sta == NULL && iface->num_bss > 1) { size_t j; for (j = 0; j < iface->num_bss; j++) { hapd = iface->bss[j]; sta = ap_get_sta(hapd, dst); if (sta) break; } } if (sta == NULL || !(sta->flags & WLAN_STA_ASSOC)) { wpa_printf(MSG_DEBUG, "Ignore TX status for Data frame to STA " MACSTR " that is not currently associated", MAC2STR(dst)); return; } ieee802_1x_eapol_tx_status(hapd, sta, data, len, ack); } void hostapd_client_poll_ok(struct hostapd_data *hapd, const u8 *addr) { struct sta_info *sta; struct hostapd_iface *iface = hapd->iface; sta = ap_get_sta(hapd, addr); if (sta == NULL && iface->num_bss > 1) { size_t j; for (j = 0; j < iface->num_bss; j++) { hapd = iface->bss[j]; sta = ap_get_sta(hapd, addr); if (sta) break; } } if (sta == NULL) return; wpa_msg(hapd->msg_ctx, MSG_INFO, AP_STA_POLL_OK MACSTR, MAC2STR(sta->addr)); if (!(sta->flags & WLAN_STA_PENDING_POLL)) return; wpa_printf(MSG_DEBUG, "STA " MACSTR " ACKed pending " "activity poll", MAC2STR(sta->addr)); sta->flags &= ~WLAN_STA_PENDING_POLL; } void ieee802_11_rx_from_unknown(struct hostapd_data *hapd, const u8 *src, int wds) { struct sta_info *sta; sta = ap_get_sta(hapd, src); if (sta && ((sta->flags & WLAN_STA_ASSOC) || ((sta->flags & WLAN_STA_ASSOC_REQ_OK) && wds))) { if (!hapd->conf->wds_sta) return; if ((sta->flags & (WLAN_STA_ASSOC | WLAN_STA_ASSOC_REQ_OK)) == WLAN_STA_ASSOC_REQ_OK) { wpa_printf(MSG_DEBUG, "Postpone 4-address WDS mode enabling for STA " MACSTR " since TX status for AssocResp is not yet known", MAC2STR(sta->addr)); sta->pending_wds_enable = 1; return; } if (wds && !(sta->flags & WLAN_STA_WDS)) { int ret; char ifname_wds[IFNAMSIZ + 1]; wpa_printf(MSG_DEBUG, "Enable 4-address WDS mode for " "STA " MACSTR " (aid %u)", MAC2STR(sta->addr), sta->aid); sta->flags |= WLAN_STA_WDS; ret = hostapd_set_wds_sta(hapd, ifname_wds, sta->addr, sta->aid, 1); if (!ret) hostapd_set_wds_encryption(hapd, sta, ifname_wds); } return; } wpa_printf(MSG_DEBUG, "Data/PS-poll frame from not associated STA " MACSTR, MAC2STR(src)); if (is_multicast_ether_addr(src)) { /* Broadcast bit set in SA?! Ignore the frame silently. */ return; } if (sta && (sta->flags & WLAN_STA_ASSOC_REQ_OK)) { wpa_printf(MSG_DEBUG, "Association Response to the STA has " "already been sent, but no TX status yet known - " "ignore Class 3 frame issue with " MACSTR, MAC2STR(src)); return; } if (sta && (sta->flags & WLAN_STA_AUTH)) hostapd_drv_sta_disassoc( hapd, src, WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA); else hostapd_drv_sta_deauth( hapd, src, WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA); } #endif /* CONFIG_NATIVE_WINDOWS */
5ca4f19e5b7c41b4cc774b48bf7e3bdef59e9878
52c8ed39b32ccc7c0673278c1adea3638797c9ff
/src/external/cairo-1.17.4/cairo-polygon.c
0e0b81328531d279147cd87ef2f7f3f2c56c587a
[ "MIT" ]
permissive
xboot/xboot
0cab7b440b612aa0a4c366025598a53a7ec3adf1
6d6b93947b7fcb8c3924fedb0715c23877eedd5e
refs/heads/master
2023-08-20T05:56:25.149388
2023-07-12T07:38:29
2023-07-12T07:38:29
471,539
765
296
MIT
2023-05-25T09:39:01
2010-01-14T08:25:12
C
UTF-8
C
false
false
16,796
c
cairo-polygon.c
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */ /* cairo - a vector graphics library with display and print output * * Copyright © 2002 University of Southern California * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL") or, at your option, under the terms of the Mozilla * Public License Version 1.1 (the "MPL"). If you do not alter this * notice, a recipient may use your version of this file under either * the MPL or the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA * You should have received a copy of the MPL along with this library * in the file COPYING-MPL-1.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/ * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY * OF ANY KIND, either express or implied. See the LGPL or the MPL for * the specific language governing rights and limitations. * * The Original Code is the cairo graphics library. * * The Initial Developer of the Original Code is University of Southern * California. * * Contributor(s): * Carl D. Worth <cworth@cworth.org> */ #include "cairoint.h" #include "cairo-boxes-private.h" #include "cairo-contour-private.h" #include "cairo-error-private.h" #define DEBUG_POLYGON 0 #if DEBUG_POLYGON && !NDEBUG static void assert_last_edge_is_valid(cairo_polygon_t *polygon, const cairo_box_t *limit) { cairo_edge_t *edge; cairo_fixed_t x; edge = &polygon->edges[polygon->num_edges-1]; assert (edge->bottom > edge->top); assert (edge->top >= limit->p1.y); assert (edge->bottom <= limit->p2.y); x = _cairo_edge_compute_intersection_x_for_y (&edge->line.p1, &edge->line.p2, edge->top); assert (x >= limit->p1.x); assert (x <= limit->p2.x); x = _cairo_edge_compute_intersection_x_for_y (&edge->line.p1, &edge->line.p2, edge->bottom); assert (x >= limit->p1.x); assert (x <= limit->p2.x); } #else #define assert_last_edge_is_valid(p, l) #endif static void _cairo_polygon_add_edge (cairo_polygon_t *polygon, const cairo_point_t *p1, const cairo_point_t *p2, int dir); void _cairo_polygon_limit (cairo_polygon_t *polygon, const cairo_box_t *limits, int num_limits) { int n; polygon->limits = limits; polygon->num_limits = num_limits; if (polygon->num_limits) { polygon->limit = limits[0]; for (n = 1; n < num_limits; n++) { if (limits[n].p1.x < polygon->limit.p1.x) polygon->limit.p1.x = limits[n].p1.x; if (limits[n].p1.y < polygon->limit.p1.y) polygon->limit.p1.y = limits[n].p1.y; if (limits[n].p2.x > polygon->limit.p2.x) polygon->limit.p2.x = limits[n].p2.x; if (limits[n].p2.y > polygon->limit.p2.y) polygon->limit.p2.y = limits[n].p2.y; } } } void _cairo_polygon_limit_to_clip (cairo_polygon_t *polygon, const cairo_clip_t *clip) { if (clip) _cairo_polygon_limit (polygon, clip->boxes, clip->num_boxes); else _cairo_polygon_limit (polygon, 0, 0); } void _cairo_polygon_init (cairo_polygon_t *polygon, const cairo_box_t *limits, int num_limits) { VG (VALGRIND_MAKE_MEM_UNDEFINED (polygon, sizeof (cairo_polygon_t))); polygon->status = CAIRO_STATUS_SUCCESS; polygon->num_edges = 0; polygon->edges = polygon->edges_embedded; polygon->edges_size = ARRAY_LENGTH (polygon->edges_embedded); polygon->extents.p1.x = polygon->extents.p1.y = INT32_MAX; polygon->extents.p2.x = polygon->extents.p2.y = INT32_MIN; _cairo_polygon_limit (polygon, limits, num_limits); } void _cairo_polygon_init_with_clip (cairo_polygon_t *polygon, const cairo_clip_t *clip) { if (clip) _cairo_polygon_init (polygon, clip->boxes, clip->num_boxes); else _cairo_polygon_init (polygon, 0, 0); } cairo_status_t _cairo_polygon_init_boxes (cairo_polygon_t *polygon, const cairo_boxes_t *boxes) { const struct _cairo_boxes_chunk *chunk; int i; VG (VALGRIND_MAKE_MEM_UNDEFINED (polygon, sizeof (cairo_polygon_t))); polygon->status = CAIRO_STATUS_SUCCESS; polygon->num_edges = 0; polygon->edges = polygon->edges_embedded; polygon->edges_size = ARRAY_LENGTH (polygon->edges_embedded); if (boxes->num_boxes > ARRAY_LENGTH (polygon->edges_embedded)/2) { polygon->edges_size = 2 * boxes->num_boxes; polygon->edges = _cairo_malloc_ab (polygon->edges_size, 2*sizeof(cairo_edge_t)); if (unlikely (polygon->edges == NULL)) return polygon->status = _cairo_error (CAIRO_STATUS_NO_MEMORY); } polygon->extents.p1.x = polygon->extents.p1.y = INT32_MAX; polygon->extents.p2.x = polygon->extents.p2.y = INT32_MIN; polygon->limits = NULL; polygon->num_limits = 0; for (chunk = &boxes->chunks; chunk != NULL; chunk = chunk->next) { for (i = 0; i < chunk->count; i++) { cairo_point_t p1, p2; p1 = chunk->base[i].p1; p2.x = p1.x; p2.y = chunk->base[i].p2.y; _cairo_polygon_add_edge (polygon, &p1, &p2, 1); p1 = chunk->base[i].p2; p2.x = p1.x; p2.y = chunk->base[i].p1.y; _cairo_polygon_add_edge (polygon, &p1, &p2, 1); } } return polygon->status; } cairo_status_t _cairo_polygon_init_box_array (cairo_polygon_t *polygon, cairo_box_t *boxes, int num_boxes) { int i; VG (VALGRIND_MAKE_MEM_UNDEFINED (polygon, sizeof (cairo_polygon_t))); polygon->status = CAIRO_STATUS_SUCCESS; polygon->num_edges = 0; polygon->edges = polygon->edges_embedded; polygon->edges_size = ARRAY_LENGTH (polygon->edges_embedded); if (num_boxes > ARRAY_LENGTH (polygon->edges_embedded)/2) { polygon->edges_size = 2 * num_boxes; polygon->edges = _cairo_malloc_ab (polygon->edges_size, 2*sizeof(cairo_edge_t)); if (unlikely (polygon->edges == NULL)) return polygon->status = _cairo_error (CAIRO_STATUS_NO_MEMORY); } polygon->extents.p1.x = polygon->extents.p1.y = INT32_MAX; polygon->extents.p2.x = polygon->extents.p2.y = INT32_MIN; polygon->limits = NULL; polygon->num_limits = 0; for (i = 0; i < num_boxes; i++) { cairo_point_t p1, p2; p1 = boxes[i].p1; p2.x = p1.x; p2.y = boxes[i].p2.y; _cairo_polygon_add_edge (polygon, &p1, &p2, 1); p1 = boxes[i].p2; p2.x = p1.x; p2.y = boxes[i].p1.y; _cairo_polygon_add_edge (polygon, &p1, &p2, 1); } return polygon->status; } void _cairo_polygon_fini (cairo_polygon_t *polygon) { if (polygon->edges != polygon->edges_embedded) free (polygon->edges); VG (VALGRIND_MAKE_MEM_UNDEFINED (polygon, sizeof (cairo_polygon_t))); } /* make room for at least one more edge */ static cairo_bool_t _cairo_polygon_grow (cairo_polygon_t *polygon) { cairo_edge_t *new_edges; int old_size = polygon->edges_size; int new_size = 4 * old_size; if (CAIRO_INJECT_FAULT ()) { polygon->status = _cairo_error (CAIRO_STATUS_NO_MEMORY); return FALSE; } if (polygon->edges == polygon->edges_embedded) { new_edges = _cairo_malloc_ab (new_size, sizeof (cairo_edge_t)); if (new_edges != NULL) memcpy (new_edges, polygon->edges, old_size * sizeof (cairo_edge_t)); } else { new_edges = _cairo_realloc_ab (polygon->edges, new_size, sizeof (cairo_edge_t)); } if (unlikely (new_edges == NULL)) { polygon->status = _cairo_error (CAIRO_STATUS_NO_MEMORY); return FALSE; } polygon->edges = new_edges; polygon->edges_size = new_size; return TRUE; } static void _add_edge (cairo_polygon_t *polygon, const cairo_point_t *p1, const cairo_point_t *p2, int top, int bottom, int dir) { cairo_edge_t *edge; assert (top < bottom); if (unlikely (polygon->num_edges == polygon->edges_size)) { if (! _cairo_polygon_grow (polygon)) return; } edge = &polygon->edges[polygon->num_edges++]; edge->line.p1 = *p1; edge->line.p2 = *p2; edge->top = top; edge->bottom = bottom; edge->dir = dir; if (top < polygon->extents.p1.y) polygon->extents.p1.y = top; if (bottom > polygon->extents.p2.y) polygon->extents.p2.y = bottom; if (p1->x < polygon->extents.p1.x || p1->x > polygon->extents.p2.x) { cairo_fixed_t x = p1->x; if (top != p1->y) x = _cairo_edge_compute_intersection_x_for_y (p1, p2, top); if (x < polygon->extents.p1.x) polygon->extents.p1.x = x; if (x > polygon->extents.p2.x) polygon->extents.p2.x = x; } if (p2->x < polygon->extents.p1.x || p2->x > polygon->extents.p2.x) { cairo_fixed_t x = p2->x; if (bottom != p2->y) x = _cairo_edge_compute_intersection_x_for_y (p1, p2, bottom); if (x < polygon->extents.p1.x) polygon->extents.p1.x = x; if (x > polygon->extents.p2.x) polygon->extents.p2.x = x; } } static void _add_clipped_edge (cairo_polygon_t *polygon, const cairo_point_t *p1, const cairo_point_t *p2, const int top, const int bottom, const int dir) { cairo_point_t bot_left, top_right; cairo_fixed_t top_y, bot_y; int n; for (n = 0; n < polygon->num_limits; n++) { const cairo_box_t *limits = &polygon->limits[n]; cairo_fixed_t pleft, pright; if (top >= limits->p2.y) continue; if (bottom <= limits->p1.y) continue; bot_left.x = limits->p1.x; bot_left.y = limits->p2.y; top_right.x = limits->p2.x; top_right.y = limits->p1.y; /* The useful region */ top_y = MAX (top, limits->p1.y); bot_y = MIN (bottom, limits->p2.y); /* The projection of the edge on the horizontal axis */ pleft = MIN (p1->x, p2->x); pright = MAX (p1->x, p2->x); if (limits->p1.x <= pleft && pright <= limits->p2.x) { /* Projection of the edge completely contained in the box: * clip vertically by restricting top and bottom */ _add_edge (polygon, p1, p2, top_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); } else if (pright <= limits->p1.x) { /* Projection of the edge to the left of the box: * replace with the left side of the box (clipped top/bottom) */ _add_edge (polygon, &limits->p1, &bot_left, top_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); } else if (limits->p2.x <= pleft) { /* Projection of the edge to the right of the box: * replace with the right side of the box (clipped top/bottom) */ _add_edge (polygon, &top_right, &limits->p2, top_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); } else { /* The edge and the box intersect in a generic way */ cairo_fixed_t left_y, right_y; cairo_bool_t top_left_to_bottom_right; /* * The edge intersects the lines corresponding to the left * and right sides of the limit box at left_y and right_y, * but we need to add edges for the range from top_y to * bot_y. * * For both intersections, there are three cases: * * 1) It is outside the vertical range of the limit * box. In this case we can simply further clip the * edge we will be emitting (i.e. restrict its * top/bottom limits to those of the limit box). * * 2) It is inside the vertical range of the limit * box. In this case, we need to add the vertical edge * connecting the correct vertex to the intersection, * in order to preserve the winding count. * * 3) It is exactly on the box. In this case, do nothing. * * These operations restrict the active range (stored in * top_y/bot_y) so that the p1-p2 edge is completely * inside the box if it is clipped to this vertical range. */ top_left_to_bottom_right = (p1->x <= p2->x) == (p1->y <= p2->y); if (top_left_to_bottom_right) { if (pleft >= limits->p1.x) { left_y = top_y; } else { left_y = _cairo_edge_compute_intersection_y_for_x (p1, p2, limits->p1.x); if (_cairo_edge_compute_intersection_x_for_y (p1, p2, left_y) < limits->p1.x) left_y++; } left_y = MIN (left_y, bot_y); if (top_y < left_y) { _add_edge (polygon, &limits->p1, &bot_left, top_y, left_y, dir); assert_last_edge_is_valid (polygon, limits); top_y = left_y; } if (pright <= limits->p2.x) { right_y = bot_y; } else { right_y = _cairo_edge_compute_intersection_y_for_x (p1, p2, limits->p2.x); if (_cairo_edge_compute_intersection_x_for_y (p1, p2, right_y) > limits->p2.x) right_y--; } right_y = MAX (right_y, top_y); if (bot_y > right_y) { _add_edge (polygon, &top_right, &limits->p2, right_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); bot_y = right_y; } } else { if (pright <= limits->p2.x) { right_y = top_y; } else { right_y = _cairo_edge_compute_intersection_y_for_x (p1, p2, limits->p2.x); if (_cairo_edge_compute_intersection_x_for_y (p1, p2, right_y) > limits->p2.x) right_y++; } right_y = MIN (right_y, bot_y); if (top_y < right_y) { _add_edge (polygon, &top_right, &limits->p2, top_y, right_y, dir); assert_last_edge_is_valid (polygon, limits); top_y = right_y; } if (pleft >= limits->p1.x) { left_y = bot_y; } else { left_y = _cairo_edge_compute_intersection_y_for_x (p1, p2, limits->p1.x); if (_cairo_edge_compute_intersection_x_for_y (p1, p2, left_y) < limits->p1.x) left_y--; } left_y = MAX (left_y, top_y); if (bot_y > left_y) { _add_edge (polygon, &limits->p1, &bot_left, left_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); bot_y = left_y; } } if (top_y != bot_y) { _add_edge (polygon, p1, p2, top_y, bot_y, dir); assert_last_edge_is_valid (polygon, limits); } } } } static void _cairo_polygon_add_edge (cairo_polygon_t *polygon, const cairo_point_t *p1, const cairo_point_t *p2, int dir) { /* drop horizontal edges */ if (p1->y == p2->y) return; if (p1->y > p2->y) { const cairo_point_t *t; t = p1, p1 = p2, p2 = t; dir = -dir; } if (polygon->num_limits) { if (p2->y <= polygon->limit.p1.y) return; if (p1->y >= polygon->limit.p2.y) return; _add_clipped_edge (polygon, p1, p2, p1->y, p2->y, dir); } else _add_edge (polygon, p1, p2, p1->y, p2->y, dir); } cairo_status_t _cairo_polygon_add_external_edge (void *polygon, const cairo_point_t *p1, const cairo_point_t *p2) { _cairo_polygon_add_edge (polygon, p1, p2, 1); return _cairo_polygon_status (polygon); } cairo_status_t _cairo_polygon_add_line (cairo_polygon_t *polygon, const cairo_line_t *line, int top, int bottom, int dir) { /* drop horizontal edges */ if (line->p1.y == line->p2.y) return CAIRO_STATUS_SUCCESS; if (bottom <= top) return CAIRO_STATUS_SUCCESS; if (polygon->num_limits) { if (line->p2.y <= polygon->limit.p1.y) return CAIRO_STATUS_SUCCESS; if (line->p1.y >= polygon->limit.p2.y) return CAIRO_STATUS_SUCCESS; _add_clipped_edge (polygon, &line->p1, &line->p2, top, bottom, dir); } else _add_edge (polygon, &line->p1, &line->p2, top, bottom, dir); return polygon->status; } cairo_status_t _cairo_polygon_add_contour (cairo_polygon_t *polygon, const cairo_contour_t *contour) { const struct _cairo_contour_chain *chain; const cairo_point_t *prev = NULL; int i; if (contour->chain.num_points <= 1) return CAIRO_INT_STATUS_SUCCESS; prev = &contour->chain.points[0]; for (chain = &contour->chain; chain; chain = chain->next) { for (i = 0; i < chain->num_points; i++) { _cairo_polygon_add_edge (polygon, prev, &chain->points[i], contour->direction); prev = &chain->points[i]; } } return polygon->status; } void _cairo_polygon_translate (cairo_polygon_t *polygon, int dx, int dy) { int n; dx = _cairo_fixed_from_int (dx); dy = _cairo_fixed_from_int (dy); polygon->extents.p1.x += dx; polygon->extents.p2.x += dx; polygon->extents.p1.y += dy; polygon->extents.p2.y += dy; for (n = 0; n < polygon->num_edges; n++) { cairo_edge_t *e = &polygon->edges[n]; e->top += dy; e->bottom += dy; e->line.p1.x += dx; e->line.p2.x += dx; e->line.p1.y += dy; e->line.p2.y += dy; } }
47a18d68d9ae924c0e797c1f90d657db7f297cfa
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/usb/tlg2300/vendorcmds.h
ba6f4ae3b2c29b2c15f18c2b1fbef1b4c88126d3
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
6,673
h
vendorcmds.h
#ifndef VENDOR_CMD_H_ #define VENDOR_CMD_H_ #define BULK_ALTERNATE_IFACE (2) #define ISO_3K_BULK_ALTERNATE_IFACE (1) #define REQ_SET_CMD (0X00) #define REQ_GET_CMD (0X80) enum tlg__analog_audio_standard { TLG_TUNE_ASTD_NONE = 0x00000000, TLG_TUNE_ASTD_A2 = 0x00000001, TLG_TUNE_ASTD_NICAM = 0x00000002, TLG_TUNE_ASTD_EIAJ = 0x00000004, TLG_TUNE_ASTD_BTSC = 0x00000008, TLG_TUNE_ASTD_FM_US = 0x00000010, TLG_TUNE_ASTD_FM_EUR = 0x00000020, TLG_TUNE_ASTD_ALL = 0x0000003f }; /* * identifiers for Custom Parameter messages. * @typedef cmd_custom_param_id_t */ enum cmd_custom_param_id { CUST_PARM_ID_NONE = 0x00, CUST_PARM_ID_BRIGHTNESS_CTRL = 0x01, CUST_PARM_ID_CONTRAST_CTRL = 0x02, CUST_PARM_ID_HUE_CTRL = 0x03, CUST_PARM_ID_SATURATION_CTRL = 0x04, CUST_PARM_ID_AUDIO_SNR_THRESHOLD = 0x10, CUST_PARM_ID_AUDIO_AGC_THRESHOLD = 0x11, CUST_PARM_ID_MAX }; struct tuner_custom_parameter_s { uint16_t param_id; /* Parameter identifier */ uint16_t param_value; /* Parameter value */ }; struct tuner_ber_rate_s { uint32_t ber_rate; /* BER sample rate in seconds */ }; struct tuner_atv_sig_stat_s { uint32_t sig_present; uint32_t sig_locked; uint32_t sig_lock_busy; uint32_t sig_strength; /* milliDb */ uint32_t tv_audio_chan; /* mono/stereo/sap*/ uint32_t mvision_stat; /* macrovision status */ }; struct tuner_dtv_sig_stat_s { uint32_t sig_present; /* Boolean*/ uint32_t sig_locked; /* Boolean */ uint32_t sig_lock_busy; /* Boolean (Can this time-out?) */ uint32_t sig_strength; /* milliDb*/ }; struct tuner_fm_sig_stat_s { uint32_t sig_present; /* Boolean*/ uint32_t sig_locked; /* Boolean */ uint32_t sig_lock_busy; /* Boolean */ uint32_t sig_stereo_mono;/* TBD*/ uint32_t sig_strength; /* milliDb*/ }; enum _tag_tlg_tune_srv_cmd { TLG_TUNE_PLAY_SVC_START = 1, TLG_TUNE_PLAY_SVC_STOP }; enum _tag_tune_atv_audio_mode_caps { TLG_TUNE_TVAUDIO_MODE_MONO = 0x00000001, TLG_TUNE_TVAUDIO_MODE_STEREO = 0x00000002, TLG_TUNE_TVAUDIO_MODE_LANG_A = 0x00000010,/* Primary language*/ TLG_TUNE_TVAUDIO_MODE_LANG_B = 0x00000020,/* 2nd avail language*/ TLG_TUNE_TVAUDIO_MODE_LANG_C = 0x00000040 }; enum _tag_tuner_atv_audio_rates { ATV_AUDIO_RATE_NONE = 0x00,/* Audio not supported*/ ATV_AUDIO_RATE_32K = 0x01,/* Audio rate = 32 KHz*/ ATV_AUDIO_RATE_48K = 0x02, /* Audio rate = 48 KHz*/ ATV_AUDIO_RATE_31_25K = 0x04 /* Audio rate = 31.25KHz */ }; enum _tag_tune_atv_vid_res_caps { TLG_TUNE_VID_RES_NONE = 0x00000000, TLG_TUNE_VID_RES_720 = 0x00000001, TLG_TUNE_VID_RES_704 = 0x00000002, TLG_TUNE_VID_RES_360 = 0x00000004 }; enum _tag_tuner_analog_video_format { TLG_TUNER_VID_FORMAT_YUV = 0x00000001, TLG_TUNER_VID_FORMAT_YCRCB = 0x00000002, TLG_TUNER_VID_FORMAT_RGB_565 = 0x00000004, }; enum tlg_ext_audio_support { TLG_EXT_AUDIO_NONE = 0x00,/* No external audio input supported */ TLG_EXT_AUDIO_LR = 0x01/* LR external audio inputs supported*/ }; enum { TLG_MODE_NONE = 0x00, /* No Mode specified*/ TLG_MODE_ANALOG_TV = 0x01, /* Analog Television mode*/ TLG_MODE_ANALOG_TV_UNCOMP = 0x01, /* Analog Television mode*/ TLG_MODE_ANALOG_TV_COMP = 0x02, /* Analog TV mode (compressed)*/ TLG_MODE_FM_RADIO = 0x04, /* FM Radio mode*/ TLG_MODE_DVB_T = 0x08, /* Digital TV (DVB-T)*/ }; enum tlg_signal_sources_t { TLG_SIG_SRC_NONE = 0x00,/* Signal source not specified */ TLG_SIG_SRC_ANTENNA = 0x01,/* Signal src is: Antenna */ TLG_SIG_SRC_CABLE = 0x02,/* Signal src is: Coax Cable*/ TLG_SIG_SRC_SVIDEO = 0x04,/* Signal src is: S_VIDEO */ TLG_SIG_SRC_COMPOSITE = 0x08 /* Signal src is: Composite Video */ }; enum tuner_analog_video_standard { TLG_TUNE_VSTD_NONE = 0x00000000, TLG_TUNE_VSTD_NTSC_M = 0x00000001, TLG_TUNE_VSTD_NTSC_M_J = 0x00000002,/* Japan */ TLG_TUNE_VSTD_PAL_B = 0x00000010, TLG_TUNE_VSTD_PAL_D = 0x00000020, TLG_TUNE_VSTD_PAL_G = 0x00000040, TLG_TUNE_VSTD_PAL_H = 0x00000080, TLG_TUNE_VSTD_PAL_I = 0x00000100, TLG_TUNE_VSTD_PAL_M = 0x00000200, TLG_TUNE_VSTD_PAL_N = 0x00000400, TLG_TUNE_VSTD_SECAM_B = 0x00001000, TLG_TUNE_VSTD_SECAM_D = 0x00002000, TLG_TUNE_VSTD_SECAM_G = 0x00004000, TLG_TUNE_VSTD_SECAM_H = 0x00008000, TLG_TUNE_VSTD_SECAM_K = 0x00010000, TLG_TUNE_VSTD_SECAM_K1 = 0x00020000, TLG_TUNE_VSTD_SECAM_L = 0x00040000, TLG_TUNE_VSTD_SECAM_L1 = 0x00080000, TLG_TUNE_VSTD_PAL_N_COMBO = 0x00100000 }; enum tlg_mode_caps { TLG_MODE_CAPS_NONE = 0x00, /* No Mode specified */ TLG_MODE_CAPS_ANALOG_TV_UNCOMP = 0x01, /* Analog TV mode */ TLG_MODE_CAPS_ANALOG_TV_COMP = 0x02, /* Analog TV (compressed)*/ TLG_MODE_CAPS_FM_RADIO = 0x04, /* FM Radio mode */ TLG_MODE_CAPS_DVB_T = 0x08, /* Digital TV (DVB-T) */ }; enum poseidon_vendor_cmds { LAST_CMD_STAT = 0x00, GET_CHIP_ID = 0x01, GET_FW_ID = 0x02, PRODUCT_CAPS = 0x03, TUNE_MODE_CAP_ATV = 0x10, TUNE_MODE_CAP_ATVCOMP = 0X10, TUNE_MODE_CAP_DVBT = 0x10, TUNE_MODE_CAP_FM = 0x10, TUNE_MODE_SELECT = 0x11, TUNE_FREQ_SELECT = 0x12, SGNL_SRC_SEL = 0x13, VIDEO_STD_SEL = 0x14, VIDEO_STREAM_FMT_SEL = 0x15, VIDEO_ROSOLU_AVAIL = 0x16, VIDEO_ROSOLU_SEL = 0x17, VIDEO_CONT_PROTECT = 0x20, VCR_TIMING_MODSEL = 0x21, EXT_AUDIO_CAP = 0x22, EXT_AUDIO_SEL = 0x23, TEST_PATTERN_SEL = 0x24, VBI_DATA_SEL = 0x25, AUDIO_SAMPLE_RATE_CAP = 0x28, AUDIO_SAMPLE_RATE_SEL = 0x29, TUNER_AUD_MODE = 0x2a, TUNER_AUD_MODE_AVAIL = 0x2b, TUNER_AUD_ANA_STD = 0x2c, TUNER_CUSTOM_PARAMETER = 0x2f, DVBT_TUNE_MODE_SEL = 0x30, DVBT_BANDW_CAP = 0x31, DVBT_BANDW_SEL = 0x32, DVBT_GUARD_INTERV_CAP = 0x33, DVBT_GUARD_INTERV_SEL = 0x34, DVBT_MODULATION_CAP = 0x35, DVBT_MODULATION_SEL = 0x36, DVBT_INNER_FEC_RATE_CAP = 0x37, DVBT_INNER_FEC_RATE_SEL = 0x38, DVBT_TRANS_MODE_CAP = 0x39, DVBT_TRANS_MODE_SEL = 0x3a, DVBT_SEARCH_RANG = 0x3c, TUNER_SETUP_ANALOG = 0x40, TUNER_SETUP_DIGITAL = 0x41, TUNER_SETUP_FM_RADIO = 0x42, TAKE_REQUEST = 0x43, /* Take effect of the command */ PLAY_SERVICE = 0x44, /* Play start or Play stop */ TUNER_STATUS = 0x45, TUNE_PROP_DVBT = 0x46, ERR_RATE_STATS = 0x47, TUNER_BER_RATE = 0x48, SCAN_CAPS = 0x50, SCAN_SETUP = 0x51, SCAN_SERVICE = 0x52, SCAN_STATS = 0x53, PID_SET = 0x58, PID_UNSET = 0x59, PID_LIST = 0x5a, IRD_CAP = 0x60, IRD_MODE_SEL = 0x61, IRD_SETUP = 0x62, PTM_MODE_CAP = 0x70, PTM_MODE_SEL = 0x71, PTM_SERVICE = 0x72, TUNER_REG_SCRIPT = 0x73, CMD_CHIP_RST = 0x74, }; enum tlg_bw { TLG_BW_5 = 5, TLG_BW_6 = 6, TLG_BW_7 = 7, TLG_BW_8 = 8, TLG_BW_12 = 12, TLG_BW_15 = 15 }; struct cmd_firmware_vers_s { uint8_t fw_rev_major; uint8_t fw_rev_minor; uint16_t fw_patch; }; #endif /* VENDOR_CMD_H_ */
0e581e4b3daaa6c12155438c6110e604eed6a393
18333497cc6db4a990a5f5e7b0dca14e9a517a73
/include/cmt/command_queue.h
d39587244b23c1e08337ec9bb24add53fa40f1f8
[ "MIT" ]
permissive
recp/cmt
6ecbca0a356ec044257285ab58e062ee6af55c7c
e2730ade077345b389213d6695d0d7a6c4e93264
refs/heads/master
2023-05-25T16:32:50.511305
2023-05-14T11:40:55
2023-05-14T11:40:55
137,069,724
138
12
MIT
2023-05-14T11:40:56
2018-06-12T12:39:37
C
UTF-8
C
false
false
483
h
command_queue.h
/* * Copyright (c), Recep Aslantas. * MIT License (MIT), http://opensource.org/licenses/MIT */ #ifndef cmt_commandqueue_h #define cmt_commandqueue_h #ifdef __cplusplus extern "C" { #endif #include "common.h" #include "types.h" #include "enums.h" MT_EXPORT MtCommandQueue* mtNewCommandQueue(MtDevice *device); MT_EXPORT MtCommandQueue* mtNewCommandQueueWithMaxCommandBufferCount(MtDevice *device, NsUInteger count); #ifdef __cplusplus } #endif #endif /* cmt_commandqueue_h */
eea9021e657a383426356bbf8e083ede90347c17
1577e1cf4e89584a125cffb855ca50a9654c6d55
/tcpdump/tcpdump/config.h
d6cc8b61cb8d3cb022a9393e6e9f2f08519df64c
[ "BSD-3-Clause" ]
permissive
apple-open-source/macos
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
2d2b15f13487673de33297e49f00ef94af743a9a
refs/heads/master
2023-08-01T11:03:26.870408
2023-03-27T00:00:00
2023-03-27T00:00:00
180,595,052
124
24
null
2022-12-27T14:54:09
2019-04-10T14:06:23
null
UTF-8
C
false
false
10,628
h
config.h
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ #ifdef __APPLE__ #include <TargetConditionals.h> #endif /* __APPLE__ */ /* Define to 1 if arpa/inet.h declares `ether_ntohost' */ /* #undef ARPA_INET_H_DECLARES_ETHER_NTOHOST */ /* define if you want to build the possibly-buggy SMB printer */ /* #undef ENABLE_SMB */ /* Define to 1 if you have the `bpf_dump' function. */ #define HAVE_BPF_DUMP 1 /* capsicum support available */ /* #undef HAVE_CAPSICUM */ /* Define to 1 if you have the `cap_enter' function. */ /* #undef HAVE_CAP_ENTER */ /* Define to 1 if you have the `cap_ioctls_limit' function. */ /* #undef HAVE_CAP_IOCTLS_LIMIT */ /* Define to 1 if you have the <cap-ng.h> header file. */ /* #undef HAVE_CAP_NG_H */ /* Define to 1 if you have the `cap_rights_limit' function. */ /* #undef HAVE_CAP_RIGHTS_LIMIT */ /* Define to 1 if you have the declaration of `ether_ntohost', and to 0 if you don't. */ #define HAVE_DECL_ETHER_NTOHOST 1 /* Define to 1 if you have the `ether_ntohost' function. */ #define HAVE_ETHER_NTOHOST 1 /* Define to 1 if you have the `EVP_CIPHER_CTX_new' function. */ /* #undef HAVE_EVP_CIPHER_CTX_NEW */ #define HAVE_EVP_CIPHER_CTX_NEW 1 /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have the `fork' function. */ #define HAVE_FORK 1 /* Define to 1 if you have the `getopt_long' function. */ #define HAVE_GETOPT_LONG 1 /* define if you have getrpcbynumber() */ #define HAVE_GETRPCBYNUMBER 1 /* Define to 1 if you have the `getservent' function. */ #define HAVE_GETSERVENT 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `cap-ng' library (-lcap-ng). */ /* #undef HAVE_LIBCAP_NG */ /* Define to 1 if you have the `crypto' library (-lcrypto). */ #if TARGET_OS_OSX #define HAVE_LIBCRYPTO 1 #endif /* Define to 1 if you have the `rpc' library (-lrpc). */ /* #undef HAVE_LIBRPC */ /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <net/if.h> header file. */ #define HAVE_NET_IF_H 1 /* Define to 1 if you have the <net/if_pflog.h> header file. */ #define HAVE_NET_IF_PFLOG_H 1 /* Define to 1 if you have the <net/pfvar.h> header file. */ #define HAVE_NET_PFVAR_H 1 /* Define to 1 if you have the `openat' function. */ #define HAVE_OPENAT 1 /* Define to 1 if you have the <openssl/evp.h> header file. */ /* #undef HAVE_OPENSSL_EVP_H */ /* define if the OS provides AF_INET6 and struct in6_addr */ #define HAVE_OS_IPV6_SUPPORT 1 /* if there's an os_proto.h for this platform, to use additional prototypes */ /* #undef HAVE_OS_PROTO_H */ /* Define to 1 if you have the <pcap/bluetooth.h> header file. */ #define HAVE_PCAP_BLUETOOTH_H 1 /* Define to 1 if you have the `pcap_breakloop' function. */ #define HAVE_PCAP_BREAKLOOP 1 /* Define to 1 if you have the `pcap_create' function. */ #define HAVE_PCAP_CREATE 1 /* define if libpcap has pcap_datalink_name_to_val() */ #define HAVE_PCAP_DATALINK_NAME_TO_VAL 1 /* define if libpcap has pcap_datalink_val_to_description() */ #define HAVE_PCAP_DATALINK_VAL_TO_DESCRIPTION 1 /* define if libpcap has pcap_debug */ /* #undef HAVE_PCAP_DEBUG */ /* Define to 1 if you have the `pcap_dump_flush' function. */ #define HAVE_PCAP_DUMP_FLUSH 1 /* Define to 1 if you have the `pcap_dump_ftell' function. */ #define HAVE_PCAP_DUMP_FTELL 1 /* Define to 1 if you have the `pcap_dump_ftell64' function. */ #define HAVE_PCAP_DUMP_FTELL64 1 /* Define to 1 if you have the `pcap_findalldevs' function. */ #define HAVE_PCAP_FINDALLDEVS 1 /* Define to 1 if you have the `pcap_findalldevs_ex' function. */ /* #undef HAVE_PCAP_FINDALLDEVS_EX */ /* Define to 1 if you have the `pcap_free_datalinks' function. */ #define HAVE_PCAP_FREE_DATALINKS 1 /* Define to 1 if the system has the type `pcap_if_t'. */ #define HAVE_PCAP_IF_T 1 /* Define to 1 if you have the `pcap_lib_version' function. */ #define HAVE_PCAP_LIB_VERSION 1 /* define if libpcap has pcap_list_datalinks() */ #define HAVE_PCAP_LIST_DATALINKS 1 /* Define to 1 if you have the `pcap_open' function. */ /* #undef HAVE_PCAP_OPEN */ /* Define to 1 if you have the <pcap/pcap-inttypes.h> header file. */ #define HAVE_PCAP_PCAP_INTTYPES_H 1 /* Define to 1 if you have the `pcap_setdirection' function. */ #define HAVE_PCAP_SETDIRECTION 1 /* Define to 1 if you have the `pcap_set_datalink' function. */ #define HAVE_PCAP_SET_DATALINK 1 /* Define to 1 if you have the `pcap_set_immediate_mode' function. */ #define HAVE_PCAP_SET_IMMEDIATE_MODE 1 /* Define to 1 if you have the `pcap_set_optimizer_debug' function. */ /* #undef HAVE_PCAP_SET_OPTIMIZER_DEBUG */ /* Define to 1 if you have the `pcap_set_parser_debug' function. */ /* #undef HAVE_PCAP_SET_PARSER_DEBUG */ /* Define to 1 if you have the `pcap_set_tstamp_precision' function. */ #define HAVE_PCAP_SET_TSTAMP_PRECISION 1 /* Define to 1 if you have the `pcap_set_tstamp_type' function. */ #define HAVE_PCAP_SET_TSTAMP_TYPE 1 /* define if libpcap has pcap_version */ /* #undef HAVE_PCAP_VERSION */ /* Define to 1 if you have the `pfopen' function. */ /* #undef HAVE_PFOPEN */ /* Define to 1 if you have the <rpc/rpcent.h> header file. */ /* #undef HAVE_RPC_RPCENT_H */ /* Define to 1 if you have the <rpc/rpc.h> header file. */ #define HAVE_RPC_RPC_H 1 /* Define to 1 if you have the `setlinebuf' function. */ #define HAVE_SETLINEBUF 1 /* Define to 1 if you have the `sigaction' function. */ #define HAVE_SIGACTION 1 /* Define to 1 if you have the `sigset' function. */ /* #undef HAVE_SIGSET */ /* Define to 1 if you have the `snprintf' function. */ #define HAVE_SNPRINTF 1 /* if struct sockaddr has the sa_len member */ #define HAVE_SOCKADDR_SA_LEN 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the `strdup' function. */ #define HAVE_STRDUP 1 /* Define to 1 if you have the `strftime' function. */ #define HAVE_STRFTIME 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the `strlcat' function. */ #define HAVE_STRLCAT 1 /* Define to 1 if you have the `strlcpy' function. */ #define HAVE_STRLCPY 1 /* Define to 1 if you have the `strsep' function. */ #define HAVE_STRSEP 1 /* Define to 1 if the system has the type `struct ether_addr'. */ /* #undef HAVE_STRUCT_ETHER_ADDR */ /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if the system has the type `uintptr_t'. */ #define HAVE_UINTPTR_T 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `vfork' function. */ #define HAVE_VFORK 1 /* Define to 1 if you have the `vfprintf' function. */ #define HAVE_VFPRINTF 1 /* Define to 1 if you have the `vsnprintf' function. */ #define HAVE_VSNPRINTF 1 /* define if libpcap has yydebug */ /* #undef HAVE_YYDEBUG */ /* define if your compiler has __attribute__ */ #define HAVE___ATTRIBUTE__ 1 /* if unaligned access fails */ /* #undef LBL_ALIGN */ /* Define to 1 if netinet/ether.h declares `ether_ntohost' */ /* #undef NETINET_ETHER_H_DECLARES_ETHER_NTOHOST */ /* Define to 1 if netinet/if_ether.h declares `ether_ntohost' */ /* #undef NETINET_IF_ETHER_H_DECLARES_ETHER_NTOHOST */ /* Define to 1 if net/ethernet.h declares `ether_ntohost' */ #define NET_ETHERNET_H_DECLARES_ETHER_NTOHOST 1 /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "tcpdump" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "tcpdump 4.99.1" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "tcpdump" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "4.99.1" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to 1 if sys/ethernet.h declares `ether_ntohost' */ /* #undef SYS_ETHERNET_H_DECLARES_ETHER_NTOHOST */ /* define if you have ether_ntohost() and it works */ #define USE_ETHER_NTOHOST 1 /* Define if you enable support for libsmi */ /* #undef USE_LIBSMI */ /* define if should chroot when dropping privileges */ /* #undef WITH_CHROOT */ /* define if should drop privileges by default */ /* #undef WITH_USER */ /* define on AIX to get certain functions */ /* #undef _SUN */ /* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT32_T */ /* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT64_T */ /* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT8_T */ /* define if your compiler allows __attribute__((format)) without a warning */ #define __ATTRIBUTE___FORMAT_OK 1 /* define if your compiler allows __attribute__((format)) to be applied to function pointers */ #define __ATTRIBUTE___FORMAT_OK_FOR_FUNCTION_POINTERS 1 /* define if your compiler allows __attribute__((noreturn)) to be applied to function pointers */ #define __ATTRIBUTE___NORETURN_OK_FOR_FUNCTION_POINTERS 1 /* to handle Ultrix compilers that don't support const in prototypes */ /* #undef const */ /* Define as token for inline if inlining supported */ #define inline inline /* Define to `uint16_t' if u_int16_t not defined. */ /* #undef u_int16_t */ /* Define to `uint32_t' if u_int32_t not defined. */ /* #undef u_int32_t */ /* Define to `uint64_t' if u_int64_t not defined. */ /* #undef u_int64_t */ /* Define to `uint8_t' if u_int8_t not defined. */ /* #undef u_int8_t */ /* Define to the type of an unsigned integer type wide enough to hold a pointer, if such a type exists, and if the system does not define it. */ /* #undef uintptr_t */
ce499ed3fb1b89c705d7ab3b78a1cb88d95ef514
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_stereo/AKWF_stereo_0093.h
99ece5f287d408c0dadd3ae0d2721af9b8db9a87
[ "CC0-1.0" ]
permissive
KristofferKarlAxelEkstrand/AKWF-FREE
b2defa1a2d389d309be6dd2e9f968923daf80d1b
cf8171df36e9fec25416b5f568b72a6e2cb69194
refs/heads/master
2023-07-23T18:22:36.939705
2023-07-10T17:14:40
2023-07-10T17:14:40
145,817,187
359
59
CC0-1.0
2023-07-10T17:14:41
2018-08-23T07:26:56
null
UTF-8
C
false
false
6,478
h
AKWF_stereo_0093.h
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library * * Adventure Kid Waveforms(AKWF) Open waveforms library * https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/ * * This code is in the public domain, CC0 1.0 Universal (CC0 1.0) * https://creativecommons.org/publicdomain/zero/1.0/ * * Converted by Brad Roy, https://github.com/prosper00 */ /* AKWF_stereo_0093 256 samples +-----------------------------------------------------------------------------------------------------------------+ | ** ***** ** ***** | | * ***** **** ** ***** **** | | * *** ** ** ** *** ** ** | |** ** ** ** ** *** ** * | |* **** * ** ** **** * ** | | ** ***** * ** ***** | | ** ** * ** ** ** * *| | *** ** ** ** ** **| | * * * * | | ** * ** ** | | * ** * ** | | ** ** ** ** | | * ** * ** | | ** ** ** ** | | * ** ** ** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_stereo_0093 [] = { 32958, 35668, 34740, 39211, 36730, 40874, 38573, 43194, 40399, 44917, 42101, 46907, 43766, 48500, 45293, 50209, 46735, 51610, 47972, 53017, 49046, 54158, 49885, 55222, 50518, 56041, 50905, 56706, 51086, 57133, 50986, 57360, 50729, 57363, 50333, 57129, 49845, 56703, 49305, 56046, 48770, 55240, 48271, 54235, 47821, 53135, 47435, 51885, 47089, 50599, 46760, 49226, 46469, 47867, 46204, 46470, 45938, 45135, 45665, 43811, 45371, 42583, 45058, 41412, 44699, 40361, 44306, 39400, 43850, 38571, 43343, 37850, 42772, 37254, 42147, 36769, 41451, 36392, 40714, 36114, 39927, 35922, 39124, 35809, 38326, 35769, 37396, 35830, 36510, 35962, 35795, 36165, 35215, 36433, 34867, 36772, 34780, 37165, 35011, 37618, 35534, 38113, 36345, 38652, 37358, 39215, 38443, 39814, 39628, 40415, 40864, 41012, 42048, 41590, 43129, 42140, 44044, 42648, 44764, 43116, 45236, 43529, 45444, 43886, 45360, 44176, 45006, 44391, 44398, 44525, 43561, 44560, 42535, 44496, 41354, 44314, 40075, 44014, 38723, 43577, 37370, 43013, 35712, 42175, 33897, 41098, 32217, 39870, 30586, 38433, 29137, 36815, 27946, 35057, 27137, 33225, 26730, 31352, 26728, 29468, 27114, 27669, 27591, 26046, 28295, 24599, 29275, 23355, 30328, 22342, 31411, 21553, 32402, 20968, 33226, 20548, 33774, 20243, 33973, 20002, 33745, 19761, 33073, 19466, 31942, 19070, 30380, 18531, 28399, 17816, 26060, 16910, 23416, 15807, 20548, 14518, 17543, 13061, 14488, 11475, 11484, 9801, 8626, 8090, 6029, 6403, 3787, 4805, 2003, 3365, 747, 2148, 97, 1227, 49, 649, 610, 471, 1204, 513, 1928, 838, 3059, 1569, 4298, 2575, 5655, 3845, 7072, 5345, 8559, 7066, 10081, 8959, 11615, 10952, 13192, 13074, 14849, 15308, 16589, 17612, 18434, 19974, 20372, 22378, 22393, 24812, 24456, 27251, 26545, 29683, 28643, 32080, 30728, 34427, 32776, 36712, 34773, 38920, 36713, 41042, 38586, 43074, 40386, 45007, 42112, 46836, 43755, 48557, 45303, 50163, 46726, 51646, 47981, 52988, 49040, 54180, 49891, 55207, 50515, 56051, 50910, 56700, 51081, 57136, 50989, 57361, 50726, 57360, 50336, 57134, 49843, 56695, 49306, 56054, 48770, 55232, 48270, 54245, 47819, 53125, 47437, 51896, 47091, 50590, 46764, 49237, 46470, 47859, 46205, 46480, 45939, 45126, 45665, 43819, 45373, 42577, 45057, 41418, 44703, 40357, 44306, 39405, 43853, 38570, 43345, 37852, 42775, 37256, 42144, 36771, 41451, 36393, 40711, 36114, 39927, 35923, 39123, 35809, 38327, 35771, 37398, 35830, 36513, 35966, 35795, 36163, 35217, 36434, 34867, 36770, 34781, 37168, 35012, 37618, 35536, 38115, 36347, 38651, 37359, 39216, 38443, 39814, 39629, 40418, 40864, 41012, 42048, 41591, 43129, 42140, 44044, 42649, 44765, 43117, 45237, 43531, 45444, 43886, 45361, 44178, 45006, 44392, 44398, 44526, 43561, 44561, 42534, 44496, 41358, 44314, 40075, 44015, 38726, 43579, 37374, 43016, 35713, 42176, 33896, 41099, 32217, 39872, 30585, 38432, 29134, 36816, 27948, 35058, 27139, 33225, 26730, 31352, 26731, 29470, 27114, 27668, 27591, 26048, 28298, 24599, 29277, 23359, 30330, 22339, 31412, 21557, 32404, 20965, 33227, 20553, 33774, 20242, 33974, 20007, 33745, 19758, 33073, 19472, 31945, 19069, 30379, 18535, 28402, 17816, 26061, 16912, 23418, 15807, 20547, 14519, 17543, 13064, 14488, 11474, 11486, 9804, 8629, 8086, 6030, 6410, 3790, 4798, 2007, 3377, 747, 2137, 101, 1240, 52, 636, 610, 487, 1205, 497, 1929, 858, 3064, 1552, 4295, 2597, 5660, 3829, 7069, 5363, 8565, 7052, 10074, 8976, 11622, 10939, 13183, 13085, 14857, 15302, 16580, 17612, 18443, 19982, 20362, 22362, 22406, 24842, 24445, 27204, 26562, 29764, 28625, 31942, 30760, 34719, };
376214d7d2692256e9e525cbab3d03a66d5cd928
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/python/Python/xtermmodule.c
e8fa34fff1b11312dfd89fa6bc6a2c47575af5c2
[ "ISC", "Python-2.0", "GPL-1.0-or-later", "LicenseRef-scancode-python-cwi", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-copyleft" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
4,180
c
xtermmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("xterm"); PYTHON_PROVIDE("xterm.rgb2xterm256"); PyDoc_STRVAR(xterm_doc, "Xterm Module\n\ \n\ This module exposes low-level utilities for xterm ansi encoding."); PyDoc_STRVAR(rgb2xterm256_doc, "rgb2xterm256($module, r, g, b)\n\ --\n\n\ Quantizes RGB to color to XTERM256 ANSI terminal code.\n\ \n\ This helps you print colors in the terminal faster. For example:\n\ \n\ print(\"\\x1b[38;5;%dmhello\\x1b[0m\" % (xterm.rgb2xterm256(255,0,0)))\n\ \n\ Will print red text to the terminal."); static PyObject * xterm_rgb2xterm256(PyObject *self, PyObject *args) { unsigned char r, g, b; int res, cerr, gerr, ir, ig, ib, gray, grai, cr, cg, cb, gv; const unsigned char kXtermCube[6] = {0, 0137, 0207, 0257, 0327, 0377}; if (!PyArg_ParseTuple(args, "BBB:rgb2xterm256", &r, &g, &b)) return 0; gray = round(r * .299 + g * .587 + b * .114); grai = gray > 238 ? 23 : (gray - 3) / 10; ir = r < 48 ? 0 : r < 115 ? 1 : (r - 35) / 40; ig = g < 48 ? 0 : g < 115 ? 1 : (g - 35) / 40; ib = b < 48 ? 0 : b < 115 ? 1 : (b - 35) / 40; cr = kXtermCube[ir]; cg = kXtermCube[ig]; cb = kXtermCube[ib]; gv = 8 + 10 * grai; cerr = (cr-r)*(cr-r) + (cg-g)*(cg-g) + (cb-b)*(cb-b); gerr = (gv-r)*(gv-r) + (gv-g)*(gv-g) + (gv-b)*(gv-b); if (cerr <= gerr) { res = 16 + 36 * ir + 6 * ig + ib; } else { res = 232 + grai; } return PyLong_FromUnsignedLong(res); } static PyMethodDef xterm_methods[] = { {"rgb2xterm256", xterm_rgb2xterm256, METH_VARARGS, rgb2xterm256_doc}, {0}, }; static struct PyModuleDef xtermmodule = { PyModuleDef_HEAD_INIT, "xterm", xterm_doc, -1, xterm_methods, }; PyMODINIT_FUNC PyInit_xterm(void) { return PyModule_Create(&xtermmodule); } #ifdef __aarch64__ _Section(".rodata.pytab.1 //") #else _Section(".rodata.pytab.1") #endif const struct _inittab _PyImport_Inittab_xterm = { "xterm", PyInit_xterm, };
3caccbbfa2e86c172ecb86541753d055cdeb28f4
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/any-windows-any/lmshare.h
44dd80be13a422e09a25a21799ab7a5a8675d593
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
7,481
h
lmshare.h
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef _LMSHARE_ #define _LMSHARE_ #ifdef __cplusplus extern "C" { #endif #include <lmcons.h> NET_API_STATUS WINAPI NetShareAdd(LMSTR servername,DWORD level,LPBYTE buf,LPDWORD parm_err); NET_API_STATUS WINAPI NetShareEnum(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); NET_API_STATUS WINAPI NetShareEnumSticky(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); NET_API_STATUS WINAPI NetShareGetInfo(LMSTR servername,LMSTR netname,DWORD level,LPBYTE *bufptr); NET_API_STATUS WINAPI NetShareSetInfo(LMSTR servername,LMSTR netname,DWORD level,LPBYTE buf,LPDWORD parm_err); NET_API_STATUS WINAPI NetShareDel(LMSTR servername,LMSTR netname,DWORD reserved); NET_API_STATUS WINAPI NetShareDelSticky(LMSTR servername,LMSTR netname,DWORD reserved); NET_API_STATUS WINAPI NetShareCheck(LMSTR servername,LMSTR device,LPDWORD type); typedef struct _SHARE_INFO_0 { LMSTR shi0_netname; } SHARE_INFO_0,*PSHARE_INFO_0,*LPSHARE_INFO_0; typedef struct _SHARE_INFO_1 { LMSTR shi1_netname; DWORD shi1_type; LMSTR shi1_remark; } SHARE_INFO_1,*PSHARE_INFO_1,*LPSHARE_INFO_1; typedef struct _SHARE_INFO_2 { LMSTR shi2_netname; DWORD shi2_type; LMSTR shi2_remark; DWORD shi2_permissions; DWORD shi2_max_uses; DWORD shi2_current_uses; LMSTR shi2_path; LMSTR shi2_passwd; } SHARE_INFO_2,*PSHARE_INFO_2,*LPSHARE_INFO_2; typedef struct _SHARE_INFO_501 { LMSTR shi501_netname; DWORD shi501_type; LMSTR shi501_remark; DWORD shi501_flags; } SHARE_INFO_501,*PSHARE_INFO_501,*LPSHARE_INFO_501; typedef struct _SHARE_INFO_502 { LMSTR shi502_netname; DWORD shi502_type; LMSTR shi502_remark; DWORD shi502_permissions; DWORD shi502_max_uses; DWORD shi502_current_uses; LMSTR shi502_path; LMSTR shi502_passwd; DWORD shi502_reserved; PSECURITY_DESCRIPTOR shi502_security_descriptor; } SHARE_INFO_502,*PSHARE_INFO_502,*LPSHARE_INFO_502; typedef struct _SHARE_INFO_1004 { LMSTR shi1004_remark; } SHARE_INFO_1004,*PSHARE_INFO_1004,*LPSHARE_INFO_1004; typedef struct _SHARE_INFO_1005 { DWORD shi1005_flags; } SHARE_INFO_1005,*PSHARE_INFO_1005,*LPSHARE_INFO_1005; typedef struct _SHARE_INFO_1006 { DWORD shi1006_max_uses; } SHARE_INFO_1006,*PSHARE_INFO_1006,*LPSHARE_INFO_1006; typedef struct _SHARE_INFO_1501 { DWORD shi1501_reserved; PSECURITY_DESCRIPTOR shi1501_security_descriptor; } SHARE_INFO_1501,*PSHARE_INFO_1501,*LPSHARE_INFO_1501; #define SHARE_NETNAME_PARMNUM 1 #define SHARE_TYPE_PARMNUM 3 #define SHARE_REMARK_PARMNUM 4 #define SHARE_PERMISSIONS_PARMNUM 5 #define SHARE_MAX_USES_PARMNUM 6 #define SHARE_CURRENT_USES_PARMNUM 7 #define SHARE_PATH_PARMNUM 8 #define SHARE_PASSWD_PARMNUM 9 #define SHARE_FILE_SD_PARMNUM 501 #define SHARE_REMARK_INFOLEVEL (PARMNUM_BASE_INFOLEVEL + SHARE_REMARK_PARMNUM) #define SHARE_MAX_USES_INFOLEVEL (PARMNUM_BASE_INFOLEVEL + SHARE_MAX_USES_PARMNUM) #define SHARE_FILE_SD_INFOLEVEL (PARMNUM_BASE_INFOLEVEL + SHARE_FILE_SD_PARMNUM) #define SHI1_NUM_ELEMENTS 4 #define SHI2_NUM_ELEMENTS 10 #define STYPE_DISKTREE 0 #define STYPE_PRINTQ 1 #define STYPE_DEVICE 2 #define STYPE_IPC 3 #define STYPE_TEMPORARY 0x40000000 #define STYPE_SPECIAL 0x80000000 #define SHI_USES_UNLIMITED (DWORD)-1 #define SHI1005_FLAGS_DFS 0x01 #define SHI1005_FLAGS_DFS_ROOT 0x02 #define CSC_MASK 0x30 #define CSC_CACHE_MANUAL_REINT 0x00 #define CSC_CACHE_AUTO_REINT 0x10 #define CSC_CACHE_VDO 0x20 #define CSC_CACHE_NONE 0x30 #define SHI1005_FLAGS_RESTRICT_EXCLUSIVE_OPENS 0x0100 #define SHI1005_FLAGS_FORCE_SHARED_DELETE 0x0200 #define SHI1005_FLAGS_ALLOW_NAMESPACE_CACHING 0x0400 #define SHI1005_FLAGS_ACCESS_BASED_DIRECTORY_ENUM 0x0800 #define SHI1005_VALID_FLAGS_SET (CSC_MASK| SHI1005_FLAGS_RESTRICT_EXCLUSIVE_OPENS| SHI1005_FLAGS_FORCE_SHARED_DELETE| SHI1005_FLAGS_ALLOW_NAMESPACE_CACHING| SHI1005_FLAGS_ACCESS_BASED_DIRECTORY_ENUM) #endif #ifndef _LMSESSION_ #define _LMSESSION_ NET_API_STATUS WINAPI NetSessionEnum(LMSTR servername,LMSTR UncClientName,LMSTR username,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); NET_API_STATUS WINAPI NetSessionDel(LMSTR servername,LMSTR UncClientName,LMSTR username); NET_API_STATUS WINAPI NetSessionGetInfo(LMSTR servername,LMSTR UncClientName,LMSTR username,DWORD level,LPBYTE *bufptr); typedef struct _SESSION_INFO_0 { LMSTR sesi0_cname; } SESSION_INFO_0,*PSESSION_INFO_0,*LPSESSION_INFO_0; typedef struct _SESSION_INFO_1 { LMSTR sesi1_cname; LMSTR sesi1_username; DWORD sesi1_num_opens; DWORD sesi1_time; DWORD sesi1_idle_time; DWORD sesi1_user_flags; } SESSION_INFO_1,*PSESSION_INFO_1,*LPSESSION_INFO_1; typedef struct _SESSION_INFO_2 { LMSTR sesi2_cname; LMSTR sesi2_username; DWORD sesi2_num_opens; DWORD sesi2_time; DWORD sesi2_idle_time; DWORD sesi2_user_flags; LMSTR sesi2_cltype_name; } SESSION_INFO_2,*PSESSION_INFO_2,*LPSESSION_INFO_2; typedef struct _SESSION_INFO_10 { LMSTR sesi10_cname; LMSTR sesi10_username; DWORD sesi10_time; DWORD sesi10_idle_time; } SESSION_INFO_10,*PSESSION_INFO_10,*LPSESSION_INFO_10; typedef struct _SESSION_INFO_502 { LMSTR sesi502_cname; LMSTR sesi502_username; DWORD sesi502_num_opens; DWORD sesi502_time; DWORD sesi502_idle_time; DWORD sesi502_user_flags; LMSTR sesi502_cltype_name; LMSTR sesi502_transport; } SESSION_INFO_502,*PSESSION_INFO_502,*LPSESSION_INFO_502; #define SESS_GUEST 0x00000001 #define SESS_NOENCRYPTION 0x00000002 #define SESI1_NUM_ELEMENTS 8 #define SESI2_NUM_ELEMENTS 9 #endif #ifndef _LMCONNECTION_ #define _LMCONNECTION_ NET_API_STATUS WINAPI NetConnectionEnum(LMSTR servername,LMSTR qualifier,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); typedef struct _CONNECTION_INFO_0 { DWORD coni0_id; } CONNECTION_INFO_0,*PCONNECTION_INFO_0,*LPCONNECTION_INFO_0; typedef struct _CONNECTION_INFO_1 { DWORD coni1_id; DWORD coni1_type; DWORD coni1_num_opens; DWORD coni1_num_users; DWORD coni1_time; LMSTR coni1_username; LMSTR coni1_netname; } CONNECTION_INFO_1,*PCONNECTION_INFO_1,*LPCONNECTION_INFO_1; #endif #ifndef _LMFILE_ #define _LMFILE_ NET_API_STATUS WINAPI NetFileClose(LMSTR servername,DWORD fileid); NET_API_STATUS WINAPI NetFileEnum(LMSTR servername,LMSTR basepath,LMSTR username,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resume_handle); NET_API_STATUS WINAPI NetFileGetInfo(LMSTR servername,DWORD fileid,DWORD level,LPBYTE *bufptr); typedef struct _FILE_INFO_2 { DWORD fi2_id; } FILE_INFO_2,*PFILE_INFO_2,*LPFILE_INFO_2; typedef struct _FILE_INFO_3 { DWORD fi3_id; DWORD fi3_permissions; DWORD fi3_num_locks; LMSTR fi3_pathname; LMSTR fi3_username; } FILE_INFO_3,*PFILE_INFO_3,*LPFILE_INFO_3; #define PERM_FILE_READ 0x1 #define PERM_FILE_WRITE 0x2 #define PERM_FILE_CREATE 0x4 #ifdef __cplusplus } #endif #endif
b03a848867c77efcc7d740847bbc2d896da29aa4
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/xfsprogs/db/symlink.h
43431adfe0866986af883f44ca3a1d81da2343ab
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
343
h
symlink.h
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2013 Red Hat, Inc. * All Rights Reserved. */ #ifndef __XFS_DB_SYMLINK_H #define __XFS_DB_SYMLINK_H extern const struct field symlink_crc_hfld[]; extern const struct field symlink_crc_flds[]; extern int symlink_size(void *obj, int startoff, int idx); #endif /* __XFS_DB_SYMLINK_H */
0948c4b2e8e2766451cdcc448e9c4151350f4e9f
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/acpi/acpica/nswalk.c
e70911a9e441d3ded8c21cfa4c17a45c00ed936e
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
11,302
c
nswalk.c
/****************************************************************************** * * Module Name: nswalk - Functions for walking the ACPI namespace * *****************************************************************************/ /* * Copyright (C) 2000 - 2013, Intel Corp. * 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, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. */ #include <acpi/acpi.h> #include "accommon.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME("nswalk") /******************************************************************************* * * FUNCTION: acpi_ns_get_next_node * * PARAMETERS: parent_node - Parent node whose children we are * getting * child_node - Previous child that was found. * The NEXT child will be returned * * RETURN: struct acpi_namespace_node - Pointer to the NEXT child or NULL if * none is found. * * DESCRIPTION: Return the next peer node within the namespace. If Handle * is valid, Scope is ignored. Otherwise, the first node * within Scope is returned. * ******************************************************************************/ struct acpi_namespace_node *acpi_ns_get_next_node(struct acpi_namespace_node *parent_node, struct acpi_namespace_node *child_node) { ACPI_FUNCTION_ENTRY(); if (!child_node) { /* It's really the parent's _scope_ that we want */ return (parent_node->child); } /* Otherwise just return the next peer */ return (child_node->peer); } /******************************************************************************* * * FUNCTION: acpi_ns_get_next_node_typed * * PARAMETERS: type - Type of node to be searched for * parent_node - Parent node whose children we are * getting * child_node - Previous child that was found. * The NEXT child will be returned * * RETURN: struct acpi_namespace_node - Pointer to the NEXT child or NULL if * none is found. * * DESCRIPTION: Return the next peer node within the namespace. If Handle * is valid, Scope is ignored. Otherwise, the first node * within Scope is returned. * ******************************************************************************/ struct acpi_namespace_node *acpi_ns_get_next_node_typed(acpi_object_type type, struct acpi_namespace_node *parent_node, struct acpi_namespace_node *child_node) { struct acpi_namespace_node *next_node = NULL; ACPI_FUNCTION_ENTRY(); next_node = acpi_ns_get_next_node(parent_node, child_node); /* If any type is OK, we are done */ if (type == ACPI_TYPE_ANY) { /* next_node is NULL if we are at the end-of-list */ return (next_node); } /* Must search for the node -- but within this scope only */ while (next_node) { /* If type matches, we are done */ if (next_node->type == type) { return (next_node); } /* Otherwise, move on to the next peer node */ next_node = next_node->peer; } /* Not found */ return (NULL); } /******************************************************************************* * * FUNCTION: acpi_ns_walk_namespace * * PARAMETERS: type - acpi_object_type to search for * start_node - Handle in namespace where search begins * max_depth - Depth to which search is to reach * flags - Whether to unlock the NS before invoking * the callback routine * pre_order_visit - Called during tree pre-order visit * when an object of "Type" is found * post_order_visit - Called during tree post-order visit * when an object of "Type" is found * context - Passed to user function(s) above * return_value - from the user_function if terminated * early. Otherwise, returns NULL. * RETURNS: Status * * DESCRIPTION: Performs a modified depth-first walk of the namespace tree, * starting (and ending) at the node specified by start_handle. * The callback function is called whenever a node that matches * the type parameter is found. If the callback function returns * a non-zero value, the search is terminated immediately and * this value is returned to the caller. * * The point of this procedure is to provide a generic namespace * walk routine that can be called from multiple places to * provide multiple services; the callback function(s) can be * tailored to each task, whether it is a print function, * a compare function, etc. * ******************************************************************************/ acpi_status acpi_ns_walk_namespace(acpi_object_type type, acpi_handle start_node, u32 max_depth, u32 flags, acpi_walk_callback pre_order_visit, acpi_walk_callback post_order_visit, void *context, void **return_value) { acpi_status status; acpi_status mutex_status; struct acpi_namespace_node *child_node; struct acpi_namespace_node *parent_node; acpi_object_type child_type; u32 level; u8 node_previously_visited = FALSE; ACPI_FUNCTION_TRACE(ns_walk_namespace); /* Special case for the namespace Root Node */ if (start_node == ACPI_ROOT_OBJECT) { start_node = acpi_gbl_root_node; } /* Null child means "get first node" */ parent_node = start_node; child_node = acpi_ns_get_next_node(parent_node, NULL); child_type = ACPI_TYPE_ANY; level = 1; /* * Traverse the tree of nodes until we bubble back up to where we * started. When Level is zero, the loop is done because we have * bubbled up to (and passed) the original parent handle (start_entry) */ while (level > 0 && child_node) { status = AE_OK; /* Found next child, get the type if we are not searching for ANY */ if (type != ACPI_TYPE_ANY) { child_type = child_node->type; } /* * Ignore all temporary namespace nodes (created during control * method execution) unless told otherwise. These temporary nodes * can cause a race condition because they can be deleted during * the execution of the user function (if the namespace is * unlocked before invocation of the user function.) Only the * debugger namespace dump will examine the temporary nodes. */ if ((child_node->flags & ANOBJ_TEMPORARY) && !(flags & ACPI_NS_WALK_TEMP_NODES)) { status = AE_CTRL_DEPTH; } /* Type must match requested type */ else if (child_type == type) { /* * Found a matching node, invoke the user callback function. * Unlock the namespace if flag is set. */ if (flags & ACPI_NS_WALK_UNLOCK) { mutex_status = acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); if (ACPI_FAILURE(mutex_status)) { return_ACPI_STATUS(mutex_status); } } /* * Invoke the user function, either pre-order or post-order * or both. */ if (!node_previously_visited) { if (pre_order_visit) { status = pre_order_visit(child_node, level, context, return_value); } } else { if (post_order_visit) { status = post_order_visit(child_node, level, context, return_value); } } if (flags & ACPI_NS_WALK_UNLOCK) { mutex_status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); if (ACPI_FAILURE(mutex_status)) { return_ACPI_STATUS(mutex_status); } } switch (status) { case AE_OK: case AE_CTRL_DEPTH: /* Just keep going */ break; case AE_CTRL_TERMINATE: /* Exit now, with OK status */ return_ACPI_STATUS(AE_OK); default: /* All others are valid exceptions */ return_ACPI_STATUS(status); } } /* * Depth first search: Attempt to go down another level in the * namespace if we are allowed to. Don't go any further if we have * reached the caller specified maximum depth or if the user * function has specified that the maximum depth has been reached. */ if (!node_previously_visited && (level < max_depth) && (status != AE_CTRL_DEPTH)) { if (child_node->child) { /* There is at least one child of this node, visit it */ level++; parent_node = child_node; child_node = acpi_ns_get_next_node(parent_node, NULL); continue; } } /* No more children, re-visit this node */ if (!node_previously_visited) { node_previously_visited = TRUE; continue; } /* No more children, visit peers */ child_node = acpi_ns_get_next_node(parent_node, child_node); if (child_node) { node_previously_visited = FALSE; } /* No peers, re-visit parent */ else { /* * No more children of this node (acpi_ns_get_next_node failed), go * back upwards in the namespace tree to the node's parent. */ level--; child_node = parent_node; parent_node = parent_node->parent; node_previously_visited = TRUE; } } /* Complete walk, not terminated by user function */ return_ACPI_STATUS(AE_OK); }
d5d0644e8887decbe3fd94ca0818d1df76620441
89ac799bd004042f913c9205abd22feaf847f5be
/src/chara/snake/afterse.c
0a99a685fed2de0559fce0ffdbe93c144139d66e
[]
no_license
FoxdieTeam/mgs_reversing
de0b501e9a6318bf817e0d0f03af34c836a2f0b6
d057e3eb8bebeb645ca23db6ce690577268f59d5
refs/heads/master
2023-07-21T02:31:57.827478
2023-07-17T10:50:39
2023-07-17T10:50:39
223,033,157
270
35
null
2023-09-14T21:49:31
2019-11-20T21:44:13
C
UTF-8
C
false
false
1,120
c
afterse.c
#include "afterse.h" #include "libgv/libgv.h" #include "Game/game.h" #include "unknown.h" #include "map/map.h" extern char aAfterseC[]; // = "afterse.c" extern SVECTOR svector_800ABA10; void afterse_act_800603EC(Actor_afterse *pActor) { if ( --pActor->field_22_count_down == 0 ) { // Play the sound GM_Sound_800329C4(&svector_800ABA10, pActor->field_20_noise, 1); // Allow soliders/chavs/whatever to hear it GM_SetNoise(100, 16, &svector_800ABA10); // Die now we've done our stuff GV_DestroyActor_800151C8(&pActor->field_0); } } Actor_afterse *afterse_init_800604C0(short noise, short count_down) { Actor_afterse *pActor; if (noise != 0 && count_down != 0) { pActor = (Actor_afterse *)GV_NewActor_800150E4(6, sizeof(Actor_afterse)); if (pActor) { GV_SetNamedActor_8001514C(&pActor->field_0, (TActorFunction)afterse_act_800603EC, 0, aAfterseC); pActor->field_20_noise = noise; pActor->field_22_count_down = count_down; return pActor; } } return NULL; }
fb20de4b60a4f4ff67d6b68127f0ad98e1a6a7fd
a24c9a4fe4c912200e694e46992789c7e2f82dd1
/grader/assignments/threads/shared-data.c
b170cfec5135ccedea5aec33d16dff289e95d2f8
[ "BSD-2-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
cksystemsteaching/selfie
0e94758b0bfb69baa630dc4f073bed5dfc5027bb
cdd7c68e1fcaf3608527a4a85a50f57627afe9d6
refs/heads/main
2023-09-02T17:31:39.471055
2023-08-29T16:31:48
2023-08-29T16:31:48
41,832,998
2,406
485
BSD-2-Clause
2023-08-10T17:18:35
2015-09-02T23:40:53
Jupyter Notebook
UTF-8
C
false
false
429
c
shared-data.c
void* malloc(unsigned long); uint64_t pthread_create(); uint64_t pthread_join(uint64_t* status); void pthread_exit(uint64_t status); uint64_t global_variable = 0; int main(int argc, char** argv) { uint64_t tid; uint64_t* status; status = malloc(8); tid = pthread_create(); if (tid) pthread_join(status); else { global_variable = 32; pthread_exit(10); } return *status + global_variable; }
d5c0cd66947a2f8d9abe343268d35dbc84f71d2f
6436d1e6c23f9f43a8025889dc4414a3ad66acf2
/CvGameCoreDLL/CvGameCoreDLLUndefNew.h
08228adbce4004244fbcafa824352bce93632fde
[ "MIT" ]
permissive
dguenms/Dawn-of-Civilization
b710195c4f46fe11d9229182c3b1e07b77f42637
a305e7846d085d6edf1e9c472e8dfceee1c07dd4
refs/heads/develop
2023-09-04T04:57:00.086384
2023-09-01T15:24:28
2023-09-01T15:24:28
45,362,597
116
121
MIT
2023-02-08T00:18:53
2015-11-01T23:52:28
C++
UTF-8
C
false
false
121
h
CvGameCoreDLLUndefNew.h
#pragma once #ifdef USE_MEMMANAGER #undef new #undef malloc #undef realloc #undef _msize #undef free #endif
af1536d1dd3c38e11468209636244544fd4dacfd
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdScope.c
524819c2e7137ac849cef295a645e9fecc7cf050
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
2,423
c
EdbCmdScope.c
/** @file Copyright (c) 2007, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Edb.h" /** DebuggerCommand - Scope. @param CommandArg - The argument for this command @param DebuggerPrivate - EBC Debugger private data structure @param ExceptionType - Exception type. @param SystemContext - EBC system context. @retval EFI_DEBUG_CONTINUE - formal return value **/ EFI_DEBUG_STATUS DebuggerScope ( IN CHAR16 *CommandArg, IN EFI_DEBUGGER_PRIVATE_DATA *DebuggerPrivate, IN EFI_EXCEPTION_TYPE ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) { EFI_STATUS Status; UINTN Address; if (CommandArg == NULL) { EDBPrint (L"Scope: invalid Address\n"); return EFI_DEBUG_CONTINUE; } // // Load new scope // Status = Symboltoi (CommandArg, &Address); if (EFI_ERROR(Status)) { if (Status == EFI_NOT_FOUND) { Address = Xtoi(CommandArg); } else { // // Something wrong, let Symboltoi print error info. // EDBPrint (L"Command Argument error!\n"); return EFI_DEBUG_CONTINUE; } } DebuggerPrivate->InstructionScope = Address; EDBPrint (L"Scope: 0x%x\n", DebuggerPrivate->InstructionScope); EdbShowDisasm (DebuggerPrivate, SystemContext); // // Done // return EFI_DEBUG_CONTINUE; } /** DebuggerCommand - List. @param CommandArg - The argument for this command @param DebuggerPrivate - EBC Debugger private data structure @param ExceptionType - Exception type. @param SystemContext - EBC system context. @retval EFI_DEBUG_CONTINUE - formal return value **/ EFI_DEBUG_STATUS DebuggerList ( IN CHAR16 *CommandArg, IN EFI_DEBUGGER_PRIVATE_DATA *DebuggerPrivate, IN EFI_EXCEPTION_TYPE ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) { if (CommandArg == NULL) { EdbShowDisasm (DebuggerPrivate, SystemContext); } else { // // Load new list number // DebuggerPrivate->InstructionNumber = Atoi(CommandArg); EDBPrint (L"List Number: %d\n", DebuggerPrivate->InstructionNumber); EdbShowDisasm (DebuggerPrivate, SystemContext); } // // Done // return EFI_DEBUG_CONTINUE; }
e09ff5e2e629470a9d2eb7c9573c89c21dce5a25
7664f318ed04bd0680f3d82321c18896e3ef6ad5
/src/overlays/actors/ovl_En_Takara_Man/z_en_takara_man.h
48898909bcaae72409f40c55e3ab5508cbf06a40
[]
no_license
zeldaret/oot
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
refs/heads/master
2023-08-29T05:29:31.356427
2023-08-28T22:48:52
2023-08-28T22:48:52
247,875,738
4,401
802
null
2023-09-14T13:34:38
2020-03-17T04:02:19
C
UTF-8
C
false
false
835
h
z_en_takara_man.h
#ifndef Z_EN_TAKARA_MAN_H #define Z_EN_TAKARA_MAN_H #include "ultra64.h" #include "global.h" struct EnTakaraMan; typedef void (*EnTakaraManActionFunc)(struct EnTakaraMan*, PlayState*); typedef struct EnTakaraMan { /* 0x0000 */ Actor actor; /* 0x014C */ EnTakaraManActionFunc actionFunc; /* 0x0150 */ SkelAnime skelAnime; /* 0x0194 */ Vec3s jointTable[10]; /* 0x01D0 */ Vec3s morphTable[10]; /* 0x020C */ s16 dialogState; /* 0x020E */ s16 eyeTextureIdx; /* 0x0210 */ s16 eyeTimer; /* 0x0212 */ s16 unk_212; /* 0x0214 */ s16 unk_214; /* 0x0216 */ s16 originalRoomNum; /* 0x0218 */ s16 unk_218; /* 0x021A */ s16 unk_21A; /* 0x022C */ f32 height; /* 0x0220 */ Vec3f pos; /* 0x022C */ Vec3s unk_22C; /* 0x0232 */ Vec3s unk_232; } EnTakaraMan; // size = 0x0238 #endif
ba7e4fb74f84d42fe46ea75962b85515eefe15e5
aa3befea459382dc5c01c925653d54f435b3fb0f
/libs/libc/time/lib_gmtimer.c
d78d8e2ce63326eb9bafa9cc18b6c94591d86682
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
9,334
c
lib_gmtimer.c
/**************************************************************************** * libs/libc/time/lib_gmtimer.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdbool.h> #include <errno.h> #include <debug.h> #include <nuttx/clock.h> /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Calendar/UTC conversion routines */ static void clock_utc2calendar(time_t utc, FAR int *year, FAR int *month, FAR int *day); #ifdef CONFIG_GREGORIAN_TIME static void clock_utc2gregorian(time_t jdn, FAR int *year, FAR int *month, FAR int *day); #ifdef CONFIG_JULIAN_TIME static void clock_utc2julian(time_t jdn, FAR int *year, FAR int *month, FAR int *day); #endif /* CONFIG_JULIAN_TIME */ #endif /* CONFIG_GREGORIAN_TIME */ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: clock_utc2calendar, clock_utc2gregorian, and clock_utc2julian * * Description: * Calendar to UTC conversion routines. These conversions * are based on algorithms from p. 604 of Seidelman, P. K. * 1992. Explanatory Supplement to the Astronomical * Almanac. University Science Books, Mill Valley. * ****************************************************************************/ #ifdef CONFIG_GREGORIAN_TIME static void clock_utc2calendar(time_t utc, FAR int *year, FAR int *month, FAR int *day) { #ifdef CONFIG_JULIAN_TIME if (utc >= GREG_DUTC) { clock_utc2gregorian(utc + JD_OF_EPOCH, year, month, day); } else { clock_utc2julian (utc + JD_OF_EPOCH, year, month, day); } #else /* CONFIG_JULIAN_TIME */ clock_utc2gregorian(utc + JD_OF_EPOCH, year, month, day); #endif /* CONFIG_JULIAN_TIME */ } static void clock_utc2gregorian(time_t jd, FAR int *year, FAR int *month, FAR int *day) { long l; long n; long i; long j; long d; long m; long y; l = jd + 68569; n = (4 * l) / 146097; l = l - (146097 * n + 3) / 4; i = (4000 * (l + 1)) / 1461001; l = l - (1461 * i) / 4 + 31; j = (80 * l) / 2447; d = l - (2447 * j) / 80; l = j / 11; m = j + 2 - 12 * l; y = 100 * (n - 49) + i + l; *year = y; *month = m; *day = d; } #ifdef CONFIG_JULIAN_TIME static void clock_utc2julian(time_t jd, FAR int *year, FAR int *month, FAR int *day) { long j; long k; long l; long n; long d; long i; long m; long y; j = jd + 1402; k = (j - 1) / 1461; l = j - 1461 * k; n = (l - 1) / 365 - l / 1461; i = l - 365 * n + 30; j = (80 * i) / 2447; d = i - (2447 * j) / 80; i = j / 11; m = j + 2 - 12 * i; y = 4 * k + n + i - 4716; *year = y; *month = m; *day = d; } #endif /* CONFIG_JULIAN_TIME */ #else/* CONFIG_GREGORIAN_TIME */ /* Only handles dates since Jan 1, 1970 */ static void clock_utc2calendar(time_t days, FAR int *year, FAR int *month, FAR int *day) { int value; int min; int max; int tmp; bool leapyear; /* There is one leap year every four years, so we can get close with the * following: */ value = days / (4 * DAYSPERNYEAR + 1); /* Number of 4-years periods since the epoch */ days -= value * (4 * DAYSPERNYEAR + 1); /* Remaining days */ value <<= 2; /* Years since the epoch */ /* Then we will brute force the next 0-3 years * * Is this year a leap year? (we'll need this later too) */ leapyear = clock_isleapyear(value + EPOCH_YEAR); /* Get the number of days in the year */ tmp = (leapyear ? DAYSPERLYEAR : DAYSPERNYEAR); /* Do we have that many days left to account for? */ while (days >= tmp) { /* Yes.. bump up the year and subtract the number of days in the year */ value++; days -= tmp; /* Is the next year a leap year? */ leapyear = clock_isleapyear(value + EPOCH_YEAR); /* Get the number of days in the next year */ tmp = (leapyear ? DAYSPERLYEAR : DAYSPERNYEAR); } /* At this point, 'value' has the years since 1970 and 'days' has number * of days into that year. 'leapyear' is true if the year in 'value' is * a leap year. */ *year = EPOCH_YEAR + value; /* Handle the month (zero based) */ min = 0; max = 11; do { /* Get the midpoint */ value = (min + max) >> 1; /* Get the number of days that occurred before the beginning of the * month following the midpoint. */ tmp = clock_daysbeforemonth(value + 1, leapyear); /* Does the number of days before this month that equal or exceed the * number of days we have remaining? */ if (tmp > days) { /* Yes.. then the month we want is somewhere from 'min' and to the * midpoint, 'value'. Could it be the midpoint? */ tmp = clock_daysbeforemonth(value, leapyear); if (tmp > days) { /* No... The one we want is somewhere between min and value-1 */ max = value - 1; } else { /* Yes.. 'value' contains the month that we want */ break; } } else { /* No... The one we want is somewhere between value+1 and max */ min = value + 1; } /* If we break out of the loop because min == max, then we want value * to be equal to min == max. */ value = min; } while (min < max); /* The selected month number is in value. Subtract the number of days in * the selected month */ days -= clock_daysbeforemonth(value, leapyear); /* At this point, value has the month into this year (zero based) and days * has number of days into this month (zero based) */ *month = value + 1; /* 1-based */ *day = days + 1; /* 1-based */ } #endif /* CONFIG_GREGORIAN_TIME */ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: gmtime_r * * Description: * Time conversion (based on the POSIX API) * ****************************************************************************/ FAR struct tm *gmtime_r(FAR const time_t *timep, FAR struct tm *result) { time_t epoch; time_t jdn; int year; int month; int day; int hour; int min; int sec; /* Get the seconds since the EPOCH */ epoch = *timep; linfo("timer=%d\n", (int)epoch); /* Convert to days, hours, minutes, and seconds since the EPOCH */ jdn = epoch / SEC_PER_DAY; epoch -= SEC_PER_DAY * jdn; hour = epoch / SEC_PER_HOUR; epoch -= SEC_PER_HOUR * hour; min = epoch / SEC_PER_MIN; epoch -= SEC_PER_MIN * min; sec = epoch; linfo("hour=%d min=%d sec=%d\n", hour, min, sec); /* Convert the days since the EPOCH to calendar day */ clock_utc2calendar(jdn, &year, &month, &day); linfo("jdn=%d year=%d month=%d day=%d\n", (int)jdn, year, month, day); /* Then return the struct tm contents */ result->tm_year = year - TM_YEAR_BASE; /* Relative to 1900 */ result->tm_mon = month - 1; /* zero-based */ result->tm_mday = day; /* one-based */ result->tm_hour = hour; result->tm_min = min; result->tm_sec = sec; result->tm_wday = clock_dayoftheweek(day, month, year); result->tm_yday = day - 1 + clock_daysbeforemonth(result->tm_mon, clock_isleapyear(year)); result->tm_isdst = 0; result->tm_gmtoff = 0; result->tm_zone = NULL; return result; } FAR struct tm *localtime_r(FAR const time_t *timep, FAR struct tm *result) { return gmtime_r(timep, result); }
9bb853341b51711d9cf798e51a3c5c1330b4b12f
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/net/l2tp/l2tp_ip6.c
fdbdb265b7ca12da5ffdab15ed983136be6411b1
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
19,871
c
l2tp_ip6.c
/* * L2TPv3 IP encapsulation support for IPv6 * * Copyright (c) 2012 Katalix Systems Ltd * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <linux/socket.h> #include <linux/l2tp.h> #include <linux/in.h> #include <linux/in6.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/udp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/tcp_states.h> #include <net/protocol.h> #include <net/xfrm.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include "l2tp_core.h" struct l2tp_ip6_sock { /* inet_sock has to be the first member of l2tp_ip6_sock */ struct inet_sock inet; u32 conn_id; u32 peer_conn_id; /* ipv6_pinfo has to be the last member of l2tp_ip6_sock, see inet6_sk_generic */ struct ipv6_pinfo inet6; }; static DEFINE_RWLOCK(l2tp_ip6_lock); static struct hlist_head l2tp_ip6_table; static struct hlist_head l2tp_ip6_bind_table; static inline struct l2tp_ip6_sock *l2tp_ip6_sk(const struct sock *sk) { return (struct l2tp_ip6_sock *)sk; } static struct sock *__l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct sock *sk; sk_for_each_bound(sk, &l2tp_ip6_bind_table) { struct in6_addr *addr = inet6_rcv_saddr(sk); struct l2tp_ip6_sock *l2tp = l2tp_ip6_sk(sk); if (l2tp == NULL) continue; if ((l2tp->conn_id == tunnel_id) && net_eq(sock_net(sk), net) && !(addr && ipv6_addr_equal(addr, laddr)) && !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) goto found; } sk = NULL; found: return sk; } static inline struct sock *l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct sock *sk = __l2tp_ip6_bind_lookup(net, laddr, dif, tunnel_id); if (sk) sock_hold(sk); return sk; } /* When processing receive frames, there are two cases to * consider. Data frames consist of a non-zero session-id and an * optional cookie. Control frames consist of a regular L2TP header * preceded by 32-bits of zeros. * * L2TPv3 Session Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Cookie (optional, maximum 64 bits)... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * L2TPv3 Control Message Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (32 bits of zeros) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Control Connection ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ns | Nr | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * All control frames are passed to userspace. */ static int l2tp_ip6_recv(struct sk_buff *skb) { struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; int length; if (!pskb_may_pull(skb, 4)) goto discard; /* Point to L2TP header */ optr = ptr = skb->data; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_find(&init_net, NULL, session_id); if (session == NULL) goto discard; tunnel = session->tunnel; if (tunnel == NULL) goto discard; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard; /* Point to L2TP header */ optr = ptr = skb->data; ptr += 4; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); tunnel = l2tp_tunnel_find(&init_net, tunnel_id); if (tunnel != NULL) sk = tunnel->sock; else { struct ipv6hdr *iph = ipv6_hdr(skb); read_lock_bh(&l2tp_ip6_lock); sk = __l2tp_ip6_bind_lookup(&init_net, &iph->daddr, 0, tunnel_id); read_unlock_bh(&l2tp_ip6_lock); } if (sk == NULL) goto discard; sock_hold(sk); if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } static int l2tp_ip6_open(struct sock *sk) { /* Prevent autobind. We don't have ports. */ inet_sk(sk)->inet_num = IPPROTO_L2TP; write_lock_bh(&l2tp_ip6_lock); sk_add_node(sk, &l2tp_ip6_table); write_unlock_bh(&l2tp_ip6_lock); return 0; } static void l2tp_ip6_close(struct sock *sk, long timeout) { write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sk_common_release(sk); } static void l2tp_ip6_destroy_sock(struct sock *sk) { struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk); lock_sock(sk); ip6_flush_pending_frames(sk); release_sock(sk); if (tunnel) { l2tp_tunnel_closeall(tunnel); sock_put(sk); } inet6_destroy_sock(sk); } static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr; __be32 v4addr = 0; int addr_type; int err; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr->l2tp_family != AF_INET6) return -EINVAL; if (addr_len < sizeof(*addr)) return -EINVAL; addr_type = ipv6_addr_type(&addr->l2tp_addr); /* l2tp_ip6 sockets are IPv6 only */ if (addr_type == IPV6_ADDR_MAPPED) return -EADDRNOTAVAIL; /* L2TP is point-point, not multicast */ if (addr_type & IPV6_ADDR_MULTICAST) return -EADDRNOTAVAIL; err = -EADDRINUSE; read_lock_bh(&l2tp_ip6_lock); if (__l2tp_ip6_bind_lookup(&init_net, &addr->l2tp_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip6_lock); lock_sock(sk); err = -EINVAL; if (sk->sk_state != TCP_CLOSE) goto out_unlock; /* Check if the address belongs to the host. */ rcu_read_lock(); if (addr_type != IPV6_ADDR_ANY) { struct net_device *dev = NULL; if (addr_type & IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && addr->l2tp_scope_id) { /* Override any existing binding, if another * one is supplied by user. */ sk->sk_bound_dev_if = addr->l2tp_scope_id; } /* Binding to link-local address requires an interface */ if (!sk->sk_bound_dev_if) goto out_unlock_rcu; err = -ENODEV; dev = dev_get_by_index_rcu(sock_net(sk), sk->sk_bound_dev_if); if (!dev) goto out_unlock_rcu; } /* ipv4 addr of the socket is invalid. Only the * unspecified and mapped address have a v4 equivalent. */ v4addr = LOOPBACK4_IPV6; err = -EADDRNOTAVAIL; if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0)) goto out_unlock_rcu; } rcu_read_unlock(); inet->inet_rcv_saddr = inet->inet_saddr = v4addr; np->rcv_saddr = addr->l2tp_addr; np->saddr = addr->l2tp_addr; l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); sk_add_bind_node(sk, &l2tp_ip6_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sock_reset_flag(sk, SOCK_ZAPPED); release_sock(sk); return 0; out_unlock_rcu: rcu_read_unlock(); out_unlock: release_sock(sk); return err; out_in_use: read_unlock_bh(&l2tp_ip6_lock); return err; } static int l2tp_ip6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) uaddr; struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct in6_addr *daddr; int addr_type; int rc; if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */ return -EINVAL; if (addr_len < sizeof(*lsa)) return -EINVAL; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -EINVAL; if (addr_type & IPV6_ADDR_MAPPED) { daddr = &usin->sin6_addr; if (ipv4_is_multicast(daddr->s6_addr32[3])) return -EINVAL; } rc = ip6_datagram_connect(sk, uaddr, addr_len); lock_sock(sk); l2tp_ip6_sk(sk)->peer_conn_id = lsa->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_add_bind_node(sk, &l2tp_ip6_bind_table); write_unlock_bh(&l2tp_ip6_lock); release_sock(sk); return rc; } static int l2tp_ip6_disconnect(struct sock *sk, int flags) { if (sock_flag(sk, SOCK_ZAPPED)) return 0; return udp_disconnect(sk, flags); } static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_unused = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } static int l2tp_ip6_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; /* Charge it to the socket, dropping if the queue is full. */ rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) goto drop; return 0; drop: IP_INC_STATS(&init_net, IPSTATS_MIB_INDISCARDS); kfree_skb(skb); return -1; } static int l2tp_ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; __be32 *transhdr = NULL; int err = 0; skb = skb_peek(&sk->sk_write_queue); if (skb == NULL) goto out; transhdr = (__be32 *)skb_transport_header(skb); *transhdr = 0; err = ip6_push_pending_frames(sk); out: return err; } /* Userspace will call sendmsg() on the tunnel socket to send L2TP * control frames. */ static int l2tp_ip6_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) msg->msg_name; struct in6_addr *daddr, *final_p, final; struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct dst_entry *dst = NULL; struct flowi6 fl6; int addr_len = msg->msg_namelen; int hlimit = -1; int tclass = -1; int dontfrag = -1; int transhdrlen = 4; /* zero session-id */ int ulen = len + transhdrlen; int err; /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX) return -EMSGSIZE; /* Mirror BSD error message compatibility */ if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* * Get and verify the address. */ memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_mark = sk->sk_mark; if (lsa) { if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) return -EAFNOSUPPORT; daddr = &lsa->l2tp_addr; if (np->sndflow) { fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; daddr = &flowlabel->dst; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &np->daddr)) daddr = &np->daddr; if (addr_len >= sizeof(struct sockaddr_in6) && lsa->l2tp_scope_id && ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) fl6.flowi6_oif = lsa->l2tp_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &np->daddr; fl6.flowlabel = np->flow_label; } if (fl6.flowi6_oif == 0) fl6.flowi6_oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(struct ipv6_txoptions); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; } if (opt == NULL) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; final_p = fl6_update_dst(&fl6, opt, &final); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } if (hlimit < 0) { if (ipv6_addr_is_multicast(&fl6.daddr)) hlimit = np->mcast_hops; else hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); } if (tclass < 0) tclass = np->tclass; if (dontfrag < 0) dontfrag = np->dontfrag; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: lock_sock(sk); err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, transhdrlen, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); if (err) ip6_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) err = l2tp_ip6_push_pending_frames(sk); release_sock(sk); done: dst_release(dst); out: fl6_sock_release(flowlabel); return err < 0 ? err : len; do_confirm: dst_confirm(dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_conn_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } static struct proto l2tp_ip6_prot = { .name = "L2TP/IPv6", .owner = THIS_MODULE, .init = l2tp_ip6_open, .close = l2tp_ip6_close, .bind = l2tp_ip6_bind, .connect = l2tp_ip6_connect, .disconnect = l2tp_ip6_disconnect, .ioctl = udp_ioctl, .destroy = l2tp_ip6_destroy_sock, .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .sendmsg = l2tp_ip6_sendmsg, .recvmsg = l2tp_ip6_recvmsg, .backlog_rcv = l2tp_ip6_backlog_recv, .hash = inet_hash, .unhash = inet_unhash, .obj_size = sizeof(struct l2tp_ip6_sock), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif }; static const struct proto_ops l2tp_ip6_ops = { .family = PF_INET6, .owner = THIS_MODULE, .release = inet6_release, .bind = inet6_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = l2tp_ip6_getname, .poll = datagram_poll, .ioctl = inet6_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw l2tp_ip6_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_L2TP, .prot = &l2tp_ip6_prot, .ops = &l2tp_ip6_ops, .no_check = 0, }; static struct inet6_protocol l2tp_ip6_protocol __read_mostly = { .handler = l2tp_ip6_recv, }; static int __init l2tp_ip6_init(void) { int err; pr_info("L2TP IP encapsulation support for IPv6 (L2TPv3)\n"); err = proto_register(&l2tp_ip6_prot, 1); if (err != 0) goto out; err = inet6_add_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); if (err) goto out1; inet6_register_protosw(&l2tp_ip6_protosw); return 0; out1: proto_unregister(&l2tp_ip6_prot); out: return err; } static void __exit l2tp_ip6_exit(void) { inet6_unregister_protosw(&l2tp_ip6_protosw); inet6_del_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); proto_unregister(&l2tp_ip6_prot); } module_init(l2tp_ip6_init); module_exit(l2tp_ip6_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Chris Elston <celston@katalix.com>"); MODULE_DESCRIPTION("L2TP IP encapsulation for IPv6"); MODULE_VERSION("1.0"); /* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like * enums */ MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 2, IPPROTO_L2TP);
2c105dbbf9303c425c1463f8bc824f9dcb80eeec
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/opus/src/silk/resampler_down2_3.c
4342614dcccc11348bf9e45c4e20691e19f69982
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause-Clear", "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C
false
false
4,765
c
resampler_down2_3.c
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "SigProc_FIX.h" #include "resampler_private.h" #include "stack_alloc.h" #define ORDER_FIR 4 /* Downsample by a factor 2/3, low quality */ void silk_resampler_down2_3( opus_int32 *S, /* I/O State vector [ 6 ] */ opus_int16 *out, /* O Output signal [ floor(2*inLen/3) ] */ const opus_int16 *in, /* I Input signal [ inLen ] */ opus_int32 inLen /* I Number of input samples */ ) { opus_int32 nSamplesIn, counter, res_Q6; VARDECL( opus_int32, buf ); opus_int32 *buf_ptr; SAVE_STACK; ALLOC( buf, RESAMPLER_MAX_BATCH_SIZE_IN + ORDER_FIR, opus_int32 ); /* Copy buffered samples to start of buffer */ silk_memcpy( buf, S, ORDER_FIR * sizeof( opus_int32 ) ); /* Iterate over blocks of frameSizeIn input samples */ while( 1 ) { nSamplesIn = silk_min( inLen, RESAMPLER_MAX_BATCH_SIZE_IN ); /* Second-order AR filter (output in Q8) */ silk_resampler_private_AR2( &S[ ORDER_FIR ], &buf[ ORDER_FIR ], in, silk_Resampler_2_3_COEFS_LQ, nSamplesIn ); /* Interpolate filtered signal */ buf_ptr = buf; counter = nSamplesIn; while( counter > 2 ) { /* Inner product */ res_Q6 = silk_SMULWB( buf_ptr[ 0 ], silk_Resampler_2_3_COEFS_LQ[ 2 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 1 ], silk_Resampler_2_3_COEFS_LQ[ 3 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], silk_Resampler_2_3_COEFS_LQ[ 5 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], silk_Resampler_2_3_COEFS_LQ[ 4 ] ); /* Scale down, saturate and store in output array */ *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) ); res_Q6 = silk_SMULWB( buf_ptr[ 1 ], silk_Resampler_2_3_COEFS_LQ[ 4 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], silk_Resampler_2_3_COEFS_LQ[ 5 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], silk_Resampler_2_3_COEFS_LQ[ 3 ] ); res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 4 ], silk_Resampler_2_3_COEFS_LQ[ 2 ] ); /* Scale down, saturate and store in output array */ *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) ); buf_ptr += 3; counter -= 3; } in += nSamplesIn; inLen -= nSamplesIn; if( inLen > 0 ) { /* More iterations to do; copy last part of filtered signal to beginning of buffer */ silk_memcpy( buf, &buf[ nSamplesIn ], ORDER_FIR * sizeof( opus_int32 ) ); } else { break; } } /* Copy last part of filtered signal to the state for the next call */ silk_memcpy( S, &buf[ nSamplesIn ], ORDER_FIR * sizeof( opus_int32 ) ); RESTORE_STACK; }