hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
b79280a423e947c091084a99406e7da89b2bd3aa
8,810
h
C
L1Trigger/GlobalCaloTrigger/interface/L1GctGlobalEnergyAlgos.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/GlobalCaloTrigger/interface/L1GctGlobalEnergyAlgos.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/GlobalCaloTrigger/interface/L1GctGlobalEnergyAlgos.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef L1GCTGLOBALENERGYALGOS_H_ #define L1GCTGLOBALENERGYALGOS_H_ #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctEtTotal.h" #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctEtHad.h" #include "DataFormats/L1GlobalCaloTrigger/interface/L1GctEtMiss.h" #include "L1Trigger/GlobalCaloTrigger/interface/L1GctProcessor.h" #include "L1Trigger/GlobalCaloTrigger/interface/L1GctMet.h" #include <vector> class L1GctWheelEnergyFpga; class L1GctWheelJetFpga; class L1GctGlobalHfSumAlgos; /*! * \class L1GctGlobalEnergyAlgos * \brief Emulates the GCT global energy algorithms * * This class carries out the final stage of summing of * total Et, missing Et components Ex and Ey, calibrated * jet energy Ht, and jet counts. It converts the final * missing Ex and Ey sums to magnitude and direction. * The inputs come from the two Wheel cards * and the outputs are sent to the Global Trigger. * * \author Jim Brooke & Greg Heath * \date 20/2/2006 * */ class L1GctGlobalEnergyAlgos : public L1GctProcessor { public: typedef L1GctUnsignedInt<L1GctEtTotal::kEtTotalNBits> etTotalType; typedef L1GctUnsignedInt<L1GctEtHad::kEtHadNBits> etHadType; typedef L1GctMet::etMissType etMissType; typedef L1GctMet::etMissPhiType etMissPhiType; typedef L1GctMet::etmiss_vec etmiss_vec; typedef L1GctWheelEnergyFpga::etComponentType etComponentType; enum maxValues { etTotalMaxValue = L1GctEtTotal::kEtTotalMaxValue, etHadMaxValue = L1GctEtHad::kEtHadMaxValue, etMissMaxValue = L1GctEtMiss::kEtMissMaxValue }; /// Constructor needs the Wheel card Fpgas set up first L1GctGlobalEnergyAlgos(const std::vector<L1GctWheelEnergyFpga*>& WheelFpga, const std::vector<L1GctWheelJetFpga*>& WheelJetFpga); /// Destructor ~L1GctGlobalEnergyAlgos() override; /// Overload << operator friend std::ostream& operator<<(std::ostream& os, const L1GctGlobalEnergyAlgos& fpga); /// clear internal buffers void reset(); /// get input data from sources void fetchInput() override; /// process the data, fill output buffers void process() override; /// define the bunch crossing range to process void setBxRange(const int firstBx, const int numberOfBx); /// partially clear buffers void setNextBx(const int bx); /// set input Ex value per wheel (0 or 1); not used in normal operation void setInputWheelEx(unsigned wheel, int energy, bool overflow); /// set input Ey value per wheel (0 or 1); not used in normal operation void setInputWheelEy(unsigned wheel, int energy, bool overflow); /// set input Et value per wheel (0 or 1); not used in normal operation void setInputWheelEt(unsigned wheel, unsigned energy, bool overflow); /// set input Ht value per wheel (0 or 1); not used in normal operation void setInputWheelHt(unsigned wheel, unsigned energy, bool overflow); /// set input Ht component values per wheel (0 or 1); not used in normal operation void setInputWheelHx(unsigned wheel, unsigned energy, bool overflow); void setInputWheelHy(unsigned wheel, unsigned energy, bool overflow); /// set input jet count (number 0-11) per wheel (0 or 1); not used in normal operation void setInputWheelJc(unsigned wheel, unsigned jcnum, unsigned count); /// provide access to input pointer, Wheel Energy Fpga 1 L1GctWheelEnergyFpga* getPlusWheelFpga() const { return m_plusWheelFpga; } /// provide access to input pointer, Wheel Energy Fpga 0 L1GctWheelEnergyFpga* getMinusWheelFpga() const { return m_minusWheelFpga; } /// provide access to input pointer, Wheel Jet Fpga 1 L1GctWheelJetFpga* getPlusWheelJetFpga() const { return m_plusWheelJetFpga; } /// provide access to input pointer, Wheel Jet Fpga 0 L1GctWheelJetFpga* getMinusWheelJetFpga() const { return m_minusWheelJetFpga; } /// provide access to hf sum processor L1GctGlobalHfSumAlgos* getHfSumProcessor() const { return m_hfSumProcessor; } /// return input Ex value wheel 1 inline std::vector<etComponentType> getInputExValPlusWheel() const { return m_exValPlusPipe.contents; } /// return input Ex value wheel 1 inline std::vector<etComponentType> getInputEyValPlusWheel() const { return m_eyValPlusPipe.contents; } /// return input Ey value wheel 0 inline std::vector<etComponentType> getInputExVlMinusWheel() const { return m_exVlMinusPipe.contents; } /// return input Ey value wheel 0 inline std::vector<etComponentType> getInputEyVlMinusWheel() const { return m_eyVlMinusPipe.contents; } /// return input Et value wheel 1 inline std::vector<etTotalType> getInputEtValPlusWheel() const { return m_etValPlusPipe.contents; } /// return input Ht value wheel 1 inline std::vector<etHadType> getInputHtValPlusWheel() const { return m_htValPlusPipe.contents; } /// return input Ht component values wheel 1 inline std::vector<etComponentType> getInputHxValPlusWheel() const { return m_hxValPlusPipe.contents; } inline std::vector<etComponentType> getInputHyValPlusWheel() const { return m_hyValPlusPipe.contents; } /// return input Et value wheel 0 inline std::vector<etTotalType> getInputEtVlMinusWheel() const { return m_etVlMinusPipe.contents; } /// return input Ht value wheel 0 inline std::vector<etHadType> getInputHtVlMinusWheel() const { return m_htVlMinusPipe.contents; } /// return input Ht value wheel 0 inline std::vector<etComponentType> getInputHxVlMinusWheel() const { return m_hxVlMinusPipe.contents; } inline std::vector<etComponentType> getInputHyVlMinusWheel() const { return m_hyVlMinusPipe.contents; } /// Access to output quantities for all bunch crossings /// return output missing Et magnitude inline std::vector<etMissType> getEtMissColl() const { return m_outputEtMiss.contents; } /// return output missing Et value inline std::vector<etMissPhiType> getEtMissPhiColl() const { return m_outputEtMissPhi.contents; } /// return output total scalar Et inline std::vector<etTotalType> getEtSumColl() const { return m_outputEtSum.contents; } /// return std::vector< output calibrated jet Et inline std::vector<etHadType> getEtHadColl() const { return m_outputEtHad.contents; } /// return output missing Ht magnitude inline std::vector<etMissType> getHtMissColl() const { return m_outputHtMiss.contents; } /// return output missing Ht value inline std::vector<etMissPhiType> getHtMissPhiColl() const { return m_outputHtMissPhi.contents; } void setJetFinderParams(const L1GctJetFinderParams* const jfpars); void setHtMissScale(const L1CaloEtScale* const scale); // get the missing Ht LUT (used by L1GctPrintLuts) const L1GctHtMissLut* getHtMissLut() const { return m_mhtComponents.getHtMissLut(); } /// check setup bool setupOk() const; protected: /// Separate reset methods for the processor itself and any data stored in pipelines void resetProcessor() override; void resetPipelines() override; /// Initialise inputs with null objects for the correct bunch crossing if required void setupObjects() override {} private: // Here are the algorithm types we get our inputs from L1GctWheelEnergyFpga* m_plusWheelFpga; L1GctWheelEnergyFpga* m_minusWheelFpga; L1GctWheelJetFpga* m_plusWheelJetFpga; L1GctWheelJetFpga* m_minusWheelJetFpga; // Here's the class that does the Hf sums L1GctGlobalHfSumAlgos* m_hfSumProcessor; // Missing Et and missing Ht L1GctMet m_metComponents; L1GctMet m_mhtComponents; // input data etComponentType m_exValPlusWheel; etComponentType m_eyValPlusWheel; etTotalType m_etValPlusWheel; etHadType m_htValPlusWheel; etComponentType m_hxValPlusWheel; etComponentType m_hyValPlusWheel; etComponentType m_exVlMinusWheel; etComponentType m_eyVlMinusWheel; etTotalType m_etVlMinusWheel; etHadType m_htVlMinusWheel; etComponentType m_hxVlMinusWheel; etComponentType m_hyVlMinusWheel; // stored copies of input data Pipeline<etComponentType> m_exValPlusPipe; Pipeline<etComponentType> m_eyValPlusPipe; Pipeline<etTotalType> m_etValPlusPipe; Pipeline<etHadType> m_htValPlusPipe; Pipeline<etComponentType> m_hxValPlusPipe; Pipeline<etComponentType> m_hyValPlusPipe; Pipeline<etComponentType> m_exVlMinusPipe; Pipeline<etComponentType> m_eyVlMinusPipe; Pipeline<etTotalType> m_etVlMinusPipe; Pipeline<etHadType> m_htVlMinusPipe; Pipeline<etComponentType> m_hxVlMinusPipe; Pipeline<etComponentType> m_hyVlMinusPipe; // output data Pipeline<etMissType> m_outputEtMiss; Pipeline<etMissPhiType> m_outputEtMissPhi; Pipeline<etTotalType> m_outputEtSum; Pipeline<etHadType> m_outputEtHad; Pipeline<etMissType> m_outputHtMiss; Pipeline<etMissPhiType> m_outputHtMissPhi; bool m_setupOk; }; std::ostream& operator<<(std::ostream& os, const L1GctGlobalEnergyAlgos& fpga); #endif /*L1GCTGLOBALENERGYALGOS_H_*/
41.952381
105
0.77639
[ "vector" ]
b799c0b72f746bba280e2b5e777926abbe588254
3,226
h
C
source/Irrlicht/CParticleAttractionAffector.h
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
source/Irrlicht/CParticleAttractionAffector.h
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
5
2021-01-03T20:30:10.000Z
2021-01-03T21:46:53.000Z
source/Irrlicht/CParticleAttractionAffector.h
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_PARTICLE_ATTRACTION_AFFECTOR_H_INCLUDED__ #define __C_PARTICLE_ATTRACTION_AFFECTOR_H_INCLUDED__ #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_PARTICLES_ #include "IParticleAttractionAffector.h" namespace irr { namespace scene { //! Particle Affector for attracting particles to a point class CParticleAttractionAffector : public IParticleAttractionAffector { public: CParticleAttractionAffector( const core::vector3df& point = core::vector3df(), f32 speed = 1.0f, bool attract = true, bool affectX = true, bool affectY = true, bool affectZ = true ); //! Affects a particle. virtual void affect(u32 now, SParticle* particlearray, u32 count) _IRR_OVERRIDE_; //! Set the point that particles will attract to virtual void setPoint( const core::vector3df& point ) _IRR_OVERRIDE_ { Point = point; } //! Set the speed, in game units per second that the particles will attract to the specified point virtual void setSpeed( f32 speed ) _IRR_OVERRIDE_ { Speed = speed; } //! Set whether or not the particles are attracting or detracting virtual void setAttract( bool attract ) _IRR_OVERRIDE_ { Attract = attract; } //! Set whether or not this will affect particles in the X direction virtual void setAffectX( bool affect ) _IRR_OVERRIDE_ { AffectX = affect; } //! Set whether or not this will affect particles in the Y direction virtual void setAffectY( bool affect ) _IRR_OVERRIDE_ { AffectY = affect; } //! Set whether or not this will affect particles in the Z direction virtual void setAffectZ( bool affect ) _IRR_OVERRIDE_ { AffectZ = affect; } //! Get the point that particles are attracted to virtual const core::vector3df& getPoint() const _IRR_OVERRIDE_ { return Point; } //! Get the speed that points attract to the specified point virtual f32 getSpeed() const _IRR_OVERRIDE_ { return Speed; } //! Get whether or not the particles are attracting or detracting virtual bool getAttract() const _IRR_OVERRIDE_ { return Attract; } //! Get whether or not the particles X position are affected virtual bool getAffectX() const _IRR_OVERRIDE_ { return AffectX; } //! Get whether or not the particles Y position are affected virtual bool getAffectY() const _IRR_OVERRIDE_ { return AffectY; } //! Get whether or not the particles Z position are affected virtual bool getAffectZ() const _IRR_OVERRIDE_ { return AffectZ; } //! Writes attributes of the object. virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const _IRR_OVERRIDE_; //! Reads attributes of the object. virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) _IRR_OVERRIDE_; private: core::vector3df Point; f32 Speed; bool AffectX; bool AffectY; bool AffectZ; bool Attract; u32 LastTime; }; } // end namespace scene } // end namespace irr #endif // _IRR_COMPILE_WITH_PARTICLES_ #endif // __C_PARTICLE_ATTRACTION_AFFECTOR_H_INCLUDED__
35.450549
119
0.747675
[ "object" ]
b7a1037cf4472461c885050fd9f0bba544374757
8,021
c
C
watt32-2.2dev.rel.11/src/geteth.c
SuperIlu/jSH
628d976a6167c8f81701c236674759666bf47986
[ "BSD-2-Clause" ]
30
2019-06-01T20:16:04.000Z
2022-03-18T21:38:49.000Z
watt32-2.2dev.rel.11/src/geteth.c
SuperIlu/jSH
628d976a6167c8f81701c236674759666bf47986
[ "BSD-2-Clause" ]
8
2019-06-05T16:10:45.000Z
2021-05-27T18:09:08.000Z
watt32-2.2dev.rel.11/src/geteth.c
SuperIlu/jSH
628d976a6167c8f81701c236674759666bf47986
[ "BSD-2-Clause" ]
3
2019-12-24T14:47:23.000Z
2020-12-16T12:48:33.000Z
/*!\file geteth.c * * `/etc/ethers' file functions for Watt-32. */ /* Copyright (c) 1997-2002 Gisle Vanem <gvanem@yahoo.no> * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Gisle Vanem * Bergen, Norway. * * THIS SOFTWARE IS PROVIDED BY ME (Gisle Vanem) 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 I 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. * * * 28.apr 2000 - Created */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wattcp.h" #include "misc.h" #include "run.h" #include "pcarp.h" #include "pcconfig.h" #include "pcdns.h" #include "pcdbug.h" #include "strings.h" #include "netaddr.h" #include "bsddbug.h" #include "get_xby.h" #if defined(USE_BSD_API) #include <net/if.h> #include <net/if_arp.h> #include <net/if_dl.h> #include <net/if_ether.h> #include <net/route.h> #if defined(TEST_PROG) #undef SOCK_DEBUGF #define SOCK_DEBUGF(args) printf args #endif #if !defined(USE_BUFFERED_IO) #error This file needs USE_BUFFERED_IO #endif struct ethent { eth_address eth_addr; /* ether/MAC address of host */ DWORD ip_addr; /* IP-address (host order) */ char *name; /* host-name for IP-address */ struct ethent *next; }; static struct ethent *eth0 = NULL; static int num_entries = -1; static char ethersFname [MAX_PATHLEN] = ""; static void W32_CALL end_ether_entries (void); static int get_ether_entry (char *in_buf, eth_address *e, char *out_buf, size_t out_buf_size); void W32_CALL InitEthersFile (const char *fname) { if (fname && *fname) _strlcpy (ethersFname, fname, sizeof(ethersFname)); } const char * W32_CALL GetEthersFile (void) { return (ethersFname[0] ? ethersFname : NULL); } int W32_CALL NumEtherEntries (void) { return (num_entries); } /** * Read the /etc/ethers file. This MUST be called after any /etc/hosts * file has been read. * \todo: Assert that. */ void W32_CALL ReadEthersFile (void) { FILE *file; char buf [2*MAX_HOSTLEN]; if (!ethersFname[0]) return; if (!FOPEN_TXT(file, ethersFname)) { netdb_warn (ethersFname); return; } while (fgets(buf,sizeof(buf),file)) { struct ethent *e; struct hostent *h; char host_ip [MAX_HOSTLEN]; int save; eth_address eth; if (!get_ether_entry(buf,&eth,host_ip,sizeof(host_ip))) continue; if (num_entries == -1) num_entries = 0; num_entries++; save = called_from_resolve; called_from_resolve = TRUE; /* prevent a DNS lookup */ h = gethostbyname (host_ip); called_from_resolve = save; /* If 'h == NULL': means 'host_ip' contained a host-name that cannot be resolved * at this moment. gethostbyname()+resolve() cannot be called at startup. * If 'h != NULL': means 'host_ip' is simply an IPv4-address or a host-name (or alias) * that is in '/etc/hosts' file. */ if (!h) { CONSOLE_MSG (4, ("ReadEthersFile(): gethostbyname() failed\n")); continue; } CONSOLE_MSG (4, ("\n")); e = calloc (sizeof(*e), 1); if (!e) break; e->ip_addr = ntohl (*(DWORD*)h->h_addr); memcpy (&e->eth_addr, &eth, sizeof(e->eth_addr)); /* Add this to the permanent ARP-cache. */ _arp_cache_add (e->ip_addr, &e->eth_addr, FALSE); if (h->h_name) { e->name = strdup (h->h_name); if (!e->name) break; } e->next = eth0; eth0 = e; } FCLOSE (file); RUNDOWN_ADD (end_ether_entries, 250); } /* * Parse a string of text containing an ethernet address and * hostname/IP-address and separate it into its component parts. * E.g. * in_buf -> "88-87-17-17-5a-3e 10.0.0.4" * in_buf -> "E0-CA-94-3D-74-F0 printer" */ #define MIN_LEN sizeof("0:0:0:0:0:0 a.b.c.d") static int get_ether_entry (char *in_buf, eth_address *e, char *name, size_t name_max) { size_t len, i; unsigned eth [sizeof(*e)]; BOOL ok, colon; char *token = strltrim (in_buf); char *ip_name; char *tok_buf = NULL; if (*token == '#' || *token == ';' || *token == '\n' || strlen(token) < MIN_LEN) return (0); colon = (token[2] == ':'); ok = colon ? (sscanf(token, "%02x:%02x:%02x:%02x:%02x:%02x", &eth[0], &eth[1], &eth[2], &eth[3], &eth[4], &eth[5]) == DIM(eth)) : (sscanf(token, "%02x-%02x-%02x-%02x-%02x-%02x", &eth[0], &eth[1], &eth[2], &eth[3], &eth[4], &eth[5]) == DIM(eth)); if (!ok) { CONSOLE_MSG (1, ("get_ether_entry(): sscanf() failed\n")); return (0); } token = strtok_r (token, " \t", &tok_buf); ip_name = strtok_r (NULL, " #\t\n", &tok_buf); if (!token || !ip_name || (len = strlen(ip_name)) < 1 || len > name_max) { CONSOLE_MSG (1, ("get_ether_entry(): short line or malformed ip_name '%s'\n", ip_name)); return (0); } ip_name = (char*) expand_var_str (ip_name); _strlcpy (name, ip_name, name_max); for (i = 0; i < sizeof(*e); i++) ((BYTE*)e)[i] = eth[i]; CONSOLE_MSG (4, ("get_ether_entry(): ip: %s, eth: %02X:%02X:%02X:%02X:%02X:%02X\n", ip_name, eth[0],eth[1],eth[2],eth[3],eth[4],eth[5])); return (1); } /* * Free memory in 'eth0' array */ static void W32_CALL end_ether_entries (void) { struct ethent *e, *next; if (_watt_fatal_error) return; for (e = eth0; e; e = next) { DO_FREE (e->name); next = e->next; free (e); } eth0 = NULL; num_entries = 0; } void W32_CALL DumpEthersCache (void) { const struct ethent *e; if (!ethersFname[0]) { SOCK_DEBUGF (("No ETHERS line found in WATTCP.CFG\n")); return; } SOCK_DEBUGF (("\n%s entries:\n", ethersFname)); for (e = eth0; e; e = e->next) SOCK_DEBUGF ((" %s = %-15.15s (%s)\n", MAC_address(&e->eth_addr), _inet_ntoa(NULL,e->ip_addr), e->name ? e->name : "none")); } #endif /* USE_BSD_API */ /* * Find the name associated with ether-addr 'eth'. * Returns null if not found in 'eth0' list. */ const char * W32_CALL GetEtherName (const eth_address *eth) { #if defined(USE_BSD_API) const struct ethent *e; for (e = eth0; e; e = e->next) if (!memcmp(eth, e->eth_addr, sizeof(*eth))) return (e->name); #endif ARGSUSED (eth); return (NULL); } #if defined(TEST_PROG) #include "pcdbug.h" #include "sock_ini.h" int main (void) { #if defined(USE_BSD_API) debug_on = 2; dbug_init(); sock_init(); DumpEthersCache(); #else puts ("\"USE_BSD_API\" not defined"); #endif /* USE_BSD_API */ return (0); } #endif /* TEST_PROG */
26.042208
93
0.61526
[ "3d" ]
b7a1571b5b0de942f5d8dedf4bc5b29eab8f42aa
13,972
c
C
src/lpcnet_quant.c
doronbehar/LPCNet
aa6b56808d6da50e754d449305ae2a8a457e5e19
[ "BSD-3-Clause" ]
59
2019-03-26T09:21:34.000Z
2022-03-04T13:43:16.000Z
src/lpcnet_quant.c
doronbehar/LPCNet
aa6b56808d6da50e754d449305ae2a8a457e5e19
[ "BSD-3-Clause" ]
29
2019-03-26T20:05:24.000Z
2022-01-11T05:16:42.000Z
src/lpcnet_quant.c
doronbehar/LPCNet
aa6b56808d6da50e754d449305ae2a8a457e5e19
[ "BSD-3-Clause" ]
23
2019-04-18T11:57:47.000Z
2022-03-21T00:52:59.000Z
/* lpcnet_quant.c David Rowe Feb 2019 David's experimental quanisation functions for LPCNet */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "lpcnet_quant.h" #include "mbest.h" #include "freq.h" FILE *lpcnet_fsv = NULL; int lpcnet_verbose = 0; #define PITCH_MIN_PERIOD 32 #define PITCH_MAX_PERIOD 256 // defaults #define DEFAULT_WEIGHT 1.0/sqrt(NB_BANDS) #define DEFAULT_PRED 0.9 #define DEFAULT_NUM_STAGES 4 #define DEFAULT_MBEST 5 #define DEFAULT_PITCH_BITS 6 #define DEFAULT_DEC 3 static int quantise(const float * cb, float vec[], float w[], int k, int m, float *se); LPCNET_QUANT *lpcnet_quant_create(int direct_split) { LPCNET_QUANT *q = (LPCNET_QUANT*)malloc(sizeof(LPCNET_QUANT)); if (q == NULL) return NULL; if (direct_split) { q->weight = 1.0; q->pred = 0.0; q->mbest = DEFAULT_MBEST; q->pitch_bits = DEFAULT_PITCH_BITS; q->dec = DEFAULT_DEC; q->num_stages = direct_split_num_stages; q->vq = direct_split_vq; q->m = direct_split_m; q->logmag = 1; } else { q->weight = DEFAULT_WEIGHT; q->pred = DEFAULT_PRED; q->mbest = DEFAULT_MBEST; q->pitch_bits = DEFAULT_PITCH_BITS; q->dec = DEFAULT_DEC; q->num_stages = pred_num_stages; q->vq = pred_vq; q->m = pred_m; q->logmag = 0; } lpcnet_quant_compute_bits_per_frame(q); int i,d; for(i=0; i<NB_FEATURES; i++) q->features_quant[i] = 0.0; for(d=0; d<2; d++) for(i=0; i<NB_FEATURES; i++) q->features_lin[d][i] = 0.0; q->f = 0; return q; } // call this if you change any parameters from default void lpcnet_quant_compute_bits_per_frame(LPCNET_QUANT *q) { int i; q->bits_per_frame = q->pitch_bits + 2; for(i=0; i<q->num_stages; i++) q->bits_per_frame += log2(q->m[i]); } void lpcnet_quant_destroy(LPCNET_QUANT *q) { free(q); } // print vector debug function void pv(char s[], float v[]) { int i; if (lpcnet_verbose) { fprintf(stderr, "%s",s); for(i=0; i<NB_BANDS; i++) fprintf(stderr, "%4.2f ", v[i]); fprintf(stderr, "\n"); } } void quant_pred(float vec_out[], /* prev quant vector, and output */ float vec_in[], float pred, int num_stages, float vq[], int m[], int k) { float err[k], w[k], se, se1, se2; int i,s,ind; pv("\nvec_in: ", vec_in); pv("vec_out: ", vec_out); se1 = 0.0; for(i=0; i<k; i++) { err[i] = (vec_in[i] - pred*vec_out[i]); se1 += err[i]*err[i]; vec_out[i] = pred*vec_out[i]; w[i] = 1.0; } se1 /= k; pv("err: ", err); if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "%f\t%f\t", vec_in[0],sqrt(se1)); for(s=0; s<num_stages; s++) { ind = quantise(&vq[s*k*MAX_ENTRIES], err, w, k, m[s], &se); pv("entry: ", &vq[s+k*MAX_ENTRIES+ind*k]); se2 = 0.0; for(i=0; i<k; i++) { err[i] -= vq[s*k*MAX_ENTRIES+ind*k+i]; se2 += err[i]*err[i]; vec_out[i] += vq[s*k*MAX_ENTRIES+ind*k+i]; } se2 /= k; if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "%f\t", sqrt(se2)); if (lpcnet_verbose) fprintf(stderr, "se1: %f se2: %f s: %d/%d m[s]: %d ind: %d\n", se1, se2, s, num_stages, m[s], ind); pv("err: ", err); pv("vec_out: ",vec_out); } if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "\n"); } // mbest algorithm version void quant_pred_mbest(float vec_out[], int indexes[], float vec_in[], float pred, int num_stages, float vq[], int m[], int k, int mbest_survivors) { float err[k], w[k], se1; int i,j,s,s1,ind; struct MBEST *mbest_stage[num_stages]; int index[num_stages]; float target[k]; for(i=0; i<num_stages; i++) { mbest_stage[i] = lpcnet_mbest_create(mbest_survivors, num_stages); index[i] = 0; } /* predict based on last frame */ se1 = 0.0; for(i=0; i<k; i++) { err[i] = (vec_in[i] - pred*vec_out[i]); se1 += err[i]*err[i]; w[i] = 1.0; } se1 /= k; /* now quantise err[] using multi-stage mbest search, preserving mbest_survivors at each stage */ lpcnet_mbest_search(vq, err, w, k, m[0], mbest_stage[0], index); if (lpcnet_verbose) MBEST_PRINT("Stage 1:", mbest_stage[0]); for(s=1; s<num_stages; s++) { /* for each candidate in previous stage, try to find best vector in next stage */ for (j=0; j<mbest_survivors; j++) { /* indexes that lead us this far */ for(s1=0; s1<s; s1++) { index[s1+1] = mbest_stage[s-1]->list[j].index[s1]; } /* target is residual err[] vector given path to this candidate */ for(i=0; i<k; i++) target[i] = err[i]; for(s1=0; s1<s; s1++) { ind = index[s-s1]; if (lpcnet_verbose) fprintf(stderr, " s: %d s1: %d s-s1: %d ind: %d\n", s,s1,s-s1,ind); for(i=0; i<k; i++) { target[i] -= vq[s1*k*MAX_ENTRIES+ind*k+i]; } } pv(" target: ", target); lpcnet_mbest_search(&vq[s*k*MAX_ENTRIES], target, w, k, m[s], mbest_stage[s], index); } char str[80]; sprintf(str,"Stage %d:", s+1); if (lpcnet_verbose) MBEST_PRINT(str, mbest_stage[s]); } for(s=0; s<num_stages; s++) { indexes[s] = mbest_stage[num_stages-1]->list[0].index[num_stages-1-s]; } /* OK put it all back together using best survivor. Note we need to decode at encoder to keep record of last output for next frame's predictor */ pv("\n vec_in: ", vec_in); pv(" vec_out: ", vec_out); pv(" err: ", err); if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "%f\t%f\t", vec_in[0],sqrt(se1)); if (lpcnet_verbose) fprintf(stderr, " se1: %f\n", se1); quant_pred_output(vec_out, indexes, err, pred, num_stages, vq, k); for(i=0; i<num_stages; i++) lpcnet_mbest_destroy(mbest_stage[i]); } void quant_pred_output(float vec_out[], int indexes[], float err[], /* used for development, set to zeros in real world decode side */ float pred, int num_stages, float vq[], int k) { int s,i,ind; float se2; for(i=0; i<k; i++) vec_out[i] = pred*vec_out[i]; for(s=0; s<num_stages; s++) { ind = indexes[s]; se2 = 0.0; for(i=0; i<k; i++) { err[i] -= vq[s*k*MAX_ENTRIES+ind*k+i]; vec_out[i] += vq[s*k*MAX_ENTRIES+ind*k+i]; se2 += err[i]*err[i]; } se2 /= k; if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "%f\t", sqrt(se2)); pv(" err: ", err); if (lpcnet_verbose) fprintf(stderr, " se2: %f\n", se2); } pv(" vec_out: ",vec_out); if (lpcnet_fsv != NULL) fprintf(lpcnet_fsv, "\n"); } /*---------------------------------------------------------------------------* \ quantise Quantises vec by choosing the nearest vector in codebook cb, and returns the vector index. The squared error of the quantised vector is added to se. \*---------------------------------------------------------------------------*/ static int quantise(const float * cb, float vec[], float w[], int k, int m, float *se) /* float cb[][K]; current VQ codebook */ /* float vec[]; vector to quantise */ /* float w[]; weighting vector */ /* int k; dimension of vectors */ /* int m; size of codebook */ /* float *se; accumulated squared error */ { float e; /* current error */ long besti; /* best index so far */ float beste; /* best error so far */ long j; int i; float diff; besti = 0; beste = 1E32; for(j=0; j<m; j++) { e = 0.0; for(i=0; i<k; i++) { diff = cb[j*k+i]-vec[i]; e += powf(diff*w[i],2.0); } if (e < beste) { beste = e; besti = j; } } *se += beste; return(besti); } int pitch_encode(float pitch_feature, int pitch_bits) { assert(pitch_bits <= 8); // mapping we use as input to pembed layer, pemebed will only be trained // for these discrete values. However I think all integers will be covered, so // we may not need any special precautions here. int periods = 0.1 + 50*pitch_feature + 100; if (periods < PITCH_MIN_PERIOD) periods = PITCH_MIN_PERIOD; if (periods >= PITCH_MAX_PERIOD) periods = PITCH_MAX_PERIOD-1; // should probably add rounding here int q = (periods - PITCH_MIN_PERIOD) >> (8 - pitch_bits); return q; } float pitch_decode(int pitch_bits, int q) { int periods_ = (q << (8 - pitch_bits)) + PITCH_MIN_PERIOD; /* bit errors can push periods_ to 63*(8-6)+20 = 272 which breaks embedd layer */ if (periods_ < PITCH_MIN_PERIOD) periods_ = PITCH_MIN_PERIOD; if (periods_ >= PITCH_MAX_PERIOD) periods_ = PITCH_MAX_PERIOD-1; return ((float)periods_ - 100.0 - 0.1)/50.0; } static float pitch_gain_cb[] = {0.25, 0.25, 0.65, 0.80}; int pitch_gain_encode(float pitch_gain_feature) { // 2 bit pitch gain quantiser float w[1] = {1.0}; float se; int ind = quantise(pitch_gain_cb, &pitch_gain_feature, w, 1, 4, &se); return ind; } float pitch_gain_decode(int ind) { return pitch_gain_cb[ind]; } void pack_frame(int num_stages, int m[], int indexes[], int pitch_bits, int pitch_ind, int pitch_gain_ind, char frame[]) { int s,b,k=0,nbits; for(s=0; s<num_stages; s++) { nbits = log2(m[s]); for (b=0; b<nbits; b++) frame[k++] = (indexes[s] >> (nbits-1-b)) & 0x1; } for (b=0; b<pitch_bits; b++) frame[k++] = (pitch_ind >> (pitch_bits-1-b)) & 0x1; frame[k++] = (pitch_gain_ind >> 1) & 0x1; frame[k++] = pitch_gain_ind & 0x1; } void unpack_frame(int num_stages, int m[], int indexes[], int pitch_bits, int *pitch_ind, int *pitch_gain_ind, char frame[]) { int s,b,k=0,nbits; for(s=0; s<num_stages; s++) { nbits = log2(m[s]); indexes[s] = 0; for (b=0; b<nbits; b++) indexes[s] |= (int)frame[k++] << (nbits-1-b); } *pitch_ind = 0; for (b=0; b<pitch_bits; b++) *pitch_ind |= (int)frame[k++] << (pitch_bits-1-b); *pitch_gain_ind = ((int)frame[k]<<1) + frame[k+1]; } // Call every q->dec LPCNet frames int lpcnet_features_to_frame(LPCNET_QUANT *q, float features[], char frame[]) { int i, k = NB_BANDS; int frame_valid = 0; int indexes[MAX_STAGES]; /* convert cepstrals to dB */ for(i=0; i<NB_BANDS; i++) features[i] *= 10.0; /* optional weight on first cepstral which increases at sqrt(NB_BANDS) for every dB of speech input power. Note by doing it here, we won't be measuring SD of this step, SD results will be on weighted vector. */ features[0] *= q->weight; int pitch_ind, pitch_gain_ind; /* non-interpolated frame ----------------------------------------*/ quant_pred_mbest(q->features_quant, indexes, features, q->pred, q->num_stages, q->vq, q->m, k, q->mbest); pitch_ind = pitch_encode(features[2*NB_BANDS], q->pitch_bits); pitch_gain_ind = pitch_gain_encode(features[2*NB_BANDS+1]); pack_frame(q->num_stages, q->m, indexes, q->pitch_bits, pitch_ind, pitch_gain_ind, frame); frame_valid = 1; return frame_valid; } // Call every 10ms, supply a new frame of bits when (q->f % q->dec) == 0) void lpcnet_frame_to_features(LPCNET_QUANT *q, char frame[], float features_out[]) { int i,d; int pitch_ind, pitch_gain_ind; int indexes[MAX_STAGES]; float fract, err[NB_BANDS]; for(i=0; i<NB_FEATURES; i++) features_out[i] = 0.0; // note this is an unused ouput, just clear it to satisfy warnings for(i=0; i<NB_BANDS; i++) err[i] = 0.0; /* decoder */ if ((q->f % q->dec) == 0) { /* non-interpolated frame ----------------------------------------*/ unpack_frame(q->num_stages, q->m, indexes, q->pitch_bits, &pitch_ind, &pitch_gain_ind, frame); quant_pred_output(q->features_quant, indexes, err, q->pred, q->num_stages, q->vq, NB_BANDS); q->features_quant[2*NB_BANDS] = pitch_decode(q->pitch_bits, pitch_ind); q->features_quant[2*NB_BANDS+1] = pitch_gain_decode(pitch_gain_ind); /* update linear interpolation arrays */ for(i=0; i<NB_FEATURES; i++) { q->features_lin[0][i] = q->features_lin[1][i]; q->features_lin[1][i] = q->features_quant[i]; } /* pass frame through */ for(i=0; i<NB_BANDS; i++) { features_out[i] = q->features_lin[0][i]; } features_out[2*NB_BANDS] = q->features_lin[0][2*NB_BANDS]; features_out[2*NB_BANDS+1] = q->features_lin[0][2*NB_BANDS+1]; } else { /* interpolated frame ----------------------------------------*/ d = q->f % q-> dec; for(i=0; i<NB_FEATURES; i++) { fract = (float)d/(float)q->dec; features_out[i] = (1.0-fract)*q->features_lin[0][i] + fract*q->features_lin[1][i]; } } q->f++; features_out[0] /= q->weight; /* convert cepstrals back from dB */ for(i=0; i<NB_BANDS; i++) features_out[i] *= 1/10.0; /* need to recompute LPCs after every frame, as we have quantised, or interpolated */ lpc_from_cepstrum(&features_out[2*NB_BANDS+3], features_out); }
31.899543
127
0.544804
[ "vector" ]
b7a51217ab54e3f191026c21221ef5dd1a70e3d7
3,574
h
C
Parser/ParserWrapper.h
Bangsan/mapd-skyline
38905e9bc7c4d7297b87f1854e9615368dc7a423
[ "Apache-2.0" ]
null
null
null
Parser/ParserWrapper.h
Bangsan/mapd-skyline
38905e9bc7c4d7297b87f1854e9615368dc7a423
[ "Apache-2.0" ]
null
null
null
Parser/ParserWrapper.h
Bangsan/mapd-skyline
38905e9bc7c4d7297b87f1854e9615368dc7a423
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017 MapD Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file ParserWrapper.h * @author michael * @brief Classes used to wrap parser calls for calcite redirection * * Copyright (c) 2016 MapD Technologies, Inc. All rights reserved. **/ #ifndef PARSER_WRAPPER_H_ #define PARSER_WRAPPER_H_ #include <boost/regex.hpp> #include <string> #include <vector> #include "Shared/ConfigResolve.h" class ParserWrapper { public: // HACK: This needs to go away as calcite takes over parsing enum class DMLType : int { Insert = 0, Delete, Update, Upsert, NotDML }; ParserWrapper(std::string query_string); std::string process(std::string user, std::string passwd, std::string catalog, std::string sql_string, const bool legacy_syntax); virtual ~ParserWrapper(); bool is_select_explain = false; bool is_select_calcite_explain = false; bool is_other_explain = false; bool is_ddl = false; bool is_update_dml = false; bool is_copy = false; bool is_copy_to = false; bool is_optimize = false; std::string actual_query; DMLType getDMLType() const { return dml_type; } private: DMLType dml_type = DMLType::NotDML; static const std::vector<std::string> ddl_cmd; static const std::vector<std::string> update_dml_cmd; static const std::string explain_str; static const std::string calcite_explain_str; static const std::string optimize_str; }; enum class CalciteDMLPathSelection : int { Unsupported = 0, OnlyUpdates = 1, OnlyDeletes = 2, UpdatesAndDeletes = 3, }; inline CalciteDMLPathSelection yield_dml_path_selector() { int selector = 0; if (std::is_same<CalciteDeletePathSelector, PreprocessorTrue>::value) selector |= 0x02; if (std::is_same<CalciteUpdatePathSelector, PreprocessorTrue>::value) selector |= 0x01; return static_cast<CalciteDMLPathSelection>(selector); } inline bool is_calcite_permissable_dml(ParserWrapper const& pw, bool read_only_mode) { if (read_only_mode) return !pw.is_update_dml; // If we're read-only rejected, no DML is permissable switch (yield_dml_path_selector()) { case CalciteDMLPathSelection::OnlyUpdates: return !pw.is_update_dml || (pw.getDMLType() == ParserWrapper::DMLType::Update); case CalciteDMLPathSelection::OnlyDeletes: return !pw.is_update_dml || (pw.getDMLType() == ParserWrapper::DMLType::Delete); case CalciteDMLPathSelection::UpdatesAndDeletes: return !pw.is_update_dml || (pw.getDMLType() == ParserWrapper::DMLType::Delete) || (pw.getDMLType() == ParserWrapper::DMLType::Update); case CalciteDMLPathSelection::Unsupported: default: return false; } } inline bool is_calcite_path_permissable(ParserWrapper const& pw, bool read_only_mode = false) { return (!pw.is_ddl && !pw.is_optimize && is_calcite_permissable_dml(pw, read_only_mode) && !pw.is_other_explain); } #endif // PARSERWRAPPER_H_
33.092593
88
0.707051
[ "vector" ]
b7a6bef86773f63d4150430dcb7bf10e608b02fe
9,626
c
C
user-contributed/lblOLD/xview/segal.new/segal.c
mikelandy/HIPS
fb5440573848cd22d55771484e3c036b6007f780
[ "MIT" ]
null
null
null
user-contributed/lblOLD/xview/segal.new/segal.c
mikelandy/HIPS
fb5440573848cd22d55771484e3c036b6007f780
[ "MIT" ]
null
null
null
user-contributed/lblOLD/xview/segal.new/segal.c
mikelandy/HIPS
fb5440573848cd22d55771484e3c036b6007f780
[ "MIT" ]
null
null
null
/* * segal.c - Contains main() for project segal * This file was generated by `gxv'. * * Various other initialization code has been added. * * -Bryan Skene */ #include "common.h" #include "file_ui.h" #include "filter_ui.h" #include "image_reg_ui.h" #include "mask_grow_ui.h" #include "mask_log_ui.h" #include "paint_ui.h" #include "preferences_ui.h" #include "threshold_ui.h" #include "view_ui.h" #ifdef MAIN #include <stdio.h> #include <sys/param.h> #include <sys/types.h> #include <xview/xview.h> #include <xview/panel.h> #include <xview/textsw.h> #include <xview/xv_xrect.h> #include "list_ui.h" Attr_attribute INSTANCE; /* * External variable declarations. */ view_win_objects *View_win; view_pop_timer_objects *View_pop_timer; file_pop_load_image_objects *File_pop_load_image; file_pop_load_mask_objects *File_pop_load_mask; file_pop_new_mask_objects *File_pop_new_mask; file_pop_save_as_objects *File_pop_save_as; file_pop_save_image_objects *File_pop_save_image; filter_pop_filter_objects *Filter_pop_filter; image_reg_pop_image_reg_objects *Image_reg_pop_image_reg; image_reg_pop_ref_frame_objects *Image_reg_pop_ref_frame; list_pop_list_objects *List_pop_list; mask_grow_pop_mask_grow_objects *Mask_grow_pop_mask_grow; mask_grow_pop_options_objects *Mask_grow_pop_options; mask_log_pop_mask_log_objects *Mask_log_pop_mask_log; mask_log_pop_options_objects *Mask_log_pop_options; paint_win_paint_objects *Paint_win_paint; preferences_pop_preferences_display_objects *Preferences_pop_preferences_display; threshold_pop_threshold_objects *Threshold_pop_threshold; paint_pop_brush_objects *Paint_pop_brush; void main(argc, argv) int argc; char **argv; { void create_cursors(); void grow_setup(); void info_init(); void parse_args(); void load_image_header(); void load_mask(); void recall_list(); void new_mask_proc(); void save_mask_as(); void save_image_as(); /* save in globals for HIPS header */ ac = argc; av = argv; parse_args(argc, argv); /* Initialize XView */ xv_init(XV_INIT_ARGC_PTR_ARGV, &argc, argv, NULL); INSTANCE = xv_unique_key(); /* initialize global variables */ info_init(); /* ***IMPORTANT*** init routine in storage.c */ /* * Initialize user interface components. * Do NOT edit the object initializations by hand. */ View_win = view_win_objects_initialize(NULL, NULL); File_pop_load_image = file_pop_load_image_objects_initialize(NULL, View_win->win); File_pop_load_mask = file_pop_load_mask_objects_initialize(NULL, View_win->win); File_pop_new_mask = file_pop_new_mask_objects_initialize(NULL, View_win->win); File_pop_save_as = file_pop_save_as_objects_initialize(NULL, View_win->win); File_pop_save_image = file_pop_save_image_objects_initialize(NULL, View_win->win); Filter_pop_filter = filter_pop_filter_objects_initialize(NULL, View_win->win); Image_reg_pop_image_reg = image_reg_pop_image_reg_objects_initialize(NULL, View_win->win); Image_reg_pop_ref_frame = image_reg_pop_ref_frame_objects_initialize(NULL, View_win->win); List_pop_list = list_pop_list_objects_initialize(NULL, View_win->win); Mask_grow_pop_mask_grow = mask_grow_pop_mask_grow_objects_initialize(NULL, View_win->win); Mask_grow_pop_options = mask_grow_pop_options_objects_initialize(NULL, View_win->win); Mask_log_pop_mask_log = mask_log_pop_mask_log_objects_initialize(NULL, View_win->win); Mask_log_pop_options = mask_log_pop_options_objects_initialize(NULL, View_win->win); Paint_win_paint = paint_win_paint_objects_initialize(NULL, View_win->win); Paint_win_paint = paint_win_paint_objects_initialize(NULL, View_win->win); Paint_pop_brush = paint_pop_brush_objects_initialize(NULL, Paint_win_paint->win_paint); Preferences_pop_preferences_display = preferences_pop_preferences_display_objects_initialize(NULL, View_win->win); View_pop_timer = view_pop_timer_objects_initialize(NULL, View_win->win); Threshold_pop_threshold = threshold_pop_threshold_objects_initialize(NULL, NULL); /* get global X window stuff */ display = (Display *) xv_get(View_win->win, XV_DISPLAY, NULL); screen = DefaultScreen(display); winv = DefaultVisual(display, screen); winv_info = (XVisualInfo *) malloc(sizeof(XVisualInfo)); if((int) XMatchVisualInfo(display, screen, XDisplayPlanes(display, screen), PseudoColor, winv_info) == 0) { fprintf(stderr, "unable to find correct visual \n"); exit(0); } if (DisplayPlanes(display, screen) == 1) { fprintf(stderr, "This program requires an 8-bit color monitor \n"); exit(0); } gc = DefaultGC(display, screen); XSetForeground(display, gc, XWhitePixel(display, screen)); watch_cursor = XCreateFontCursor(display, XC_watch); create_cursors(); /* Allocate our standard colors to start with */ cmap_init(); /*** initialize user interface components ***/ /* set text input fields to call procs on carraige-return */ (void) xv_set(File_pop_load_image->text_image_fname, PANEL_VALUE, in_image, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, load_image_header, NULL); (void) xv_set(File_pop_load_mask->text_mask_fname, PANEL_VALUE, in_mask, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, load_mask, NULL); (void) xv_set(List_pop_list->text_l_fname, PANEL_VALUE, in_list, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, recall_list, NULL); (void) xv_set(File_pop_new_mask->text_new_fname, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, new_mask_proc, NULL); (void) xv_set(File_pop_save_image->text_i_save_fname, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, save_image_as, NULL); (void) xv_set(File_pop_save_as->text_save_fname, PANEL_NOTIFY_LEVEL, PANEL_SPECIFIED, PANEL_NOTIFY_PROC, save_mask_as, NULL); /* The following xv_set does 2 things: getwd returns and strcopies */ (void) xv_set(File_pop_load_image->text_image_dname, PANEL_VALUE, getwd(img.dname), NULL); (void) xv_set(File_pop_save_image->text_i_save_dname, PANEL_VALUE, img.dname, NULL); (void) xv_set(File_pop_load_mask->text_mask_dname, PANEL_VALUE, img.dname, NULL); (void) xv_set(File_pop_new_mask->text_new_dname, PANEL_VALUE, img.dname, NULL); /* set XID's */ win[WIN_VX].xid = (XID) xv_get(canvas_paint_window( View_win->canv_x), XV_XID); win[WIN_VY].xid = (XID) xv_get(canvas_paint_window( View_win->canv_y), XV_XID); win[WIN_VZ].xid = (XID) xv_get(canvas_paint_window( View_win->canv_z), XV_XID); win[WIN_PAINT].xid = (XID) xv_get(canvas_paint_window( Paint_win_paint->canvas), XV_XID); win[WIN_REF].xid = (XID) xv_get(canvas_paint_window( Image_reg_pop_ref_frame->canvas), XV_XID); threshold.xid = (XID) xv_get(canvas_paint_window( Threshold_pop_threshold->canvas), XV_XID); timer.xid = (XID) xv_get(canvas_paint_window( View_pop_timer->canv_timer), XV_XID); /* * Turn control over to XView. */ xv_main_loop(View_win->win); exit(0); } #endif /***********************************************************/ void parse_args(argc, argv) int argc; char *argv[]; { void usageterm(); in_image = in_mask = NULL; verbose = 0; overlay_hue = 170; /* default (dark greenish) */ /* Interpret options */ while (--argc > 0 && (*++argv)[0] == '-') { char *s; for (s = argv[0] + 1; *s; s++) switch (*s) { case 'i': if (argc < 2) usageterm(); in_image = *++argv; fprintf(stderr, " using image file: %s\n", in_image); argc--; break; case 'l': /* File containing image + list of masks */ if (argc < 2) usageterm(); in_list = *++argv; fprintf(stderr, " using list file: %s\n", in_list); argc--; break; case 'm': if (argc < 2) usageterm(); in_mask = *++argv; fprintf(stderr, " using mask file: %s\n", in_mask); argc--; break; case 'c': if (argc < 2) usageterm(); sscanf(*++argv, "%d", &overlay_hue); fprintf(stderr, " overlay hue set to %d \n", overlay_hue); argc--; break; case 'v': verbose++; break; case 'h': usageterm(); break; default: usageterm(); break; } } /* while */ if (overlay_hue < 0 || overlay_hue > 360) { fprintf(stderr, " Error: color value (hue) must be between 0 and 360. \n"); exit(0); } } /******************************************************/ void usageterm() { fprintf(stderr, "Usage: segal [-i image][-m mask] [-v] [-c NN][-h][-help] \n"); fprintf(stderr, " [-i HIPS file] load specified image file\n"); fprintf(stderr, " [-m HIPS file] load specified mask file\n"); fprintf(stderr, " [-l list_file] load list_file information\n"); fprintf(stderr, " [-v] verbose mode \n"); fprintf(stderr, " [-c NN] hue (0 to 360) for overlay blend color (default = 170)\n"); fprintf(stderr, " [-h] this list \n"); fprintf(stderr, " [-help] list of window attribute help \n\n"); exit(0); }
33.307958
115
0.669229
[ "object" ]
b7afa15b267dea8ad29e7862be70a35e6e337869
8,471
h
C
HTHttp/HTHttp/Pods/Headers/Public/HTNetworking/RestKit/Network/RKPathMatcher.h
NEYouFan/HTNetworking
c94ea7ea95b193c0d42f58a4368ca1a1e7076f1a
[ "Apache-2.0" ]
14
2016-04-28T04:50:40.000Z
2018-01-05T03:07:07.000Z
HTHttp/HTHttp/Pods/Headers/Public/HTNetworking/RestKit/Network/RKPathMatcher.h
NEYouFan/HTNetworking
c94ea7ea95b193c0d42f58a4368ca1a1e7076f1a
[ "Apache-2.0" ]
1
2016-06-06T03:11:26.000Z
2016-06-06T03:11:26.000Z
HTHttp/HTHttp/Pods/Headers/Public/HTNetworking/RestKit/Network/RKPathMatcher.h
NEYouFan/HTNetworking
c94ea7ea95b193c0d42f58a4368ca1a1e7076f1a
[ "Apache-2.0" ]
2
2017-03-09T03:34:17.000Z
2018-06-22T01:44:54.000Z
// // RKPathMatcher.h // RestKit // // Created by Greg Combs on 9/2/11. // Copyright (c) 2009-2012 RestKit. 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. // #import <Foundation/Foundation.h> @class SOCPattern; /** Convenience method for generating a path against the properties of an object. Takes an `NSString` with property names prefixed with a colon and interpolates the values of the properties specified and returns the generated path. For example, given an `article` object with an `articleID` property whose value is `@12345`, `RKPathFromPatternWithObject(@"articles/:articleID", article)` would return `@"articles/12345"`. This functionality is the basis for path generation in the `RKRouter` class. @param pathPattern An `SOCPattern` string containing zero or more colon-prefixed property names. @param object The object to interpolate the properties against @return A new `NSString` object with the values of the given object interpolated for the colon-prefixed properties name in the given pattern string. @see `RKPathMatcher` @see `SOCPattern` */ NSString *RKPathFromPatternWithObject(NSString *pathPattern, id object); /** The `RKPathMatcher` class performs pattern matching and parameter parsing of strings, typically representing the path portion of an `NSURL` object. It provides much of the necessary tools to map a given path to local objects (the inverse of RKRouter's function). This makes it easier to implement the `RKManagedObjectCaching` protocol and generate `NSFetchRequest` objects from a given path. There are two means of instantiating and using a matcher object in order to provide more flexibility in implementations, and to improve efficiency by eliminating repetitive and costly pattern initializations. @see `RKManagedObjectCaching` @see `RKPathFromPatternWithObject` @see `RKRouter` */ @interface RKPathMatcher : NSObject <NSCopying> ///--------------------------------- /// @name Matching Paths to Patterns ///--------------------------------- /** Creates a path match object starting from a path string. This method should be followed by `matchesPattern:tokenizeQueryStrings:parsedArguments:` @param pathString The string to evaluate and parse, such as `/districts/tx/upper/?apikey=GC5512354` @return An instantiated `RKPathMatcher` without an established pattern. */ + (instancetype)pathMatcherWithPath:(NSString *)pathString; /** Determines if the path string matches the provided pattern, and yields a dictionary with the resulting matched key/value pairs. Use of this method should be preceded by `pathMatcherWithPath:` Pattern strings should include encoded parameter keys, delimited by a single colon at the beginning of the key name. *NOTE 1 *- Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be separated by at least one unmapped character. For instance, `/:key1:key2:key3/` is invalid, whereas `/:key1/:key2/:key3/` is acceptable. *NOTE 2 *- The pattern matcher supports KVM, so `:key1.otherKey` normally resolves as it would in any other KVM situation, ... otherKey is a sub-key on a the object represented by key1. This presents problems in circumstances where you might want to build a pattern like /:filename.json, where the dot isn't intended as a sub-key on the filename, but rather part of the json static string. In these instances, you need to escape the dot with two backslashes, like so: /:filename\\.json @param patternString The pattern to use for evaluating, such as `/:entityName/:stateID/:chamber/` @param shouldTokenize If YES, any query parameters will be tokenized and inserted into the parsed argument dictionary. @param arguments A pointer to a dictionary that contains the key/values from the pattern (and parameter) matching. @return A boolean value indicating if the path string successfully matched the pattern. */ - (BOOL)matchesPattern:(NSString *)patternString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments; ///--------------------------------- /// @name Matching Patterns to Paths ///--------------------------------- /** Creates a path matcher object starting from a pattern string. This method should be followed by `matchesPath:tokenizeQueryStrings:parsedArguments:`. Patterns should include encoded parameter keys, delimited by a single colon at the beginning of the key name. *NOTE 1 *- Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be separated by at least one unmapped character. For instance, `/:key1:key2:key3/` is invalid, whereas `/:key1/:key2/:key3/` is acceptable. *NOTE 2 *- The pattern matcher supports KVM, so `:key1.otherKey` normally resolves as it would in any other KVM situation, ... otherKey is a sub-key on a the object represented by key1. This presents problems in circumstances where you might want to build a pattern like `/:filename.json`, where the dot isn't intended as a sub-key on the filename, but rather part of the json static string. In these instances, you need to escape the dot with two backslashes, like so: `/:filename\\.json` @param patternString The pattern to use for evaluating, such as `/:entityName/:stateID/:chamber/` @return An instantiated `RKPathMatcher` with an established pattern. */ + (instancetype)pathMatcherWithPattern:(NSString *)patternString; /** Determines if the given path string matches a pattern, and yields a dictionary with the resulting matched key/value pairs. Use of this method should be preceded by `pathMatcherWithPattern:`. @param pathString The string to evaluate and parse, such as `/districts/tx/upper/?apikey=GC5512354` @param shouldTokenize If YES, any query parameters will be tokenized and inserted into the parsed argument dictionary. @param arguments A pointer to a dictionary that contains the key/values from the pattern (and parameter) matching. @return A boolean value indicating if the path string successfully matched the pattern. */ - (BOOL)matchesPath:(NSString *)pathString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments; ///---------------------------------- /// @name Creating Paths from Objects ///---------------------------------- /** Generates a path by interpolating the properties of the 'object' argument, assuming the existence of a previously specified pattern established via `pathMatcherWithPattern:`. Otherwise, this method is identical in function to `RKPathFromPatternWithObject` (in fact it is a shortcut for this method). For example, given an 'article' object with an 'articleID' property value of 12345 and a code of "This/That"... RKPathMatcher *matcher = [RKPathMatcher pathMatcherWithPattern:@"/articles/:articleID/:code"]; NSString *path = [matcher pathFromObject:article addingEscapes:YES interpolatedParameters:nil]; ... will produce a 'path' containing the string `@"/articles/12345/This%2FThat"` @param object The object containing the properties to interpolate. @param addEscapes Conditionally add percent escapes to the interpolated property values @param interpolatedParameters On input, a pointer for a dictionary object. When the path pattern of the receiver is interpolated, this pointer is set to a new dictionary object in which the keys correspond to the named parameters within the path pattern and the values are taken from the corresponding keypaths of the interpolated object . @return A string with the object's interpolated property values inserted into the receiver's established pattern. @see `RKRouter` */ - (NSString *)pathFromObject:(id)object addingEscapes:(BOOL)addEscapes interpolatedParameters:(NSDictionary **)interpolatedParameters; ///------------------------------------------- /// @name Accessing Tokenized Query Parameters ///------------------------------------------- @property (copy, readonly) NSDictionary *queryParameters; @end
63.691729
603
0.752213
[ "object" ]
b7b69512a0957674e009f42ccc04711daa21f848
956
h
C
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/CyanTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/CyanTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/CyanTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "PassiveTargetData.h" #include "../Misc/CyanDirection.h" #include "CyanTargetData.generated.h" UCLASS(BlueprintType, meta = (BlueprintSpawnableComponent), NonTransient) class SPEEGYPT_API UCyanTargetData : public UPassiveTargetData { GENERATED_BODY() public: UPROPERTY(VisibleAnywhere, BlueprintReadOnly) bool bApplyForce = false; UPROPERTY(VisibleAnywhere, BlueprintReadWrite) float ForceMagnitude = 0.0f; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) FVector CurrentDirection; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) TSet<UCyanDirection*> ForceDirections; FORCEINLINE void UpdateComponentDirection() { FVector DirectionSum = FVector(0, 0, 0); for (auto& Vector : ForceDirections) { DirectionSum += Vector->Direction; } DirectionSum.Normalize(); CurrentDirection = DirectionSum; }; };
23.317073
78
0.780335
[ "vector" ]
b7b849c8a1dae56222168e9f2d5a9a287598952e
1,736
h
C
igl/embree/line_mesh_intersection.h
danatzmi/Animation-Assignment2
7461b57ad51d61814cd1f467863a431c7c08d84f
[ "Apache-2.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
igl/embree/line_mesh_intersection.h
danatzmi/Animation-Assignment2
7461b57ad51d61814cd1f467863a431c7c08d84f
[ "Apache-2.0" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
igl/embree/line_mesh_intersection.h
danatzmi/Animation-Assignment2
7461b57ad51d61814cd1f467863a431c7c08d84f
[ "Apache-2.0" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Daniele Panozzo <daniele.panozzo@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_EMBREE_LINE_MESH_INTERSECTION_H #define IGL_EMBREE_LINE_MESH_INTERSECTION_H #include <igl/igl_inline.h> #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> namespace igl { namespace embree { // Project the point cloud V_source onto the triangle mesh // V_target,F_target. // A ray is casted for every vertex in the direction specified by // N_source and its opposite. // // Input: // V_source: #Vx3 Vertices of the source mesh // N_source: #Vx3 Normals of the point cloud // V_target: #V2x3 Vertices of the target mesh // F_target: #F2x3 Faces of the target mesh // // Output: // #Vx3 matrix of baricentric coordinate. Each row corresponds to // a vertex of the projected mesh and it has the following format: // id b1 b2. id is the id of a face of the source mesh. b1 and b2 are // the barycentric coordinates wrt the first two edges of the triangle // To convert to standard global coordinates, see barycentric_to_global.h template <typename ScalarMatrix, typename IndexMatrix> IGL_INLINE ScalarMatrix line_mesh_intersection ( const ScalarMatrix & V_source, const ScalarMatrix & N_source, const ScalarMatrix & V_target, const IndexMatrix & F_target ); } } #ifndef IGL_STATIC_LIBRARY # include "line_mesh_intersection.cpp" #endif #endif
33.384615
79
0.710253
[ "mesh", "geometry", "vector" ]
b7bc5c6e82c5aa04d2b4261c1555dafcccbed99c
4,793
h
C
Plugins/DlgSystem/Source/DlgSystem/Public/Nodes/DlgNode_Speech.h
denfrost/DlgSystem
e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23
[ "MIT" ]
null
null
null
Plugins/DlgSystem/Source/DlgSystem/Public/Nodes/DlgNode_Speech.h
denfrost/DlgSystem
e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23
[ "MIT" ]
null
null
null
Plugins/DlgSystem/Source/DlgSystem/Public/Nodes/DlgNode_Speech.h
denfrost/DlgSystem
e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23
[ "MIT" ]
null
null
null
// Copyright 2017-2018 Csaba Molnar, Daniel Butum #pragma once #include "DlgNode.h" #include "DlgTextArgument.h" #include "DlgNode_Speech.generated.h" class USoundWave; class UDialogueWave; struct FDlgTextArgument; /** * Normal dialogue node - someone says something. */ UCLASS(BlueprintType) class DLGSYSTEM_API UDlgNode_Speech : public UDlgNode { GENERATED_BODY() public: // Begin UObject Interface. FString GetDesc() override { if (bIsVirtualParent) { return TEXT("Virtual Parent Node. Acts like a fake parent (proxy) to other child nodes. (aka makes it get the grandchildren)\nOn revaluate children, it does not get the direct children but the children of the first satisfied direct child node (grandchildren).\nIt should have at least one satisified child otherwise the Dialogue is terminated."); } return TEXT("Normal dialogue node - someone says something."); } #if WITH_EDITOR /** * Called when a property on this object has been modified externally * * @param PropertyChangedEvent the property that was modified */ virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif // Begin UDlgNode Interface. bool HandleNodeEnter(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> NodesEnteredWithThisStep) override; bool ReevaluateChildren(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> AlreadyEvaluated) override; void GetAssociatedParticipants(TArray<FName>& OutArray) const override; const TArray<FDlgTextArgument>& GetTextArguments() const { return TextArguments; }; // Getters: const FText& GetNodeText() const override { return (TextArguments.Num() > 0 && !ConstructedText.IsEmpty()) ? ConstructedText : Text; } const FText& GetRawNodeText() const override { return Text; } USoundWave* GetNodeVoiceSoundWave() const override { return VoiceSoundWave; } UDialogueWave* GetNodeVoiceDialogueWave() const override { return VoiceDialogueWave; } FName GetSpeakerState() const override { return SpeakerState; } void AddSpeakerStates(TSet<FName>& States) const { States.Add(SpeakerState); } #if WITH_EDITOR FString GetNodeTypeString() const override { return bIsVirtualParent ? TEXT("Virtual Parent") : TEXT("Speech"); } #endif // Begin own functions. /** Is this node a virtual parent? */ virtual bool IsVirtualParent() const { return bIsVirtualParent; } /** Sets the virtual parent status */ virtual void SetIsVirtualParent(bool bValue) { bIsVirtualParent = bValue; } /** Sets the Text of the Node. */ virtual void SetNodeText(const FText& InText) { Text = InText; } /** Helper functions to get the names of some properties. Used by the DlgSystemEditor module. */ static FName GetMemberNameText() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, Text); } static FName GetMemberNameTextArguments() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, TextArguments); } static FName GetMemberNameVoiceSoundWave() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, VoiceSoundWave); } static FName GetMemberNameVoiceDialogueWave() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, VoiceDialogueWave); } static FName GetMemberNameSpeakerState() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, SpeakerState); } static FName GetMemberNameIsVirtualParent() { return GET_MEMBER_NAME_CHECKED(UDlgNode_Speech, bIsVirtualParent); } protected: /** Text that will appear when this node participant name speaks to someone else. */ UPROPERTY(EditAnywhere, Category = DialogueNodeData, Meta = (MultiLine = true)) FText Text; UPROPERTY(EditAnywhere, EditFixedSize, Category = DialogueNodeData) TArray<FDlgTextArgument> TextArguments; /** Voice attached to this node. The Sound Wave variant. */ UPROPERTY(EditAnywhere, Category = DialogueNodeData, Meta = (DlgSaveOnlyReference)) USoundWave* VoiceSoundWave; /** Voice attached to this node. The Dialogue Wave variant. Only the first wave from the dialogue context array should be used. */ UPROPERTY(EditAnywhere, Category = DialogueNodeData, Meta = (DlgSaveOnlyReference)) UDialogueWave* VoiceDialogueWave; /** State of the speaker attached to this node. Passed to the GetParticipantIcon function. */ UPROPERTY(EditAnywhere, Category = DialogueNodeData) FName SpeakerState; /** * Make this Node act like a fake parent (proxy) to other child nodes. (aka makes it get the grandchildren) * On revaluate children, it does not get the direct children but the children of the first satisfied direct child node (grandchildren). * It should have at least one satisfied child otherwise the Dialogue is terminated. */ UPROPERTY(EditAnywhere, Category = DialogueNodeData) bool bIsVirtualParent = false; /** Constructed at runtime from the original text and the arguments if there is any. */ FText ConstructedText; };
43.572727
349
0.779261
[ "object" ]
b7c1d507b9af99b112e571583282cd6ed723cde9
4,296
h
C
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Component/EntityId.h> #include <AzCore/Outcome/Outcome.h> #include <AzCore/std/string/string.h> #include <AzCore/std/string/string_view.h> #include <stdarg.h> namespace ScriptCanvas { class Graph; class Node; class Slot; namespace Grammar { struct Source; } namespace Translation { class Writer; struct Configuration; AZStd::string EntityIdToU64String(const AZ::EntityId& entityId); AZStd::string EntityIdValueToString(const AZ::EntityId& entityId, const Configuration& config); AZStd::string_view GetCopyright(); AZStd::string_view GetAutoNativeNamespace(); AZStd::string_view GetDoNotModifyCommentText(); AZ::Outcome<void, AZStd::string> SaveDotCPP(const Grammar::Source& source, AZStd::string_view dotCPP); AZ::Outcome<void, AZStd::string> SaveDotH(const Grammar::Source& source, AZStd::string_view dotH); AZ::Outcome<void, AZStd::string> SaveDotLua(const Grammar::Source& source, AZStd::string_view dotLua); class Writer { friend class ScopedIndent; public: Writer(); void Indent(size_t tabs = 1); const AZStd::string& GetOutput() const; size_t GetIndent() const; AZStd::string&& MoveOutput(); void Outdent(size_t tabs = 1); void SetIndent(size_t tabs); // in general, don't include newlines, as it will violate the tab policy void Write(const AZStd::string_view& stringView); // in general, don't include newlines, as it will violate the tab policy void Write(const char* format, ...); void WriteIndent(); // in general, don't include newlines, as it will violate the tab policy inline void WriteIndented(const AZStd::string_view& stringView) { WriteIndent(); Write(stringView); } // in general, don't include newlines, as it will violate the tab policy inline void WriteIndented(const char* format, ...) { va_list vargs; va_start(vargs, format); WriteIndent(); m_output.append(AZStd::string::format_arg(format, vargs)); va_end(vargs); } // in general, don't include newlines, as it will violate the tab policy void WriteLine(const AZStd::string_view& stringView); // in general, don't include newlines, as it will violate the tab policy void WriteLine(const char* format, ...); // in general, don't include newlines, as it will violate the tab policy inline void WriteLineIndented(const AZStd::string_view& stringView) { WriteIndent(); WriteLine(stringView); } // in general, don't include newlines, as it will violate the tab policy inline void WriteLineIndented(const char* format, ...) { va_list vargs; va_start(vargs, format); WriteIndent(); m_output.append(AZStd::string::format_arg(format, vargs)); WriteNewLine(); va_end(vargs); } // in general, don't include newlines, as it will violate the tab policy void WriteNewLine(); void WriteSpace(); private: static const size_t k_initialReservationSize = 2048; AZStd::string m_output; size_t m_indent = 0; }; class ScopedIndent { public: ScopedIndent(Writer& writer) : m_writer(writer) { m_writer.Indent(); } ~ScopedIndent() { m_writer.Outdent(); } private: Writer& m_writer; }; } }
28.450331
110
0.566806
[ "3d" ]
b7c473e6abd980a64fedc51a616ccda20ffbabab
275,109
c
C
xun/xnu-6153.81.5/bsd/netkey/key.c
L-Zheng/AppleOpenSource
65fac74ce17dc97404f1aeb8c24625fe82b7d142
[ "MIT" ]
null
null
null
xun/xnu-6153.81.5/bsd/netkey/key.c
L-Zheng/AppleOpenSource
65fac74ce17dc97404f1aeb8c24625fe82b7d142
[ "MIT" ]
null
null
null
xun/xnu-6153.81.5/bsd/netkey/key.c
L-Zheng/AppleOpenSource
65fac74ce17dc97404f1aeb8c24625fe82b7d142
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008-2016 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* $FreeBSD: src/sys/netkey/key.c,v 1.16.2.13 2002/07/24 18:17:40 ume Exp $ */ /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This code is referd to RFC 2367 */ #include <machine/endian.h> #include <sys/types.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/mbuf.h> #include <sys/domain.h> #include <sys/protosw.h> #include <sys/malloc.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/sysctl.h> #include <sys/errno.h> #include <sys/proc.h> #include <sys/queue.h> #include <sys/syslog.h> #include <sys/mcache.h> #include <kern/locks.h> #include <net/if.h> #include <net/route.h> #include <net/raw_cb.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/in_var.h> #if INET6 #include <netinet/ip6.h> #include <netinet6/in6_var.h> #include <netinet6/ip6_var.h> #endif /* INET6 */ #include <net/pfkeyv2.h> #include <netkey/keydb.h> #include <netkey/key.h> #include <netkey/keysock.h> #include <netkey/key_debug.h> #include <stdarg.h> #include <libkern/crypto/rand.h> #include <netinet6/ipsec.h> #if INET6 #include <netinet6/ipsec6.h> #endif #include <netinet6/ah.h> #if INET6 #include <netinet6/ah6.h> #endif #if IPSEC_ESP #include <netinet6/esp.h> #if INET6 #include <netinet6/esp6.h> #endif #endif /* randomness */ #include <sys/random.h> #include <net/net_osdep.h> #define FULLMASK 0xff lck_grp_t *sadb_mutex_grp; lck_grp_attr_t *sadb_mutex_grp_attr; lck_attr_t *sadb_mutex_attr; decl_lck_mtx_data(, sadb_mutex_data); lck_mtx_t *sadb_mutex = &sadb_mutex_data; lck_grp_t *pfkey_stat_mutex_grp; lck_grp_attr_t *pfkey_stat_mutex_grp_attr; lck_attr_t *pfkey_stat_mutex_attr; decl_lck_mtx_data(, pfkey_stat_mutex_data); lck_mtx_t *pfkey_stat_mutex = &pfkey_stat_mutex_data; /* * Note on SA reference counting: * - SAs that are not in DEAD state will have (total external reference + 1) * following value in reference count field. they cannot be freed and are * referenced from SA header. * - SAs that are in DEAD state will have (total external reference) * in reference count field. they are ready to be freed. reference from * SA header will be removed in key_delsav(), when the reference count * field hits 0 (= no external reference other than from SA header. */ u_int32_t key_debug_level = 0; //### our sysctl is not dynamic static int key_timehandler_running = 0; static u_int key_spi_trycnt = 1000; static u_int32_t key_spi_minval = 0x100; static u_int32_t key_spi_maxval = 0x0fffffff; /* XXX */ static u_int32_t policy_id = 0; static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/ static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/ static int key_blockacq_count = 10; /* counter for blocking SADB_ACQUIRE.*/ static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/ static int key_preferred_oldsa = 0; /* preferred old sa rather than new sa.*/ __private_extern__ int natt_keepalive_interval = 20; /* interval between natt keepalives.*/ __private_extern__ int ipsec_policy_count = 0; static int ipsec_sav_count = 0; static u_int32_t acq_seq = 0; static int key_tick_init_random = 0; static u_int64_t up_time = 0; __private_extern__ u_int64_t natt_now = 0; static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX]; /* SPD */ static LIST_HEAD(_sahtree, secashead) sahtree; /* SAD */ static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1]; /* registed list */ #define SPIHASHSIZE 128 #define SPIHASH(x) (((x) ^ ((x) >> 16)) % SPIHASHSIZE) static LIST_HEAD(_spihash, secasvar) spihash[SPIHASHSIZE]; #ifndef IPSEC_NONBLOCK_ACQUIRE static LIST_HEAD(_acqtree, secacq) acqtree; /* acquiring list */ #endif static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */ struct key_cb key_cb; /* search order for SAs */ static const u_int saorder_state_valid_prefer_old[] = { SADB_SASTATE_DYING, SADB_SASTATE_MATURE, }; static const u_int saorder_state_valid_prefer_new[] = { SADB_SASTATE_MATURE, SADB_SASTATE_DYING, }; static const u_int saorder_state_alive[] = { /* except DEAD */ SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL }; static const u_int saorder_state_any[] = { SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD }; static const int minsize[] = { sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */ sizeof(struct sadb_sa), /* SADB_EXT_SA */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */ sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */ sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */ sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */ sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */ sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */ sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */ sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */ sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */ sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */ sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */ sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */ sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */ 0, /* SADB_X_EXT_KMPRIVATE */ sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */ sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */ sizeof(struct sadb_session_id), /* SADB_EXT_SESSION_ID */ sizeof(struct sadb_sastat), /* SADB_EXT_SASTAT */ sizeof(struct sadb_x_ipsecif), /* SADB_X_EXT_IPSECIF */ sizeof(struct sadb_address), /* SADB_X_EXT_ADDR_RANGE_SRC_START */ sizeof(struct sadb_address), /* SADB_X_EXT_ADDR_RANGE_SRC_END */ sizeof(struct sadb_address), /* SADB_X_EXT_ADDR_RANGE_DST_START */ sizeof(struct sadb_address), /* SADB_X_EXT_ADDR_RANGE_DST_END */ sizeof(struct sadb_address), /* SADB_EXT_MIGRATE_ADDRESS_SRC */ sizeof(struct sadb_address), /* SADB_EXT_MIGRATE_ADDRESS_DST */ sizeof(struct sadb_x_ipsecif), /* SADB_X_EXT_MIGRATE_IPSECIF */ }; static const int maxsize[] = { sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */ sizeof(struct sadb_sa_2), /* SADB_EXT_SA */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */ sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */ 0, /* SADB_EXT_ADDRESS_SRC */ 0, /* SADB_EXT_ADDRESS_DST */ 0, /* SADB_EXT_ADDRESS_PROXY */ 0, /* SADB_EXT_KEY_AUTH */ 0, /* SADB_EXT_KEY_ENCRYPT */ 0, /* SADB_EXT_IDENTITY_SRC */ 0, /* SADB_EXT_IDENTITY_DST */ 0, /* SADB_EXT_SENSITIVITY */ 0, /* SADB_EXT_PROPOSAL */ 0, /* SADB_EXT_SUPPORTED_AUTH */ 0, /* SADB_EXT_SUPPORTED_ENCRYPT */ sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */ 0, /* SADB_X_EXT_KMPRIVATE */ 0, /* SADB_X_EXT_POLICY */ sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */ 0, /* SADB_EXT_SESSION_ID */ 0, /* SADB_EXT_SASTAT */ sizeof(struct sadb_x_ipsecif), /* SADB_X_EXT_IPSECIF */ 0, /* SADB_X_EXT_ADDR_RANGE_SRC_START */ 0, /* SADB_X_EXT_ADDR_RANGE_SRC_END */ 0, /* SADB_X_EXT_ADDR_RANGE_DST_START */ 0, /* SADB_X_EXT_ADDR_RANGE_DST_END */ 0, /* SADB_EXT_MIGRATE_ADDRESS_SRC */ 0, /* SADB_EXT_MIGRATE_ADDRESS_DST */ sizeof(struct sadb_x_ipsecif), /* SADB_X_EXT_MIGRATE_IPSECIF */ }; static int ipsec_esp_keymin = 256; static int ipsec_esp_auth = 0; static int ipsec_ah_keymin = 128; SYSCTL_DECL(_net_key); /* Thread safe: no accumulated state */ SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_debug_level, 0, ""); /* max count of trial for the decision of spi value */ SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_spi_trycnt, 0, ""); /* minimum spi value to allocate automatically. */ SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_spi_minval, 0, ""); /* maximun spi value to allocate automatically. */ SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_spi_maxval, 0, ""); /* interval to initialize randseed */ SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_int_random, 0, ""); /* lifetime for larval SA; thread safe due to > compare */ SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_larval_lifetime, 0, ""); /* counter for blocking to send SADB_ACQUIRE to IKEd */ SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_blockacq_count, 0, ""); /* lifetime for blocking to send SADB_ACQUIRE to IKEd: Thread safe, > compare */ SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_blockacq_lifetime, 0, ""); /* ESP auth */ SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth, CTLFLAG_RW | CTLFLAG_LOCKED, \ &ipsec_esp_auth, 0, ""); /* minimum ESP key length */ SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW | CTLFLAG_LOCKED, \ &ipsec_esp_keymin, 0, ""); /* minimum AH key length */ SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW | CTLFLAG_LOCKED, \ &ipsec_ah_keymin, 0, ""); /* perfered old SA rather than new SA */ SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, prefered_oldsa, CTLFLAG_RW | CTLFLAG_LOCKED, \ &key_preferred_oldsa, 0, ""); /* time between NATT keepalives in seconds, 0 disabled */ SYSCTL_INT(_net_key, KEYCTL_NATT_KEEPALIVE_INTERVAL, natt_keepalive_interval, CTLFLAG_RW | CTLFLAG_LOCKED, \ &natt_keepalive_interval, 0, ""); /* PF_KEY statistics */ SYSCTL_STRUCT(_net_key, KEYCTL_PFKEYSTAT, pfkeystat, CTLFLAG_RD | CTLFLAG_LOCKED, \ &pfkeystat, pfkeystat, ""); #ifndef LIST_FOREACH #define LIST_FOREACH(elm, head, field) \ for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field)) #endif #define __LIST_CHAINED(elm) \ (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL)) #define LIST_INSERT_TAIL(head, elm, type, field) \ do {\ struct type *curelm = LIST_FIRST(head); \ if (curelm == NULL) {\ LIST_INSERT_HEAD(head, elm, field); \ } else { \ while (LIST_NEXT(curelm, field)) \ curelm = LIST_NEXT(curelm, field);\ LIST_INSERT_AFTER(curelm, elm, field);\ }\ } while (0) #define KEY_CHKSASTATE(head, sav, name) \ do { \ if ((head) != (sav)) { \ ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \ (name), (head), (sav))); \ continue; \ } \ } while (0) #define KEY_CHKSPDIR(head, sp, name) \ do { \ if ((head) != (sp)) { \ ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \ "anyway continue.\n", \ (name), (head), (sp))); \ } \ } while (0) #if 1 #define KMALLOC_WAIT(p, t, n) \ ((p) = (t) _MALLOC((u_int32_t)(n), M_SECA, M_WAITOK)) #define KMALLOC_NOWAIT(p, t, n) \ ((p) = (t) _MALLOC((u_int32_t)(n), M_SECA, M_NOWAIT)) #define KFREE(p) \ _FREE((caddr_t)(p), M_SECA); #else #define KMALLOC_WAIT(p, t, n) \ do { \ ((p) = (t)_MALLOC((u_int32_t)(n), M_SECA, M_WAITOK)); \ printf("%s %d: %p <- KMALLOC_WAIT(%s, %d)\n", \ __FILE__, __LINE__, (p), #t, n); \ } while (0) #define KMALLOC_NOWAIT(p, t, n) \ do { \ ((p) = (t)_MALLOC((u_int32_t)(n), M_SECA, M_NOWAIT)); \ printf("%s %d: %p <- KMALLOC_NOWAIT(%s, %d)\n", \ __FILE__, __LINE__, (p), #t, n); \ } while (0) #define KFREE(p) \ do { \ printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p)); \ _FREE((caddr_t)(p), M_SECA); \ } while (0) #endif /* * set parameters into secpolicyindex buffer. * Must allocate secpolicyindex buffer passed to this function. */ #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, ifp, s_s, s_e, d_s, d_e, idx) \ do { \ bzero((idx), sizeof(struct secpolicyindex)); \ (idx)->dir = (_dir); \ (idx)->prefs = (ps); \ (idx)->prefd = (pd); \ (idx)->ul_proto = (ulp); \ (idx)->internal_if = (ifp); \ if (s) bcopy((s), &(idx)->src, ((struct sockaddr *)(s))->sa_len); \ if (d) bcopy((d), &(idx)->dst, ((struct sockaddr *)(d))->sa_len); \ if (s_s) bcopy((s_s), &(idx)->src_range.start, ((struct sockaddr *)(s_s))->sa_len); \ if (s_e) bcopy((s_e), &(idx)->src_range.end, ((struct sockaddr *)(s_e))->sa_len); \ if (d_s) bcopy((d_s), &(idx)->dst_range.start, ((struct sockaddr *)(d_s))->sa_len); \ if (d_e) bcopy((d_e), &(idx)->dst_range.end, ((struct sockaddr *)(d_e))->sa_len); \ } while (0) /* * set parameters into secasindex buffer. * Must allocate secasindex buffer before calling this function. */ #define KEY_SETSECASIDX(p, m, r, s, d, ifi, idx) \ do { \ bzero((idx), sizeof(struct secasindex)); \ (idx)->proto = (p); \ (idx)->mode = (m); \ (idx)->reqid = (r); \ bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \ bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \ (idx)->ipsec_ifindex = (ifi); \ } while (0) /* key statistics */ struct _keystat { u_int32_t getspi_count; /* the avarage of count to try to get new SPI */ } keystat; struct sadb_msghdr { struct sadb_msg *msg; struct sadb_ext *ext[SADB_EXT_MAX + 1]; int extoff[SADB_EXT_MAX + 1]; int extlen[SADB_EXT_MAX + 1]; }; static struct secpolicy *__key_getspbyid(u_int32_t id); static struct secasvar *key_do_allocsa_policy(struct secashead *, u_int, u_int16_t); static int key_do_get_translated_port(struct secashead *, struct secasvar *, u_int); static void key_delsp(struct secpolicy *); static struct secpolicy *key_getsp(struct secpolicyindex *); static u_int32_t key_newreqid(void); static struct mbuf *key_gather_mbuf(struct mbuf *, const struct sadb_msghdr *, int, int, int *); static int key_spdadd(struct socket *, struct mbuf *, const struct sadb_msghdr *); static u_int32_t key_getnewspid(void); static int key_spddelete(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spddelete2(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spdenable(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spddisable(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spdget(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spdflush(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_spddump(struct socket *, struct mbuf *, const struct sadb_msghdr *); static struct mbuf *key_setdumpsp(struct secpolicy *, u_int8_t, u_int32_t, u_int32_t); static u_int key_getspreqmsglen(struct secpolicy *); static int key_spdexpire(struct secpolicy *); static struct secashead *key_newsah(struct secasindex *, ifnet_t, u_int, u_int8_t); static struct secasvar *key_newsav(struct mbuf *, const struct sadb_msghdr *, struct secashead *, int *, struct socket *); static struct secashead *key_getsah(struct secasindex *); static struct secasvar *key_checkspidup(struct secasindex *, u_int32_t); static void key_setspi __P((struct secasvar *, u_int32_t)); static struct secasvar *key_getsavbyspi(struct secashead *, u_int32_t); static int key_setsaval(struct secasvar *, struct mbuf *, const struct sadb_msghdr *); static int key_mature(struct secasvar *); static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t, u_int8_t, u_int32_t, u_int32_t); static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t, u_int32_t, pid_t, u_int16_t); static struct mbuf *key_setsadbsa(struct secasvar *); static struct mbuf *key_setsadbaddr(u_int16_t, struct sockaddr *, u_int8_t, u_int16_t); static struct mbuf *key_setsadbipsecif(ifnet_t, ifnet_t, ifnet_t, int); #if 0 static struct mbuf *key_setsadbident(u_int16_t, u_int16_t, caddr_t, int, u_int64_t); #endif static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t, u_int16_t); static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t, u_int32_t); static void *key_newbuf(const void *, u_int); #if INET6 static int key_ismyaddr6(struct sockaddr_in6 *); #endif static void key_update_natt_keepalive_timestamp(struct secasvar *, struct secasvar *); /* flags for key_cmpsaidx() */ #define CMP_HEAD 0x1 /* protocol, addresses. */ #define CMP_PORT 0x2 /* additionally HEAD, reqid, mode. */ #define CMP_REQID 0x4 /* additionally HEAD, reqid. */ #define CMP_MODE 0x8 /* additionally mode. */ #define CMP_EXACTLY 0xF /* all elements. */ static int key_cmpsaidx(struct secasindex *, struct secasindex *, int); static int key_cmpspidx_exactly(struct secpolicyindex *, struct secpolicyindex *); static int key_cmpspidx_withmask(struct secpolicyindex *, struct secpolicyindex *); static int key_sockaddrcmp(struct sockaddr *, struct sockaddr *, int); static int key_is_addr_in_range(struct sockaddr_storage *, struct secpolicyaddrrange *); static int key_bbcmp(caddr_t, caddr_t, u_int); static void key_srandom(void); static u_int16_t key_satype2proto(u_int8_t); static u_int8_t key_proto2satype(u_int16_t); static int key_getspi(struct socket *, struct mbuf *, const struct sadb_msghdr *); static u_int32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *); static int key_update(struct socket *, struct mbuf *, const struct sadb_msghdr *); #if IPSEC_DOSEQCHECK static struct secasvar *key_getsavbyseq(struct secashead *, u_int32_t); #endif static int key_add(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_setident(struct secashead *, struct mbuf *, const struct sadb_msghdr *); static struct mbuf *key_getmsgbuf_x1(struct mbuf *, const struct sadb_msghdr *); static int key_delete(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_get(struct socket *, struct mbuf *, const struct sadb_msghdr *); static void key_getcomb_setlifetime(struct sadb_comb *); #if IPSEC_ESP static struct mbuf *key_getcomb_esp(void); #endif static struct mbuf *key_getcomb_ah(void); static struct mbuf *key_getprop(const struct secasindex *); static int key_acquire(struct secasindex *, struct secpolicy *); #ifndef IPSEC_NONBLOCK_ACQUIRE static struct secacq *key_newacq(struct secasindex *); static struct secacq *key_getacq(struct secasindex *); static struct secacq *key_getacqbyseq(u_int32_t); #endif static struct secspacq *key_newspacq(struct secpolicyindex *); static struct secspacq *key_getspacq(struct secpolicyindex *); static int key_acquire2(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_register(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_expire(struct secasvar *); static int key_flush(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_dump(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_promisc(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_senderror(struct socket *, struct mbuf *, int); static int key_validate_ext(const struct sadb_ext *, int); static int key_align(struct mbuf *, struct sadb_msghdr *); static struct mbuf *key_alloc_mbuf(int); static int key_getsastat(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_migrate(struct socket *, struct mbuf *, const struct sadb_msghdr *); static int key_setsaval2(struct secasvar *sav, u_int8_t satype, u_int8_t alg_auth, u_int8_t alg_enc, u_int32_t flags, u_int8_t replay, struct sadb_key *key_auth, u_int16_t key_auth_len, struct sadb_key *key_enc, u_int16_t key_enc_len, u_int16_t natt_port, u_int32_t seq, u_int32_t spi, u_int32_t pid, struct sadb_lifetime *lifetime_hard, struct sadb_lifetime *lifetime_soft); static void bzero_keys(const struct sadb_msghdr *); extern int ipsec_bypass; extern int esp_udp_encap_port; int ipsec_send_natt_keepalive(struct secasvar *sav); bool ipsec_fill_offload_frame(ifnet_t ifp, struct secasvar *sav, struct ifnet_keepalive_offload_frame *frame, size_t frame_data_offset); void key_init(struct protosw *, struct domain *); /* * PF_KEY init * setup locks, call raw_init(), and then init timer and associated data * */ void key_init(struct protosw *pp, struct domain *dp) { static int key_initialized = 0; int i; VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED); _CASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= _MHLEN); _CASSERT(MAX_REPLAY_WINDOWS == MBUF_TC_MAX); if (key_initialized) { return; } key_initialized = 1; sadb_mutex_grp_attr = lck_grp_attr_alloc_init(); sadb_mutex_grp = lck_grp_alloc_init("sadb", sadb_mutex_grp_attr); sadb_mutex_attr = lck_attr_alloc_init(); lck_mtx_init(sadb_mutex, sadb_mutex_grp, sadb_mutex_attr); pfkey_stat_mutex_grp_attr = lck_grp_attr_alloc_init(); pfkey_stat_mutex_grp = lck_grp_alloc_init("pfkey_stat", pfkey_stat_mutex_grp_attr); pfkey_stat_mutex_attr = lck_attr_alloc_init(); lck_mtx_init(pfkey_stat_mutex, pfkey_stat_mutex_grp, pfkey_stat_mutex_attr); for (i = 0; i < SPIHASHSIZE; i++) { LIST_INIT(&spihash[i]); } raw_init(pp, dp); bzero((caddr_t)&key_cb, sizeof(key_cb)); for (i = 0; i < IPSEC_DIR_MAX; i++) { LIST_INIT(&sptree[i]); } ipsec_policy_count = 0; LIST_INIT(&sahtree); for (i = 0; i <= SADB_SATYPE_MAX; i++) { LIST_INIT(&regtree[i]); } ipsec_sav_count = 0; #ifndef IPSEC_NONBLOCK_ACQUIRE LIST_INIT(&acqtree); #endif LIST_INIT(&spacqtree); /* system default */ #if INET ip4_def_policy.policy = IPSEC_POLICY_NONE; ip4_def_policy.refcnt++; /*never reclaim this*/ #endif #if INET6 ip6_def_policy.policy = IPSEC_POLICY_NONE; ip6_def_policy.refcnt++; /*never reclaim this*/ #endif key_timehandler_running = 0; /* initialize key statistics */ keystat.getspi_count = 1; esp_init(); #ifndef __APPLE__ printf("IPsec: Initialized Security Association Processing.\n"); #endif } static void key_start_timehandler(void) { /* must be called while locked */ LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); if (key_timehandler_running == 0) { key_timehandler_running = 1; (void)timeout((void *)key_timehandler, (void *)0, hz); } /* Turn off the ipsec bypass */ if (ipsec_bypass != 0) { ipsec_bypass = 0; } } /* %%% IPsec policy management */ /* * allocating a SP for OUTBOUND or INBOUND packet. * Must call key_freesp() later. * OUT: NULL: not found * others: found and return the pointer. */ struct secpolicy * key_allocsp( struct secpolicyindex *spidx, u_int dir) { struct secpolicy *sp; struct timeval tv; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (spidx == NULL) { panic("key_allocsp: NULL pointer is passed.\n"); } /* check direction */ switch (dir) { case IPSEC_DIR_INBOUND: case IPSEC_DIR_OUTBOUND: break; default: panic("key_allocsp: Invalid direction is passed.\n"); } /* get a SP entry */ KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("*** objects\n"); kdebug_secpolicyindex(spidx)); lck_mtx_lock(sadb_mutex); LIST_FOREACH(sp, &sptree[dir], chain) { KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("*** in SPD\n"); kdebug_secpolicyindex(&sp->spidx)); if (sp->state == IPSEC_SPSTATE_DEAD) { continue; } /* If the policy is disabled, skip */ if (sp->disabled > 0) { continue; } /* If the incoming spidx specifies bound if, * ignore unbound policies*/ if (spidx->internal_if != NULL && (sp->spidx.internal_if == NULL || sp->ipsec_if == NULL)) { continue; } if (key_cmpspidx_withmask(&sp->spidx, spidx)) { goto found; } } lck_mtx_unlock(sadb_mutex); return NULL; found: /* found a SPD entry */ microtime(&tv); sp->lastused = tv.tv_sec; sp->refcnt++; lck_mtx_unlock(sadb_mutex); /* sanity check */ KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp"); KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP key_allocsp cause refcnt++:%d SP:0x%llx\n", sp->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(sp))); return sp; } /* * return a policy that matches this particular inbound packet. * XXX slow */ struct secpolicy * key_gettunnel( struct sockaddr *osrc, struct sockaddr *odst, struct sockaddr *isrc, struct sockaddr *idst) { struct secpolicy *sp; const int dir = IPSEC_DIR_INBOUND; struct timeval tv; struct ipsecrequest *r1, *r2, *p; struct sockaddr *os, *od, *is, *id; struct secpolicyindex spidx; if (isrc->sa_family != idst->sa_family) { ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.", isrc->sa_family, idst->sa_family)); return NULL; } lck_mtx_lock(sadb_mutex); LIST_FOREACH(sp, &sptree[dir], chain) { if (sp->state == IPSEC_SPSTATE_DEAD) { continue; } r1 = r2 = NULL; for (p = sp->req; p; p = p->next) { if (p->saidx.mode != IPSEC_MODE_TUNNEL) { continue; } r1 = r2; r2 = p; if (!r1) { /* here we look at address matches only */ spidx = sp->spidx; if (isrc->sa_len > sizeof(spidx.src) || idst->sa_len > sizeof(spidx.dst)) { continue; } bcopy(isrc, &spidx.src, isrc->sa_len); bcopy(idst, &spidx.dst, idst->sa_len); if (!key_cmpspidx_withmask(&sp->spidx, &spidx)) { continue; } } else { is = (struct sockaddr *)&r1->saidx.src; id = (struct sockaddr *)&r1->saidx.dst; if (key_sockaddrcmp(is, isrc, 0) || key_sockaddrcmp(id, idst, 0)) { continue; } } os = (struct sockaddr *)&r2->saidx.src; od = (struct sockaddr *)&r2->saidx.dst; if (key_sockaddrcmp(os, osrc, 0) || key_sockaddrcmp(od, odst, 0)) { continue; } goto found; } } lck_mtx_unlock(sadb_mutex); return NULL; found: microtime(&tv); sp->lastused = tv.tv_sec; sp->refcnt++; lck_mtx_unlock(sadb_mutex); return sp; } struct secasvar * key_alloc_outbound_sav_for_interface(ifnet_t interface, int family, struct sockaddr *src, struct sockaddr *dst) { struct secashead *sah; struct secasvar *sav; u_int stateidx; u_int state; const u_int *saorder_state_valid; int arraysize; struct sockaddr_in *sin; u_int16_t dstport; bool strict = true; if (interface == NULL) { return NULL; } LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); lck_mtx_lock(sadb_mutex); do { LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (sah->ipsec_if == interface && (family == AF_INET6 || family == AF_INET) && sah->dir == IPSEC_DIR_OUTBOUND) { if (strict && sah->saidx.mode == IPSEC_MODE_TRANSPORT && src != NULL && dst != NULL) { // Validate addresses for transport mode if (key_sockaddrcmp((struct sockaddr *)&sah->saidx.src, src, 0) != 0) { // Source doesn't match continue; } if (key_sockaddrcmp((struct sockaddr *)&sah->saidx.dst, dst, 0) != 0) { // Destination doesn't match continue; } } /* This SAH is linked to the IPsec interface, and the right family. We found it! */ if (key_preferred_oldsa) { saorder_state_valid = saorder_state_valid_prefer_old; arraysize = _ARRAYLEN(saorder_state_valid_prefer_old); } else { saorder_state_valid = saorder_state_valid_prefer_new; arraysize = _ARRAYLEN(saorder_state_valid_prefer_new); } sin = (struct sockaddr_in *)&sah->saidx.dst; dstport = sin->sin_port; if (sah->saidx.mode == IPSEC_MODE_TRANSPORT) { sin->sin_port = IPSEC_PORT_ANY; } for (stateidx = 0; stateidx < arraysize; stateidx++) { state = saorder_state_valid[stateidx]; sav = key_do_allocsa_policy(sah, state, dstport); if (sav != NULL) { lck_mtx_unlock(sadb_mutex); return sav; } } break; } } if (strict) { // If we didn't find anything, try again without strict strict = false; } else { // We already were on the second try, bail break; } } while (true); lck_mtx_unlock(sadb_mutex); return NULL; } /* * allocating an SA entry for an *OUTBOUND* packet. * checking each request entries in SP, and acquire an SA if need. * OUT: 0: there are valid requests. * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring. */ int key_checkrequest( struct ipsecrequest *isr, struct secasindex *saidx, struct secasvar **sav) { u_int level; int error; struct sockaddr_in *sin; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); *sav = NULL; /* sanity check */ if (isr == NULL || saidx == NULL) { panic("key_checkrequest: NULL pointer is passed.\n"); } /* check mode */ switch (saidx->mode) { case IPSEC_MODE_TRANSPORT: case IPSEC_MODE_TUNNEL: break; case IPSEC_MODE_ANY: default: panic("key_checkrequest: Invalid policy defined.\n"); } /* get current level */ level = ipsec_get_reqlevel(isr); /* * key_allocsa_policy should allocate the oldest SA available. * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt. */ if (*sav == NULL) { *sav = key_allocsa_policy(saidx); } /* When there is SA. */ if (*sav != NULL) { return 0; } /* There is no SA. * * Remove dst port - used for special natt support - don't call * key_acquire with it. */ if (saidx->mode == IPSEC_MODE_TRANSPORT) { sin = (struct sockaddr_in *)&saidx->dst; sin->sin_port = IPSEC_PORT_ANY; } if ((error = key_acquire(saidx, isr->sp)) != 0) { /* XXX What should I do ? */ ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned " "from key_acquire.\n", error)); return error; } return level == IPSEC_LEVEL_REQUIRE ? ENOENT : 0; } /* * allocating a SA for policy entry from SAD. * NOTE: searching SAD of aliving state. * OUT: NULL: not found. * others: found and return the pointer. */ u_int32_t sah_search_calls = 0; u_int32_t sah_search_count = 0; struct secasvar * key_allocsa_policy( struct secasindex *saidx) { struct secashead *sah; struct secasvar *sav; u_int stateidx, state; const u_int *saorder_state_valid; int arraysize; struct sockaddr_in *sin; u_int16_t dstport; lck_mtx_lock(sadb_mutex); sah_search_calls++; LIST_FOREACH(sah, &sahtree, chain) { sah_search_count++; if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE | CMP_REQID)) { goto found; } } lck_mtx_unlock(sadb_mutex); return NULL; found: /* * search a valid state list for outbound packet. * This search order is important. */ if (key_preferred_oldsa) { saorder_state_valid = saorder_state_valid_prefer_old; arraysize = _ARRAYLEN(saorder_state_valid_prefer_old); } else { saorder_state_valid = saorder_state_valid_prefer_new; arraysize = _ARRAYLEN(saorder_state_valid_prefer_new); } sin = (struct sockaddr_in *)&saidx->dst; dstport = sin->sin_port; if (saidx->mode == IPSEC_MODE_TRANSPORT) { sin->sin_port = IPSEC_PORT_ANY; } for (stateidx = 0; stateidx < arraysize; stateidx++) { state = saorder_state_valid[stateidx]; sav = key_do_allocsa_policy(sah, state, dstport); if (sav != NULL) { lck_mtx_unlock(sadb_mutex); return sav; } } lck_mtx_unlock(sadb_mutex); return NULL; } static void key_send_delete(struct secasvar *sav) { struct mbuf *m, *result; u_int8_t satype; key_sa_chgstate(sav, SADB_SASTATE_DEAD); if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) { panic("key_do_allocsa_policy: invalid proto is passed.\n"); } m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0, sav->refcnt - 1); if (!m) { goto msgfail; } result = m; /* set sadb_address for saidx's. */ m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sav->sah->saidx.src, sav->sah->saidx.src.ss_len << 3, IPSEC_ULPROTO_ANY); if (!m) { goto msgfail; } m_cat(result, m); /* set sadb_address for saidx's. */ m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sav->sah->saidx.dst, sav->sah->saidx.src.ss_len << 3, IPSEC_ULPROTO_ANY); if (!m) { goto msgfail; } m_cat(result, m); /* create SA extension */ m = key_setsadbsa(sav); if (!m) { goto msgfail; } m_cat(result, m); if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { goto msgfail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); if (key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED)) { goto msgfail; } msgfail: key_freesav(sav, KEY_SADB_LOCKED); } /* * searching SAD with direction, protocol, mode and state. * called by key_allocsa_policy(). * OUT: * NULL : not found * others : found, pointer to a SA. */ static struct secasvar * key_do_allocsa_policy( struct secashead *sah, u_int state, u_int16_t dstport) { struct secasvar *sav, *nextsav, *candidate, *natt_candidate, *no_natt_candidate, *d; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* initialize */ candidate = NULL; natt_candidate = NULL; no_natt_candidate = NULL; for (sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); /* sanity check */ KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy"); if (sah->saidx.mode == IPSEC_MODE_TUNNEL && dstport && ((sav->flags & SADB_X_EXT_NATT) != 0) && ntohs(dstport) != sav->remote_ike_port) { continue; } if (sah->saidx.mode == IPSEC_MODE_TRANSPORT && ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) && ntohs(dstport) != sav->remote_ike_port) { continue; /* skip this one - not a match - or not UDP */ } if ((sah->saidx.mode == IPSEC_MODE_TUNNEL && ((sav->flags & SADB_X_EXT_NATT) != 0)) || (sah->saidx.mode == IPSEC_MODE_TRANSPORT && ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0))) { if (natt_candidate == NULL) { natt_candidate = sav; continue; } else { candidate = natt_candidate; } } else { if (no_natt_candidate == NULL) { no_natt_candidate = sav; continue; } else { candidate = no_natt_candidate; } } /* Which SA is the better ? */ /* sanity check 2 */ if (candidate->lft_c == NULL || sav->lft_c == NULL) { panic("key_do_allocsa_policy: " "lifetime_current is NULL.\n"); } /* What the best method is to compare ? */ if (key_preferred_oldsa) { if (candidate->lft_c->sadb_lifetime_addtime > sav->lft_c->sadb_lifetime_addtime) { if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) { natt_candidate = sav; } else { no_natt_candidate = sav; } } continue; /*NOTREACHED*/ } /* prefered new sa rather than old sa */ if (candidate->lft_c->sadb_lifetime_addtime < sav->lft_c->sadb_lifetime_addtime) { d = candidate; if ((sah->saidx.mode == IPSEC_MODE_TUNNEL && ((sav->flags & SADB_X_EXT_NATT) != 0)) || (sah->saidx.mode == IPSEC_MODE_TRANSPORT && ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0))) { natt_candidate = sav; } else { no_natt_candidate = sav; } } else { d = sav; } /* * prepared to delete the SA when there is more * suitable candidate and the lifetime of the SA is not * permanent. */ if (d->lft_c->sadb_lifetime_addtime != 0) { key_send_delete(d); } } /* choose latest if both types present */ if (natt_candidate == NULL) { candidate = no_natt_candidate; } else if (no_natt_candidate == NULL) { candidate = natt_candidate; } else if (sah->saidx.mode == IPSEC_MODE_TUNNEL && dstport) { candidate = natt_candidate; } else if (natt_candidate->lft_c->sadb_lifetime_addtime > no_natt_candidate->lft_c->sadb_lifetime_addtime) { candidate = natt_candidate; } else { candidate = no_natt_candidate; } if (candidate) { candidate->refcnt++; KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP allocsa_policy cause " "refcnt++:%d SA:0x%llx\n", candidate->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(candidate))); } return candidate; } /* * allocating a SA entry for a *INBOUND* packet. * Must call key_freesav() later. * OUT: positive: pointer to a sav. * NULL: not found, or error occurred. * * In the comparison, source address will be ignored for RFC2401 conformance. * To quote, from section 4.1: * A security association is uniquely identified by a triple consisting * of a Security Parameter Index (SPI), an IP Destination Address, and a * security protocol (AH or ESP) identifier. * Note that, however, we do need to keep source address in IPsec SA. * IKE specification and PF_KEY specification do assume that we * keep source address in IPsec SA. We see a tricky situation here. */ struct secasvar * key_allocsa( u_int family, caddr_t src, caddr_t dst, u_int proto, u_int32_t spi) { return key_allocsa_extended(family, src, dst, proto, spi, NULL); } struct secasvar * key_allocsa_extended(u_int family, caddr_t src, caddr_t dst, u_int proto, u_int32_t spi, ifnet_t interface) { struct secasvar *sav, *match; u_int stateidx, state, tmpidx, matchidx; struct sockaddr_in sin; struct sockaddr_in6 sin6; const u_int *saorder_state_valid; int arraysize; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (src == NULL || dst == NULL) { panic("key_allocsa: NULL pointer is passed.\n"); } /* * when both systems employ similar strategy to use a SA. * the search order is important even in the inbound case. */ if (key_preferred_oldsa) { saorder_state_valid = saorder_state_valid_prefer_old; arraysize = _ARRAYLEN(saorder_state_valid_prefer_old); } else { saorder_state_valid = saorder_state_valid_prefer_new; arraysize = _ARRAYLEN(saorder_state_valid_prefer_new); } /* * searching SAD. * XXX: to be checked internal IP header somewhere. Also when * IPsec tunnel packet is received. But ESP tunnel mode is * encrypted so we can't check internal IP header. */ /* * search a valid state list for inbound packet. * the search order is not important. */ match = NULL; matchidx = arraysize; lck_mtx_lock(sadb_mutex); LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) { if (sav->spi != spi) { continue; } if (interface != NULL && sav->sah->ipsec_if != interface) { continue; } if (proto != sav->sah->saidx.proto) { continue; } if (family != sav->sah->saidx.src.ss_family || family != sav->sah->saidx.dst.ss_family) { continue; } tmpidx = arraysize; for (stateidx = 0; stateidx < matchidx; stateidx++) { state = saorder_state_valid[stateidx]; if (sav->state == state) { tmpidx = stateidx; break; } } if (tmpidx >= matchidx) { continue; } #if 0 /* don't check src */ /* check src address */ switch (family) { case AF_INET: bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_len = sizeof(sin); bcopy(src, &sin.sin_addr, sizeof(sin.sin_addr)); if (key_sockaddrcmp((struct sockaddr*)&sin, (struct sockaddr *)&sav->sah->saidx.src, 0) != 0) { continue; } break; case AF_INET6: bzero(&sin6, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_len = sizeof(sin6); bcopy(src, &sin6.sin6_addr, sizeof(sin6.sin6_addr)); if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) { /* kame fake scopeid */ sin6.sin6_scope_id = ntohs(sin6.sin6_addr.s6_addr16[1]); sin6.sin6_addr.s6_addr16[1] = 0; } if (key_sockaddrcmp((struct sockaddr*)&sin6, (struct sockaddr *)&sav->sah->saidx.src, 0) != 0) { continue; } break; default: ipseclog((LOG_DEBUG, "key_allocsa: " "unknown address family=%d.\n", family)); continue; } #endif /* check dst address */ switch (family) { case AF_INET: bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_len = sizeof(sin); bcopy(dst, &sin.sin_addr, sizeof(sin.sin_addr)); if (key_sockaddrcmp((struct sockaddr*)&sin, (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0) { continue; } break; case AF_INET6: bzero(&sin6, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_len = sizeof(sin6); bcopy(dst, &sin6.sin6_addr, sizeof(sin6.sin6_addr)); if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) { /* kame fake scopeid */ sin6.sin6_scope_id = ntohs(sin6.sin6_addr.s6_addr16[1]); sin6.sin6_addr.s6_addr16[1] = 0; } if (key_sockaddrcmp((struct sockaddr*)&sin6, (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0) { continue; } break; default: ipseclog((LOG_DEBUG, "key_allocsa: " "unknown address family=%d.\n", family)); continue; } match = sav; matchidx = tmpidx; } if (match) { goto found; } /* not found */ lck_mtx_unlock(sadb_mutex); return NULL; found: match->refcnt++; lck_mtx_unlock(sadb_mutex); KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP allocsa cause refcnt++:%d SA:0x%llx\n", match->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(match))); return match; } /* * This function checks whether a UDP packet with a random local port * and a remote port of 4500 matches an SA in the kernel. If does match, * send the packet to the ESP engine. If not, send the packet to the UDP protocol. */ bool key_checksa_present(u_int family, caddr_t local_addr, caddr_t remote_addr, u_int16_t local_port, u_int16_t remote_port) { LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (local_addr == NULL || remote_addr == NULL) { panic("key_allocsa: NULL pointer is passed.\n"); } /* * searching SAD. * XXX: to be checked internal IP header somewhere. Also when * IPsec tunnel packet is received. But ESP tunnel mode is * encrypted so we can't check internal IP header. */ /* * search a valid state list for inbound packet. * the search order is not important. */ struct secashead *sah = NULL; bool found_sa = false; lck_mtx_lock(sadb_mutex); LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (sah->dir != IPSEC_DIR_OUTBOUND) { continue; } if (family != sah->saidx.src.ss_family) { continue; } struct sockaddr_in src_in = {}; struct sockaddr_in6 src_in6 = {}; /* check src address */ switch (family) { case AF_INET: src_in.sin_family = AF_INET; src_in.sin_len = sizeof(src_in); memcpy(&src_in.sin_addr, local_addr, sizeof(src_in.sin_addr)); if (key_sockaddrcmp((struct sockaddr*)&src_in, (struct sockaddr *)&sah->saidx.src, 0) != 0) { continue; } break; case AF_INET6: src_in6.sin6_family = AF_INET6; src_in6.sin6_len = sizeof(src_in6); memcpy(&src_in6.sin6_addr, local_addr, sizeof(src_in6.sin6_addr)); if (IN6_IS_SCOPE_LINKLOCAL(&src_in6.sin6_addr)) { /* kame fake scopeid */ src_in6.sin6_scope_id = ntohs(src_in6.sin6_addr.s6_addr16[1]); src_in6.sin6_addr.s6_addr16[1] = 0; } if (key_sockaddrcmp((struct sockaddr*)&src_in6, (struct sockaddr *)&sah->saidx.src, 0) != 0) { continue; } break; default: ipseclog((LOG_DEBUG, "key_checksa_present: " "unknown address family=%d.\n", family)); continue; } struct sockaddr_in dest_in = {}; struct sockaddr_in6 dest_in6 = {}; /* check dst address */ switch (family) { case AF_INET: dest_in.sin_family = AF_INET; dest_in.sin_len = sizeof(dest_in); memcpy(&dest_in.sin_addr, remote_addr, sizeof(dest_in.sin_addr)); if (key_sockaddrcmp((struct sockaddr*)&dest_in, (struct sockaddr *)&sah->saidx.dst, 0) != 0) { continue; } break; case AF_INET6: dest_in6.sin6_family = AF_INET6; dest_in6.sin6_len = sizeof(dest_in6); memcpy(&dest_in6.sin6_addr, remote_addr, sizeof(dest_in6.sin6_addr)); if (IN6_IS_SCOPE_LINKLOCAL(&dest_in6.sin6_addr)) { /* kame fake scopeid */ dest_in6.sin6_scope_id = ntohs(dest_in6.sin6_addr.s6_addr16[1]); dest_in6.sin6_addr.s6_addr16[1] = 0; } if (key_sockaddrcmp((struct sockaddr*)&dest_in6, (struct sockaddr *)&sah->saidx.dst, 0) != 0) { continue; } break; default: ipseclog((LOG_DEBUG, "key_checksa_present: " "unknown address family=%d.\n", family)); continue; } struct secasvar *nextsav = NULL; for (u_int stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { u_int state = saorder_state_alive[stateidx]; for (struct secasvar *sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); /* sanity check */ if (sav->state != state) { ipseclog((LOG_DEBUG, "key_checksa_present: " "invalid sav->state " "(state: %d SA: %d)\n", state, sav->state)); continue; } if (sav->remote_ike_port != ntohs(remote_port)) { continue; } if (sav->natt_encapsulated_src_port != local_port) { continue; } found_sa = true;; break; } } } /* not found */ lck_mtx_unlock(sadb_mutex); return found_sa; } u_int16_t key_natt_get_translated_port( struct secasvar *outsav) { struct secasindex saidx; struct secashead *sah; u_int stateidx, state; const u_int *saorder_state_valid; int arraysize; /* get sa for incoming */ saidx.mode = outsav->sah->saidx.mode; saidx.reqid = 0; saidx.proto = outsav->sah->saidx.proto; bcopy(&outsav->sah->saidx.src, &saidx.dst, sizeof(struct sockaddr_in)); bcopy(&outsav->sah->saidx.dst, &saidx.src, sizeof(struct sockaddr_in)); lck_mtx_lock(sadb_mutex); LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE)) { goto found; } } lck_mtx_unlock(sadb_mutex); return 0; found: /* * Found sah - now go thru list of SAs and find * matching remote ike port. If found - set * sav->natt_encapsulated_src_port and return the port. */ /* * search a valid state list for outbound packet. * This search order is important. */ if (key_preferred_oldsa) { saorder_state_valid = saorder_state_valid_prefer_old; arraysize = _ARRAYLEN(saorder_state_valid_prefer_old); } else { saorder_state_valid = saorder_state_valid_prefer_new; arraysize = _ARRAYLEN(saorder_state_valid_prefer_new); } for (stateidx = 0; stateidx < arraysize; stateidx++) { state = saorder_state_valid[stateidx]; if (key_do_get_translated_port(sah, outsav, state)) { lck_mtx_unlock(sadb_mutex); return outsav->natt_encapsulated_src_port; } } lck_mtx_unlock(sadb_mutex); return 0; } static int key_do_get_translated_port( struct secashead *sah, struct secasvar *outsav, u_int state) { struct secasvar *currsav, *nextsav, *candidate; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* initilize */ candidate = NULL; for (currsav = LIST_FIRST(&sah->savtree[state]); currsav != NULL; currsav = nextsav) { nextsav = LIST_NEXT(currsav, chain); /* sanity check */ KEY_CHKSASTATE(currsav->state, state, "key_do_get_translated_port"); if ((currsav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) == 0 || currsav->remote_ike_port != outsav->remote_ike_port) { continue; } if (candidate == NULL) { candidate = currsav; continue; } /* Which SA is the better ? */ /* sanity check 2 */ if (candidate->lft_c == NULL || currsav->lft_c == NULL) { panic("key_do_get_translated_port: " "lifetime_current is NULL.\n"); } /* What the best method is to compare ? */ if (key_preferred_oldsa) { if (candidate->lft_c->sadb_lifetime_addtime > currsav->lft_c->sadb_lifetime_addtime) { candidate = currsav; } continue; /*NOTREACHED*/ } /* prefered new sa rather than old sa */ if (candidate->lft_c->sadb_lifetime_addtime < currsav->lft_c->sadb_lifetime_addtime) { candidate = currsav; } } if (candidate) { outsav->natt_encapsulated_src_port = candidate->natt_encapsulated_src_port; return 1; } return 0; } /* * Must be called after calling key_allocsp(). */ void key_freesp( struct secpolicy *sp, int locked) { /* sanity check */ if (sp == NULL) { panic("key_freesp: NULL pointer is passed.\n"); } if (!locked) { lck_mtx_lock(sadb_mutex); } else { LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); } sp->refcnt--; KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP freesp cause refcnt--:%d SP:0x%llx\n", sp->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(sp))); if (sp->refcnt == 0) { key_delsp(sp); } if (!locked) { lck_mtx_unlock(sadb_mutex); } return; } /* * Must be called after calling key_allocsa(). * This function is called by key_freesp() to free some SA allocated * for a policy. */ void key_freesav( struct secasvar *sav, int locked) { /* sanity check */ if (sav == NULL) { panic("key_freesav: NULL pointer is passed.\n"); } if (!locked) { lck_mtx_lock(sadb_mutex); } else { LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); } sav->refcnt--; KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP freesav cause refcnt--:%d SA:0x%llx SPI %u\n", sav->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(sav), (u_int32_t)ntohl(sav->spi))); if (sav->refcnt == 0) { key_delsav(sav); } if (!locked) { lck_mtx_unlock(sadb_mutex); } return; } /* %%% SPD management */ /* * free security policy entry. */ static void key_delsp( struct secpolicy *sp) { /* sanity check */ if (sp == NULL) { panic("key_delsp: NULL pointer is passed.\n"); } LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); sp->state = IPSEC_SPSTATE_DEAD; if (sp->refcnt > 0) { return; /* can't free */ } /* remove from SP index */ if (__LIST_CHAINED(sp)) { LIST_REMOVE(sp, chain); ipsec_policy_count--; } if (sp->spidx.internal_if) { ifnet_release(sp->spidx.internal_if); sp->spidx.internal_if = NULL; } if (sp->ipsec_if) { ifnet_release(sp->ipsec_if); sp->ipsec_if = NULL; } if (sp->outgoing_if) { ifnet_release(sp->outgoing_if); sp->outgoing_if = NULL; } { struct ipsecrequest *isr = sp->req, *nextisr; while (isr != NULL) { nextisr = isr->next; KFREE(isr); isr = nextisr; } } keydb_delsecpolicy(sp); return; } /* * search SPD * OUT: NULL : not found * others : found, pointer to a SP. */ static struct secpolicy * key_getsp( struct secpolicyindex *spidx) { struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (spidx == NULL) { panic("key_getsp: NULL pointer is passed.\n"); } LIST_FOREACH(sp, &sptree[spidx->dir], chain) { if (sp->state == IPSEC_SPSTATE_DEAD) { continue; } if (key_cmpspidx_exactly(spidx, &sp->spidx)) { sp->refcnt++; return sp; } } return NULL; } /* * get SP by index. * OUT: NULL : not found * others : found, pointer to a SP. */ struct secpolicy * key_getspbyid( u_int32_t id) { struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); lck_mtx_lock(sadb_mutex); sp = __key_getspbyid(id); lck_mtx_unlock(sadb_mutex); return sp; } static struct secpolicy * __key_getspbyid(u_int32_t id) { struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) { if (sp->state == IPSEC_SPSTATE_DEAD) { continue; } if (sp->id == id) { sp->refcnt++; return sp; } } LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) { if (sp->state == IPSEC_SPSTATE_DEAD) { continue; } if (sp->id == id) { sp->refcnt++; return sp; } } return NULL; } struct secpolicy * key_newsp(void) { struct secpolicy *newsp = NULL; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); newsp = keydb_newsecpolicy(); if (!newsp) { return newsp; } newsp->refcnt = 1; newsp->req = NULL; return newsp; } /* * create secpolicy structure from sadb_x_policy structure. * NOTE: `state', `secpolicyindex' in secpolicy structure are not set, * so must be set properly later. */ struct secpolicy * key_msg2sp( struct sadb_x_policy *xpl0, size_t len, int *error) { struct secpolicy *newsp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (xpl0 == NULL) { panic("key_msg2sp: NULL pointer was passed.\n"); } if (len < sizeof(*xpl0)) { panic("key_msg2sp: invalid length.\n"); } if (len != PFKEY_EXTLEN(xpl0)) { ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n")); *error = EINVAL; return NULL; } if ((newsp = key_newsp()) == NULL) { *error = ENOBUFS; return NULL; } newsp->spidx.dir = xpl0->sadb_x_policy_dir; newsp->policy = xpl0->sadb_x_policy_type; /* check policy */ switch (xpl0->sadb_x_policy_type) { case IPSEC_POLICY_DISCARD: case IPSEC_POLICY_GENERATE: case IPSEC_POLICY_NONE: case IPSEC_POLICY_ENTRUST: case IPSEC_POLICY_BYPASS: newsp->req = NULL; break; case IPSEC_POLICY_IPSEC: { int tlen; struct sadb_x_ipsecrequest *xisr; struct ipsecrequest **p_isr = &newsp->req; /* validity check */ if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) { ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0); xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1); while (tlen > 0) { if (tlen < sizeof(*xisr)) { ipseclog((LOG_DEBUG, "key_msg2sp: " "invalid ipsecrequest.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } /* length check */ if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) { ipseclog((LOG_DEBUG, "key_msg2sp: " "invalid ipsecrequest length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } /* allocate request buffer */ KMALLOC_WAIT(*p_isr, struct ipsecrequest *, sizeof(**p_isr)); if ((*p_isr) == NULL) { ipseclog((LOG_DEBUG, "key_msg2sp: No more memory.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = ENOBUFS; return NULL; } bzero(*p_isr, sizeof(**p_isr)); /* set values */ (*p_isr)->next = NULL; switch (xisr->sadb_x_ipsecrequest_proto) { case IPPROTO_ESP: case IPPROTO_AH: break; default: ipseclog((LOG_DEBUG, "key_msg2sp: invalid proto type=%u\n", xisr->sadb_x_ipsecrequest_proto)); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EPROTONOSUPPORT; return NULL; } (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto; switch (xisr->sadb_x_ipsecrequest_mode) { case IPSEC_MODE_TRANSPORT: case IPSEC_MODE_TUNNEL: break; case IPSEC_MODE_ANY: default: ipseclog((LOG_DEBUG, "key_msg2sp: invalid mode=%u\n", xisr->sadb_x_ipsecrequest_mode)); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode; switch (xisr->sadb_x_ipsecrequest_level) { case IPSEC_LEVEL_DEFAULT: case IPSEC_LEVEL_USE: case IPSEC_LEVEL_REQUIRE: break; case IPSEC_LEVEL_UNIQUE: /* validity check */ /* * If range violation of reqid, kernel will * update it, don't refuse it. */ if (xisr->sadb_x_ipsecrequest_reqid > IPSEC_MANUAL_REQID_MAX) { ipseclog((LOG_DEBUG, "key_msg2sp: reqid=%d range " "violation, updated by kernel.\n", xisr->sadb_x_ipsecrequest_reqid)); xisr->sadb_x_ipsecrequest_reqid = 0; } /* allocate new reqid id if reqid is zero. */ if (xisr->sadb_x_ipsecrequest_reqid == 0) { u_int32_t reqid; if ((reqid = key_newreqid()) == 0) { key_freesp(newsp, KEY_SADB_UNLOCKED); *error = ENOBUFS; return NULL; } (*p_isr)->saidx.reqid = reqid; xisr->sadb_x_ipsecrequest_reqid = reqid; } else { /* set it for manual keying. */ (*p_isr)->saidx.reqid = xisr->sadb_x_ipsecrequest_reqid; } break; default: ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n", xisr->sadb_x_ipsecrequest_level)); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } (*p_isr)->level = xisr->sadb_x_ipsecrequest_level; /* set IP addresses if there */ if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) { struct sockaddr *paddr; if (tlen < xisr->sadb_x_ipsecrequest_len) { ipseclog((LOG_DEBUG, "key_msg2sp: invalid request " "address length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } paddr = (struct sockaddr *)(xisr + 1); uint8_t src_len = paddr->sa_len; /* +sizeof(uint8_t) for dst_len below */ if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) + src_len + sizeof(uint8_t)) { ipseclog((LOG_DEBUG, "key_msg2sp: invalid request " "invalid source address length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } /* validity check */ if (paddr->sa_len > sizeof((*p_isr)->saidx.src)) { ipseclog((LOG_DEBUG, "key_msg2sp: invalid request " "address length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } bcopy(paddr, &(*p_isr)->saidx.src, MIN(paddr->sa_len, sizeof((*p_isr)->saidx.src))); paddr = (struct sockaddr *)((caddr_t)paddr + paddr->sa_len); uint8_t dst_len = paddr->sa_len; if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) + src_len + dst_len) { ipseclog((LOG_DEBUG, "key_msg2sp: invalid request " "invalid dest address length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } /* validity check */ if (paddr->sa_len > sizeof((*p_isr)->saidx.dst)) { ipseclog((LOG_DEBUG, "key_msg2sp: invalid request " "address length.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } bcopy(paddr, &(*p_isr)->saidx.dst, MIN(paddr->sa_len, sizeof((*p_isr)->saidx.dst))); } (*p_isr)->sp = newsp; /* initialization for the next. */ p_isr = &(*p_isr)->next; tlen -= xisr->sadb_x_ipsecrequest_len; /* validity check */ if (tlen < 0) { ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } xisr = (struct sadb_x_ipsecrequest *)(void *) ((caddr_t)xisr + xisr->sadb_x_ipsecrequest_len); } } break; default: ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n")); key_freesp(newsp, KEY_SADB_UNLOCKED); *error = EINVAL; return NULL; } *error = 0; return newsp; } static u_int32_t key_newreqid(void) { lck_mtx_lock(sadb_mutex); static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1; int done = 0; /* The reqid must be limited to 16 bits because the PF_KEY message format only uses * 16 bits for this field. Once it becomes larger than 16 bits - ipsec fails to * work anymore. Changing the PF_KEY message format would introduce compatibility * issues. This code now tests to see if the tentative reqid is in use */ while (!done) { struct secpolicy *sp; struct ipsecrequest *isr; int dir; auto_reqid = (auto_reqid == 0xFFFF ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1); /* check for uniqueness */ done = 1; for (dir = 0; dir < IPSEC_DIR_MAX; dir++) { LIST_FOREACH(sp, &sptree[dir], chain) { for (isr = sp->req; isr != NULL; isr = isr->next) { if (isr->saidx.reqid == auto_reqid) { done = 0; break; } } if (done == 0) { break; } } if (done == 0) { break; } } } lck_mtx_unlock(sadb_mutex); return auto_reqid; } /* * copy secpolicy struct to sadb_x_policy structure indicated. */ struct mbuf * key_sp2msg( struct secpolicy *sp) { struct sadb_x_policy *xpl; int tlen; caddr_t p; struct mbuf *m; /* sanity check. */ if (sp == NULL) { panic("key_sp2msg: NULL pointer was passed.\n"); } tlen = key_getspreqmsglen(sp); m = key_alloc_mbuf(tlen); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } m->m_len = tlen; m->m_next = NULL; xpl = mtod(m, struct sadb_x_policy *); bzero(xpl, tlen); xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen); xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY; xpl->sadb_x_policy_type = sp->policy; xpl->sadb_x_policy_dir = sp->spidx.dir; xpl->sadb_x_policy_id = sp->id; p = (caddr_t)xpl + sizeof(*xpl); /* if is the policy for ipsec ? */ if (sp->policy == IPSEC_POLICY_IPSEC) { struct sadb_x_ipsecrequest *xisr; struct ipsecrequest *isr; for (isr = sp->req; isr != NULL; isr = isr->next) { xisr = (struct sadb_x_ipsecrequest *)(void *)p; xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto; xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode; xisr->sadb_x_ipsecrequest_level = isr->level; xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid; p += sizeof(*xisr); bcopy(&isr->saidx.src, p, isr->saidx.src.ss_len); p += isr->saidx.src.ss_len; bcopy(&isr->saidx.dst, p, isr->saidx.dst.ss_len); p += isr->saidx.src.ss_len; xisr->sadb_x_ipsecrequest_len = PFKEY_ALIGN8(sizeof(*xisr) + isr->saidx.src.ss_len + isr->saidx.dst.ss_len); } } return m; } /* m will not be freed nor modified */ static struct mbuf * key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp, int ndeep, int nitem, int *items) { int idx; int i; struct mbuf *result = NULL, *n; int len; if (m == NULL || mhp == NULL) { panic("null pointer passed to key_gather"); } for (i = 0; i < nitem; i++) { idx = items[i]; if (idx < 0 || idx > SADB_EXT_MAX) { goto fail; } /* don't attempt to pull empty extension */ if (idx == SADB_EXT_RESERVED && mhp->msg == NULL) { continue; } if (idx != SADB_EXT_RESERVED && (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0)) { continue; } if (idx == SADB_EXT_RESERVED) { len = PFKEY_ALIGN8(sizeof(struct sadb_msg)); MGETHDR(n, M_WAITOK, MT_DATA); // sadb_msg len < MHLEN - enforced by _CASSERT if (!n) { goto fail; } n->m_len = len; n->m_next = NULL; m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t)); } else if (i < ndeep) { len = mhp->extlen[idx]; n = key_alloc_mbuf(len); if (!n || n->m_next) { /*XXX*/ if (n) { m_freem(n); } goto fail; } m_copydata(m, mhp->extoff[idx], mhp->extlen[idx], mtod(n, caddr_t)); } else { n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx], M_WAITOK); } if (n == NULL) { goto fail; } if (result) { m_cat(result, n); } else { result = n; } } if ((result->m_flags & M_PKTHDR) != 0) { result->m_pkthdr.len = 0; for (n = result; n; n = n->m_next) { result->m_pkthdr.len += n->m_len; } } return result; fail: m_freem(result); return NULL; } /* * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing * add a entry to SP database, when received * <base, address(SD), (lifetime(H),) policy> * from the user(?). * Adding to SP database, * and send * <base, address(SD), (lifetime(H),) policy> * to the socket which was send. * * SPDADD set a unique policy entry. * SPDSETIDX like SPDADD without a part of policy requests. * SPDUPDATE replace a unique policy entry. * * m will always be freed. */ static int key_spdadd( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_address *src0, *dst0, *src1 = NULL, *dst1 = NULL; struct sadb_x_policy *xpl0, *xpl; struct sadb_lifetime *lft = NULL; struct secpolicyindex spidx; struct secpolicy *newsp; struct timeval tv; ifnet_t internal_if = NULL; char *outgoing_if = NULL; char *ipsec_if = NULL; struct sadb_x_ipsecif *ipsecifopts = NULL; int error; int use_src_range = 0; int use_dst_range = 0; int init_disabled = 0; int address_family, address_len; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spdadd: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_START] != NULL && mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_END] != NULL) { use_src_range = 1; } if (mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_START] != NULL && mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_END] != NULL) { use_dst_range = 1; } if ((!use_src_range && mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL) || (!use_dst_range && mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) || mhp->ext[SADB_X_EXT_POLICY] == NULL) { ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if ((use_src_range && (mhp->extlen[SADB_X_EXT_ADDR_RANGE_SRC_START] < sizeof(struct sadb_address) || mhp->extlen[SADB_X_EXT_ADDR_RANGE_SRC_END] < sizeof(struct sadb_address))) || (!use_src_range && mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address)) || (use_dst_range && (mhp->extlen[SADB_X_EXT_ADDR_RANGE_DST_START] < sizeof(struct sadb_address) || mhp->extlen[SADB_X_EXT_ADDR_RANGE_DST_END] < sizeof(struct sadb_address))) || (!use_dst_range && mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) { if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(struct sadb_lifetime)) { ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } lft = (struct sadb_lifetime *) (void *)mhp->ext[SADB_EXT_LIFETIME_HARD]; } if (mhp->ext[SADB_X_EXT_IPSECIF] != NULL) { if (mhp->extlen[SADB_X_EXT_IPSECIF] < sizeof(struct sadb_x_ipsecif)) { ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } } if (use_src_range) { src0 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_START]; src1 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_END]; } else { src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC]; } if (use_dst_range) { dst0 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_START]; dst1 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_END]; } else { dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST]; } xpl0 = (struct sadb_x_policy *)(void *)mhp->ext[SADB_X_EXT_POLICY]; ipsecifopts = (struct sadb_x_ipsecif *)(void *)mhp->ext[SADB_X_EXT_IPSECIF]; /* check addresses */ address_family = ((struct sockaddr *)(src0 + 1))->sa_family; address_len = ((struct sockaddr *)(src0 + 1))->sa_len; if (use_src_range) { if (((struct sockaddr *)(src1 + 1))->sa_family != address_family || ((struct sockaddr *)(src1 + 1))->sa_len != address_len) { return key_senderror(so, m, EINVAL); } } if (((struct sockaddr *)(dst0 + 1))->sa_family != address_family || ((struct sockaddr *)(dst0 + 1))->sa_len != address_len) { return key_senderror(so, m, EINVAL); } if (use_dst_range) { if (((struct sockaddr *)(dst1 + 1))->sa_family != address_family || ((struct sockaddr *)(dst1 + 1))->sa_len != address_len) { return key_senderror(so, m, EINVAL); } } /* checking the direction. */ switch (xpl0->sadb_x_policy_dir) { case IPSEC_DIR_INBOUND: case IPSEC_DIR_OUTBOUND: break; default: ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n")); mhp->msg->sadb_msg_errno = EINVAL; return 0; } /* check policy */ /* key_spdadd() accepts DISCARD, NONE and IPSEC. */ if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) { ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n")); return key_senderror(so, m, EINVAL); } /* policy requests are mandatory when action is ipsec. */ if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) { ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n")); return key_senderror(so, m, EINVAL); } /* Process interfaces */ if (ipsecifopts != NULL) { if (ipsecifopts->sadb_x_ipsecif_internal_if[0]) { ifnet_find_by_name(ipsecifopts->sadb_x_ipsecif_internal_if, &internal_if); } if (ipsecifopts->sadb_x_ipsecif_outgoing_if[0]) { outgoing_if = ipsecifopts->sadb_x_ipsecif_outgoing_if; } if (ipsecifopts->sadb_x_ipsecif_ipsec_if[0]) { ipsec_if = ipsecifopts->sadb_x_ipsecif_ipsec_if; } init_disabled = ipsecifopts->sadb_x_ipsecif_init_disabled; } /* make secindex */ /* XXX boundary check against sa_len */ KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir, src0 + 1, dst0 + 1, src0->sadb_address_prefixlen, dst0->sadb_address_prefixlen, src0->sadb_address_proto, internal_if, use_src_range ? src0 + 1 : NULL, use_src_range ? src1 + 1 : NULL, use_dst_range ? dst0 + 1 : NULL, use_dst_range ? dst1 + 1 : NULL, &spidx); /* * checking there is SP already or not. * SPDUPDATE doesn't depend on whether there is a SP or not. * If the type is either SPDADD or SPDSETIDX AND a SP is found, * then error. */ lck_mtx_lock(sadb_mutex); newsp = key_getsp(&spidx); if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) { if (newsp) { newsp->state = IPSEC_SPSTATE_DEAD; key_freesp(newsp, KEY_SADB_LOCKED); } } else { if (newsp != NULL) { key_freesp(newsp, KEY_SADB_LOCKED); ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n")); lck_mtx_unlock(sadb_mutex); if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, EEXIST); } } lck_mtx_unlock(sadb_mutex); /* allocation new SP entry */ if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) { if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, error); } if ((newsp->id = key_getnewspid()) == 0) { keydb_delsecpolicy(newsp); if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, ENOBUFS); } /* XXX boundary check against sa_len */ KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir, src0 + 1, dst0 + 1, src0->sadb_address_prefixlen, dst0->sadb_address_prefixlen, src0->sadb_address_proto, internal_if, use_src_range ? src0 + 1 : NULL, use_src_range ? src1 + 1 : NULL, use_dst_range ? dst0 + 1 : NULL, use_dst_range ? dst1 + 1 : NULL, &newsp->spidx); #if 1 /* * allow IPv6 over IPv4 or IPv4 over IPv6 tunnels using ESP - * otherwise reject if inner and outer address families not equal */ if (newsp->req && newsp->req->saidx.src.ss_family) { struct sockaddr *sa; sa = (struct sockaddr *)(src0 + 1); if (sa->sa_family != newsp->req->saidx.src.ss_family) { if (newsp->req->saidx.mode != IPSEC_MODE_TUNNEL || newsp->req->saidx.proto != IPPROTO_ESP) { keydb_delsecpolicy(newsp); if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, EINVAL); } } } if (newsp->req && newsp->req->saidx.dst.ss_family) { struct sockaddr *sa; sa = (struct sockaddr *)(dst0 + 1); if (sa->sa_family != newsp->req->saidx.dst.ss_family) { if (newsp->req->saidx.mode != IPSEC_MODE_TUNNEL || newsp->req->saidx.proto != IPPROTO_ESP) { keydb_delsecpolicy(newsp); if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, EINVAL); } } } #endif microtime(&tv); newsp->created = tv.tv_sec; newsp->lastused = tv.tv_sec; newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0; newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0; if (outgoing_if != NULL) { ifnet_find_by_name(outgoing_if, &newsp->outgoing_if); } if (ipsec_if != NULL) { ifnet_find_by_name(ipsec_if, &newsp->ipsec_if); } if (init_disabled > 0) { newsp->disabled = 1; } newsp->refcnt = 1; /* do not reclaim until I say I do */ newsp->state = IPSEC_SPSTATE_ALIVE; lck_mtx_lock(sadb_mutex); /* * policies of type generate should be at the end of the SPD * because they function as default discard policies * Don't start timehandler for generate policies */ if (newsp->policy == IPSEC_POLICY_GENERATE) { LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain); } else { /* XXX until we have policy ordering in the kernel */ struct secpolicy *tmpsp; LIST_FOREACH(tmpsp, &sptree[newsp->spidx.dir], chain) if (tmpsp->policy == IPSEC_POLICY_GENERATE) { break; } if (tmpsp) { LIST_INSERT_BEFORE(tmpsp, newsp, chain); } else { LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain); } key_start_timehandler(); } ipsec_policy_count++; /* Turn off the ipsec bypass */ if (ipsec_bypass != 0) { ipsec_bypass = 0; } /* delete the entry in spacqtree */ if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) { struct secspacq *spacq; if ((spacq = key_getspacq(&spidx)) != NULL) { /* reset counter in order to deletion by timehandler. */ microtime(&tv); spacq->created = tv.tv_sec; spacq->count = 0; } } lck_mtx_unlock(sadb_mutex); { struct mbuf *n, *mpolicy; struct sadb_msg *newmsg; int off; /* create new sadb_msg to reply. */ if (lft) { int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_X_EXT_ADDR_RANGE_SRC_START, SADB_X_EXT_ADDR_RANGE_SRC_END, SADB_X_EXT_ADDR_RANGE_DST_START, SADB_X_EXT_ADDR_RANGE_DST_END}; n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems) / sizeof(int), mbufItems); } else { int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_X_EXT_ADDR_RANGE_SRC_START, SADB_X_EXT_ADDR_RANGE_SRC_END, SADB_X_EXT_ADDR_RANGE_DST_START, SADB_X_EXT_ADDR_RANGE_DST_END}; n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems) / sizeof(int), mbufItems); } if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(*newmsg)) { n = m_pullup(n, sizeof(*newmsg)); if (!n) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); off = 0; mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)), sizeof(*xpl), &off); if (mpolicy == NULL) { /* n is already freed */ return key_senderror(so, m, ENOBUFS); } xpl = (struct sadb_x_policy *)(void *)(mtod(mpolicy, caddr_t) + off); if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) { m_freem(n); return key_senderror(so, m, EINVAL); } xpl->sadb_x_policy_id = newsp->id; m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * get new policy id. * OUT: * 0: failure. * others: success. */ static u_int32_t key_getnewspid(void) { u_int32_t newid = 0; int count = key_spi_trycnt; /* XXX */ struct secpolicy *sp; /* when requesting to allocate spi ranged */ lck_mtx_lock(sadb_mutex); while (count--) { newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1)); if ((sp = __key_getspbyid(newid)) == NULL) { break; } key_freesp(sp, KEY_SADB_LOCKED); } lck_mtx_unlock(sadb_mutex); if (count == 0 || newid == 0) { ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n")); return 0; } return newid; } /* * SADB_SPDDELETE processing * receive * <base, address(SD), policy(*)> * from the user(?), and set SADB_SASTATE_DEAD, * and send, * <base, address(SD), policy(*)> * to the ikmpd. * policy(*) including direction of policy. * * m will always be freed. */ static int key_spddelete( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_address *src0, *dst0, *src1 = NULL, *dst1 = NULL; struct sadb_x_policy *xpl0; struct secpolicyindex spidx; struct secpolicy *sp; ifnet_t internal_if = NULL; struct sadb_x_ipsecif *ipsecifopts = NULL; int use_src_range = 0; int use_dst_range = 0; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spddelete: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_START] != NULL && mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_END] != NULL) { use_src_range = 1; } if (mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_START] != NULL && mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_END] != NULL) { use_dst_range = 1; } if ((!use_src_range && mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL) || (!use_dst_range && mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) || mhp->ext[SADB_X_EXT_POLICY] == NULL) { ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if ((use_src_range && (mhp->extlen[SADB_X_EXT_ADDR_RANGE_SRC_START] < sizeof(struct sadb_address) || mhp->extlen[SADB_X_EXT_ADDR_RANGE_SRC_END] < sizeof(struct sadb_address))) || (!use_src_range && mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address)) || (use_dst_range && (mhp->extlen[SADB_X_EXT_ADDR_RANGE_DST_START] < sizeof(struct sadb_address) || mhp->extlen[SADB_X_EXT_ADDR_RANGE_DST_END] < sizeof(struct sadb_address))) || (!use_dst_range && mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (use_src_range) { src0 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_START]; src1 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_SRC_END]; } else { src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC]; } if (use_dst_range) { dst0 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_START]; dst1 = (struct sadb_address *)mhp->ext[SADB_X_EXT_ADDR_RANGE_DST_END]; } else { dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST]; } xpl0 = (struct sadb_x_policy *)(void *)mhp->ext[SADB_X_EXT_POLICY]; ipsecifopts = (struct sadb_x_ipsecif *)(void *)mhp->ext[SADB_X_EXT_IPSECIF]; /* checking the direction. */ switch (xpl0->sadb_x_policy_dir) { case IPSEC_DIR_INBOUND: case IPSEC_DIR_OUTBOUND: break; default: ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n")); return key_senderror(so, m, EINVAL); } /* Process interfaces */ if (ipsecifopts != NULL) { if (ipsecifopts->sadb_x_ipsecif_internal_if[0]) { ifnet_find_by_name(ipsecifopts->sadb_x_ipsecif_internal_if, &internal_if); } } /* make secindex */ /* XXX boundary check against sa_len */ KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir, src0 + 1, dst0 + 1, src0->sadb_address_prefixlen, dst0->sadb_address_prefixlen, src0->sadb_address_proto, internal_if, use_src_range ? src0 + 1 : NULL, use_src_range ? src1 + 1 : NULL, use_dst_range ? dst0 + 1 : NULL, use_dst_range ? dst1 + 1 : NULL, &spidx); /* Is there SP in SPD ? */ lck_mtx_lock(sadb_mutex); if ((sp = key_getsp(&spidx)) == NULL) { ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n")); lck_mtx_unlock(sadb_mutex); if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } return key_senderror(so, m, EINVAL); } if (internal_if) { ifnet_release(internal_if); internal_if = NULL; } /* save policy id to buffer to be returned. */ xpl0->sadb_x_policy_id = sp->id; sp->state = IPSEC_SPSTATE_DEAD; key_freesp(sp, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_X_EXT_ADDR_RANGE_SRC_START, SADB_X_EXT_ADDR_RANGE_SRC_END, SADB_X_EXT_ADDR_RANGE_DST_START, SADB_X_EXT_ADDR_RANGE_DST_END}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * SADB_SPDDELETE2 processing * receive * <base, policy(*)> * from the user(?), and set SADB_SASTATE_DEAD, * and send, * <base, policy(*)> * to the ikmpd. * policy(*) including direction of policy. * * m will always be freed. */ static int key_spddelete2( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { u_int32_t id; struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spddelete2: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_POLICY] == NULL || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n")); key_senderror(so, m, EINVAL); return 0; } id = ((struct sadb_x_policy *) (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id; /* Is there SP in SPD ? */ lck_mtx_lock(sadb_mutex); if ((sp = __key_getspbyid(id)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id)); return key_senderror(so, m, EINVAL); } sp->state = IPSEC_SPSTATE_DEAD; key_freesp(sp, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); { struct mbuf *n, *nn; struct sadb_msg *newmsg; int off, len; /* create new sadb_msg to reply. */ len = PFKEY_ALIGN8(sizeof(struct sadb_msg)); if (len > MCLBYTES) { return key_senderror(so, m, ENOBUFS); } MGETHDR(n, M_WAITOK, MT_DATA); if (n && len > MHLEN) { MCLGET(n, M_WAITOK); if ((n->m_flags & M_EXT) == 0) { m_freem(n); n = NULL; } } if (!n) { return key_senderror(so, m, ENOBUFS); } n->m_len = len; n->m_next = NULL; off = 0; m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off); off += PFKEY_ALIGN8(sizeof(struct sadb_msg)); #if DIAGNOSTIC if (off != len) { panic("length inconsistency in key_spddelete2"); } #endif n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY], mhp->extlen[SADB_X_EXT_POLICY], M_WAITOK); if (!n->m_next) { m_freem(n); return key_senderror(so, m, ENOBUFS); } n->m_pkthdr.len = 0; for (nn = n; nn; nn = nn->m_next) { n->m_pkthdr.len += nn->m_len; } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } static int key_spdenable( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { u_int32_t id; struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spdenable: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_POLICY] == NULL || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spdenable: invalid message is passed.\n")); key_senderror(so, m, EINVAL); return 0; } id = ((struct sadb_x_policy *) (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id; /* Is there SP in SPD ? */ lck_mtx_lock(sadb_mutex); if ((sp = __key_getspbyid(id)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_spdenable: no SP found id:%u.\n", id)); return key_senderror(so, m, EINVAL); } sp->disabled = 0; lck_mtx_unlock(sadb_mutex); { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } static int key_spddisable( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { u_int32_t id; struct secpolicy *sp; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spddisable: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_POLICY] == NULL || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spddisable: invalid message is passed.\n")); key_senderror(so, m, EINVAL); return 0; } id = ((struct sadb_x_policy *) (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id; /* Is there SP in SPD ? */ lck_mtx_lock(sadb_mutex); if ((sp = __key_getspbyid(id)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_spddisable: no SP found id:%u.\n", id)); return key_senderror(so, m, EINVAL); } sp->disabled = 1; lck_mtx_unlock(sadb_mutex); { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * SADB_X_GET processing * receive * <base, policy(*)> * from the user(?), * and send, * <base, address(SD), policy> * to the ikmpd. * policy(*) including direction of policy. * * m will always be freed. */ static int key_spdget( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { u_int32_t id; struct secpolicy *sp; struct mbuf *n; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spdget: NULL pointer is passed.\n"); } if (mhp->ext[SADB_X_EXT_POLICY] == NULL || mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) { ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } id = ((struct sadb_x_policy *) (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id; /* Is there SP in SPD ? */ lck_mtx_lock(sadb_mutex); if ((sp = __key_getspbyid(id)) == NULL) { ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id)); lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, ENOENT); } lck_mtx_unlock(sadb_mutex); n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid); if (n != NULL) { m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ONE); } else { return key_senderror(so, m, ENOBUFS); } } /* * SADB_X_SPDACQUIRE processing. * Acquire policy and SA(s) for a *OUTBOUND* packet. * send * <base, policy(*)> * to KMD, and expect to receive * <base> with SADB_X_SPDACQUIRE if error occurred, * or * <base, policy> * with SADB_X_SPDUPDATE from KMD by PF_KEY. * policy(*) is without policy requests. * * 0 : succeed * others: error number */ int key_spdacquire( struct secpolicy *sp) { struct mbuf *result = NULL, *m; struct secspacq *newspacq; int error; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (sp == NULL) { panic("key_spdacquire: NULL pointer is passed.\n"); } if (sp->req != NULL) { panic("key_spdacquire: called but there is request.\n"); } if (sp->policy != IPSEC_POLICY_IPSEC) { panic("key_spdacquire: policy mismathed. IPsec is expected.\n"); } /* get a entry to check whether sent message or not. */ lck_mtx_lock(sadb_mutex); if ((newspacq = key_getspacq(&sp->spidx)) != NULL) { if (key_blockacq_count < newspacq->count) { /* reset counter and do send message. */ newspacq->count = 0; } else { /* increment counter and do nothing. */ newspacq->count++; lck_mtx_unlock(sadb_mutex); return 0; } } else { /* make new entry for blocking to send SADB_ACQUIRE. */ if ((newspacq = key_newspacq(&sp->spidx)) == NULL) { lck_mtx_unlock(sadb_mutex); return ENOBUFS; } /* add to acqtree */ LIST_INSERT_HEAD(&spacqtree, newspacq, chain); key_start_timehandler(); } lck_mtx_unlock(sadb_mutex); /* create new sadb_msg to reply. */ m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0); if (!m) { error = ENOBUFS; goto fail; } result = m; result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED); fail: if (result) { m_freem(result); } return error; } /* * SADB_SPDFLUSH processing * receive * <base> * from the user, and free all entries in secpctree. * and send, * <base> * to the user. * NOTE: what to do is only marking SADB_SASTATE_DEAD. * * m will always be freed. */ static int key_spdflush( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_msg *newmsg; struct secpolicy *sp; u_int dir; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spdflush: NULL pointer is passed.\n"); } if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg))) { return key_senderror(so, m, EINVAL); } lck_mtx_lock(sadb_mutex); for (dir = 0; dir < IPSEC_DIR_MAX; dir++) { LIST_FOREACH(sp, &sptree[dir], chain) { sp->state = IPSEC_SPSTATE_DEAD; } } lck_mtx_unlock(sadb_mutex); if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) { ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } if (m->m_next) { m_freem(m->m_next); } m->m_next = NULL; m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg)); newmsg = mtod(m, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len); return key_sendup_mbuf(so, m, KEY_SENDUP_ALL); } /* * SADB_SPDDUMP processing * receive * <base> * from the user, and dump all SP leaves * and send, * <base> ..... * to the ikmpd. * * m will always be freed. */ static int key_spddump( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct secpolicy *sp, **spbuf = NULL, **sp_ptr; int cnt = 0, bufcount; u_int dir; struct mbuf *n; int error = 0; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_spddump: NULL pointer is passed.\n"); } if ((bufcount = ipsec_policy_count) == 0) { error = ENOENT; goto end; } bufcount += 256; /* extra */ KMALLOC_WAIT(spbuf, struct secpolicy**, bufcount * sizeof(struct secpolicy*)); if (spbuf == NULL) { ipseclog((LOG_DEBUG, "key_spddump: No more memory.\n")); error = ENOMEM; goto end; } lck_mtx_lock(sadb_mutex); /* search SPD entry, make list. */ sp_ptr = spbuf; for (dir = 0; dir < IPSEC_DIR_MAX; dir++) { LIST_FOREACH(sp, &sptree[dir], chain) { if (cnt == bufcount) { break; /* buffer full */ } *sp_ptr++ = sp; sp->refcnt++; cnt++; } } lck_mtx_unlock(sadb_mutex); if (cnt == 0) { error = ENOENT; goto end; } sp_ptr = spbuf; while (cnt) { --cnt; n = key_setdumpsp(*sp_ptr++, SADB_X_SPDDUMP, cnt, mhp->msg->sadb_msg_pid); if (n) { key_sendup_mbuf(so, n, KEY_SENDUP_ONE); } } lck_mtx_lock(sadb_mutex); while (sp_ptr > spbuf) { key_freesp(*(--sp_ptr), KEY_SADB_LOCKED); } lck_mtx_unlock(sadb_mutex); end: if (spbuf) { KFREE(spbuf); } if (error) { return key_senderror(so, m, error); } m_freem(m); return 0; } static struct mbuf * key_setdumpsp( struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid) { struct mbuf *result = NULL, *m; m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt); if (!m) { goto fail; } result = m; if (sp->spidx.src_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_START, (struct sockaddr *)&sp->spidx.src_range.start, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_END, (struct sockaddr *)&sp->spidx.src_range.end, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } if (sp->spidx.dst_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_START, (struct sockaddr *)&sp->spidx.dst_range.start, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_END, (struct sockaddr *)&sp->spidx.dst_range.end, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } if (sp->spidx.internal_if || sp->outgoing_if || sp->ipsec_if || sp->disabled) { m = key_setsadbipsecif(sp->spidx.internal_if, sp->outgoing_if, sp->ipsec_if, sp->disabled); if (!m) { goto fail; } m_cat(result, m); } m = key_sp2msg(sp); if (!m) { goto fail; } m_cat(result, m); if ((result->m_flags & M_PKTHDR) == 0) { goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return result; fail: m_freem(result); return NULL; } /* * get PFKEY message length for security policy and request. */ static u_int key_getspreqmsglen( struct secpolicy *sp) { u_int tlen; tlen = sizeof(struct sadb_x_policy); /* if is the policy for ipsec ? */ if (sp->policy != IPSEC_POLICY_IPSEC) { return tlen; } /* get length of ipsec requests */ { struct ipsecrequest *isr; int len; for (isr = sp->req; isr != NULL; isr = isr->next) { len = sizeof(struct sadb_x_ipsecrequest) + isr->saidx.src.ss_len + isr->saidx.dst.ss_len; tlen += PFKEY_ALIGN8(len); } } return tlen; } /* * SADB_SPDEXPIRE processing * send * <base, address(SD), lifetime(CH), policy> * to KMD by PF_KEY. * * OUT: 0 : succeed * others : error number */ static int key_spdexpire( struct secpolicy *sp) { struct mbuf *result = NULL, *m; int len; int error = EINVAL; struct sadb_lifetime *lt; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (sp == NULL) { panic("key_spdexpire: NULL pointer is passed.\n"); } /* set msg header */ m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0); if (!m) { error = ENOBUFS; goto fail; } result = m; /* create lifetime extension (current and hard) */ len = PFKEY_ALIGN8(sizeof(*lt)) * 2; m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } error = ENOBUFS; goto fail; } bzero(mtod(m, caddr_t), len); lt = mtod(m, struct sadb_lifetime *); lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lt->sadb_lifetime_allocations = 0; lt->sadb_lifetime_bytes = 0; lt->sadb_lifetime_addtime = sp->created; lt->sadb_lifetime_usetime = sp->lastused; lt = (struct sadb_lifetime *)(void *)(mtod(m, caddr_t) + len / 2); lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lt->sadb_lifetime_allocations = 0; lt->sadb_lifetime_bytes = 0; lt->sadb_lifetime_addtime = sp->lifetime; lt->sadb_lifetime_usetime = sp->validtime; m_cat(result, m); /* set sadb_address(es) for source */ if (sp->spidx.src_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_START, (struct sockaddr *)&sp->spidx.src_range.start, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_END, (struct sockaddr *)&sp->spidx.src_range.end, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); } /* set sadb_address(es) for dest */ if (sp->spidx.dst_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_START, (struct sockaddr *)&sp->spidx.dst_range.start, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_END, (struct sockaddr *)&sp->spidx.dst_range.end, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); } /* set secpolicy */ m = key_sp2msg(sp); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); if ((result->m_flags & M_PKTHDR) == 0) { error = EINVAL; goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { error = ENOBUFS; goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED); fail: if (result) { m_freem(result); } return error; } /* %%% SAD management */ /* * allocating a memory for new SA head, and copy from the values of mhp. * OUT: NULL : failure due to the lack of memory. * others : pointer to new SA head. */ static struct secashead * key_newsah(struct secasindex *saidx, ifnet_t ipsec_if, u_int outgoing_if, u_int8_t dir) { struct secashead *newsah; /* sanity check */ if (saidx == NULL) { panic("key_newsaidx: NULL pointer is passed.\n"); } newsah = keydb_newsecashead(); if (newsah == NULL) { return NULL; } bcopy(saidx, &newsah->saidx, sizeof(newsah->saidx)); /* remove the ports */ switch (saidx->src.ss_family) { case AF_INET: ((struct sockaddr_in *)(&newsah->saidx.src))->sin_port = IPSEC_PORT_ANY; break; case AF_INET6: ((struct sockaddr_in6 *)(&newsah->saidx.src))->sin6_port = IPSEC_PORT_ANY; break; default: break; } switch (saidx->dst.ss_family) { case AF_INET: ((struct sockaddr_in *)(&newsah->saidx.dst))->sin_port = IPSEC_PORT_ANY; break; case AF_INET6: ((struct sockaddr_in6 *)(&newsah->saidx.dst))->sin6_port = IPSEC_PORT_ANY; break; default: break; } newsah->outgoing_if = outgoing_if; if (ipsec_if) { ifnet_reference(ipsec_if); newsah->ipsec_if = ipsec_if; } newsah->dir = dir; /* add to saidxtree */ newsah->state = SADB_SASTATE_MATURE; LIST_INSERT_HEAD(&sahtree, newsah, chain); key_start_timehandler(); return newsah; } /* * delete SA index and all SA registerd. */ void key_delsah( struct secashead *sah) { struct secasvar *sav, *nextsav; u_int stateidx, state; int zombie = 0; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (sah == NULL) { panic("key_delsah: NULL pointer is passed.\n"); } /* searching all SA registerd in the secindex. */ for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_any); stateidx++) { state = saorder_state_any[stateidx]; for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); if (sav->refcnt > 0) { /* give up to delete this sa */ zombie++; continue; } /* sanity check */ KEY_CHKSASTATE(state, sav->state, "key_delsah"); key_freesav(sav, KEY_SADB_LOCKED); /* remove back pointer */ sav->sah = NULL; sav = NULL; } } /* don't delete sah only if there are savs. */ if (zombie) { return; } ROUTE_RELEASE(&sah->sa_route); if (sah->ipsec_if) { ifnet_release(sah->ipsec_if); sah->ipsec_if = NULL; } if (sah->idents) { KFREE(sah->idents); } if (sah->identd) { KFREE(sah->identd); } /* remove from tree of SA index */ if (__LIST_CHAINED(sah)) { LIST_REMOVE(sah, chain); } KFREE(sah); return; } /* * allocating a new SA with LARVAL state. key_add() and key_getspi() call, * and copy the values of mhp into new buffer. * When SAD message type is GETSPI: * to set sequence number from acq_seq++, * to set zero to SPI. * not to call key_setsava(). * OUT: NULL : fail * others : pointer to new secasvar. * * does not modify mbuf. does not free mbuf on error. */ static struct secasvar * key_newsav( struct mbuf *m, const struct sadb_msghdr *mhp, struct secashead *sah, int *errp, struct socket *so) { struct secasvar *newsav; const struct sadb_sa *xsa; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL) { panic("key_newsa: NULL pointer is passed.\n"); } KMALLOC_NOWAIT(newsav, struct secasvar *, sizeof(struct secasvar)); if (newsav == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(newsav, struct secasvar *, sizeof(struct secasvar)); lck_mtx_lock(sadb_mutex); if (newsav == NULL) { ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n")); *errp = ENOBUFS; return NULL; } } bzero((caddr_t)newsav, sizeof(struct secasvar)); switch (mhp->msg->sadb_msg_type) { case SADB_GETSPI: key_setspi(newsav, 0); #if IPSEC_DOSEQCHECK /* sync sequence number */ if (mhp->msg->sadb_msg_seq == 0) { newsav->seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq)); } else #endif newsav->seq = mhp->msg->sadb_msg_seq; break; case SADB_ADD: /* sanity check */ if (mhp->ext[SADB_EXT_SA] == NULL) { key_delsav(newsav); ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n")); *errp = EINVAL; return NULL; } xsa = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; key_setspi(newsav, xsa->sadb_sa_spi); newsav->seq = mhp->msg->sadb_msg_seq; break; default: key_delsav(newsav); *errp = EINVAL; return NULL; } if (mhp->ext[SADB_X_EXT_SA2] != NULL) { if (((struct sadb_x_sa2 *)(void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_alwaysexpire) { newsav->always_expire = 1; } newsav->flags2 = ((struct sadb_x_sa2 *)(void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_flags; if (newsav->flags2 & SADB_X_EXT_SA2_DELETE_ON_DETACH) { newsav->so = so; } } /* copy sav values */ if (mhp->msg->sadb_msg_type != SADB_GETSPI) { *errp = key_setsaval(newsav, m, mhp); if (*errp) { key_delsav(newsav); return NULL; } } else { /* For get SPI, if has a hard lifetime, apply */ const struct sadb_lifetime *lft0; struct timeval tv; lft0 = (struct sadb_lifetime *)(void *)mhp->ext[SADB_EXT_LIFETIME_HARD]; if (lft0 != NULL) { /* make lifetime for CURRENT */ KMALLOC_NOWAIT(newsav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); if (newsav->lft_c == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(newsav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); lck_mtx_lock(sadb_mutex); if (newsav->lft_c == NULL) { ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n")); key_delsav(newsav); *errp = ENOBUFS; return NULL; } } microtime(&tv); newsav->lft_c->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); newsav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; newsav->lft_c->sadb_lifetime_allocations = 0; newsav->lft_c->sadb_lifetime_bytes = 0; newsav->lft_c->sadb_lifetime_addtime = tv.tv_sec; newsav->lft_c->sadb_lifetime_usetime = 0; if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) { ipseclog((LOG_DEBUG, "key_newsa: invalid hard lifetime ext len.\n")); key_delsav(newsav); *errp = EINVAL; return NULL; } newsav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0, sizeof(*lft0)); if (newsav->lft_h == NULL) { ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n")); key_delsav(newsav); *errp = ENOBUFS; return NULL; } } } /* reset created */ { struct timeval tv; microtime(&tv); newsav->created = tv.tv_sec; } newsav->pid = mhp->msg->sadb_msg_pid; /* add to satree */ newsav->sah = sah; newsav->refcnt = 1; newsav->state = SADB_SASTATE_LARVAL; LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav, secasvar, chain); ipsec_sav_count++; ipsec_monitor_sleep_wake(); return newsav; } /* * allocating a new SA with LARVAL state. key_add() and key_getspi() call, * and copy the values passed into new buffer. * When SAD message type is GETSPI: * to set sequence number from acq_seq++, * to set zero to SPI. * not to call key_setsava(). * OUT: NULL : fail * others : pointer to new secasvar. */ struct secasvar * key_newsav2(struct secashead *sah, u_int8_t satype, u_int8_t alg_auth, u_int8_t alg_enc, u_int32_t flags, u_int8_t replay, struct sadb_key *key_auth, u_int16_t key_auth_len, struct sadb_key *key_enc, u_int16_t key_enc_len, u_int16_t natt_port, u_int32_t seq, u_int32_t spi, u_int32_t pid, struct sadb_lifetime *lifetime_hard, struct sadb_lifetime *lifetime_soft) { struct secasvar *newsav; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (sah == NULL) { panic("key_newsa: NULL pointer is passed.\n"); } KMALLOC_NOWAIT(newsav, struct secasvar *, sizeof(struct secasvar)); if (newsav == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(newsav, struct secasvar *, sizeof(struct secasvar)); lck_mtx_lock(sadb_mutex); if (newsav == NULL) { ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n")); return NULL; } } bzero((caddr_t)newsav, sizeof(struct secasvar)); #if IPSEC_DOSEQCHECK /* sync sequence number */ if (seq == 0) { newsav->seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq)); } else #endif newsav->seq = seq; key_setspi(newsav, spi); if (key_setsaval2(newsav, satype, alg_auth, alg_enc, flags, replay, key_auth, key_auth_len, key_enc, key_enc_len, natt_port, seq, spi, pid, lifetime_hard, lifetime_soft)) { key_delsav(newsav); return NULL; } /* reset created */ { struct timeval tv; microtime(&tv); newsav->created = tv.tv_sec; } newsav->pid = pid; /* add to satree */ newsav->sah = sah; newsav->refcnt = 1; if (spi && key_auth && key_auth_len && key_enc && key_enc_len) { newsav->state = SADB_SASTATE_MATURE; LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_MATURE], newsav, secasvar, chain); } else { newsav->state = SADB_SASTATE_LARVAL; LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav, secasvar, chain); } ipsec_sav_count++; return newsav; } static int key_migratesav(struct secasvar *sav, struct secashead *newsah) { if (sav == NULL || newsah == NULL || sav->state != SADB_SASTATE_MATURE) { return EINVAL; } /* remove from SA header */ if (__LIST_CHAINED(sav)) { LIST_REMOVE(sav, chain); } sav->sah = newsah; LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_MATURE], sav, secasvar, chain); return 0; } /* * free() SA variable entry. */ void key_delsav( struct secasvar *sav) { LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (sav == NULL) { panic("key_delsav: NULL pointer is passed.\n"); } if (sav->refcnt > 0) { return; /* can't free */ } /* remove from SA header */ if (__LIST_CHAINED(sav)) { LIST_REMOVE(sav, chain); ipsec_sav_count--; } if (sav->spihash.le_prev || sav->spihash.le_next) { LIST_REMOVE(sav, spihash); } if (sav->key_auth != NULL) { bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); KFREE(sav->key_auth); sav->key_auth = NULL; } if (sav->key_enc != NULL) { bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc)); KFREE(sav->key_enc); sav->key_enc = NULL; } if (sav->sched) { bzero(sav->sched, sav->schedlen); KFREE(sav->sched); sav->sched = NULL; } for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { if (sav->replay[i] != NULL) { keydb_delsecreplay(sav->replay[i]); sav->replay[i] = NULL; } } if (sav->lft_c != NULL) { KFREE(sav->lft_c); sav->lft_c = NULL; } if (sav->lft_h != NULL) { KFREE(sav->lft_h); sav->lft_h = NULL; } if (sav->lft_s != NULL) { KFREE(sav->lft_s); sav->lft_s = NULL; } if (sav->iv != NULL) { KFREE(sav->iv); sav->iv = NULL; } KFREE(sav); return; } /* * search SAD. * OUT: * NULL : not found * others : found, pointer to a SA. */ static struct secashead * key_getsah(struct secasindex *saidx) { struct secashead *sah; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID)) { return sah; } } return NULL; } struct secashead * key_newsah2(struct secasindex *saidx, u_int8_t dir) { struct secashead *sah; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); sah = key_getsah(saidx); if (!sah) { return key_newsah(saidx, NULL, 0, dir); } return sah; } /* * check not to be duplicated SPI. * NOTE: this function is too slow due to searching all SAD. * OUT: * NULL : not found * others : found, pointer to a SA. */ static struct secasvar * key_checkspidup( struct secasindex *saidx, u_int32_t spi) { struct secasvar *sav; u_int stateidx, state; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* check address family */ if (saidx->src.ss_family != saidx->dst.ss_family) { ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n")); return NULL; } /* check all SAD */ LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) { if (sav->spi != spi) { continue; } for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { state = saorder_state_alive[stateidx]; if (sav->state == state && key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst)) { return sav; } } } return NULL; } static void key_setspi( struct secasvar *sav, u_int32_t spi) { LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); sav->spi = spi; if (sav->spihash.le_prev || sav->spihash.le_next) { LIST_REMOVE(sav, spihash); } LIST_INSERT_HEAD(&spihash[SPIHASH(spi)], sav, spihash); } /* * search SAD litmited alive SA, protocol, SPI. * OUT: * NULL : not found * others : found, pointer to a SA. */ static struct secasvar * key_getsavbyspi( struct secashead *sah, u_int32_t spi) { struct secasvar *sav, *match; u_int stateidx, state, matchidx; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); match = NULL; matchidx = _ARRAYLEN(saorder_state_alive); LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) { if (sav->spi != spi) { continue; } if (sav->sah != sah) { continue; } for (stateidx = 0; stateidx < matchidx; stateidx++) { state = saorder_state_alive[stateidx]; if (sav->state == state) { match = sav; matchidx = stateidx; break; } } } return match; } /* * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*. * You must update these if need. * OUT: 0: success. * !0: failure. * * does not modify mbuf. does not free mbuf on error. */ static int key_setsaval( struct secasvar *sav, struct mbuf *m, const struct sadb_msghdr *mhp) { #if IPSEC_ESP const struct esp_algorithm *algo; #endif int error = 0; struct timeval tv; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_setsaval: NULL pointer is passed.\n"); } /* initialization */ for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { sav->replay[i] = NULL; } sav->key_auth = NULL; sav->key_enc = NULL; sav->sched = NULL; sav->schedlen = 0; sav->iv = NULL; sav->lft_c = NULL; sav->lft_h = NULL; sav->lft_s = NULL; sav->remote_ike_port = 0; sav->natt_last_activity = natt_now; sav->natt_encapsulated_src_port = 0; /* SA */ if (mhp->ext[SADB_EXT_SA] != NULL) { const struct sadb_sa *sa0; sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) { ipseclog((LOG_DEBUG, "key_setsaval: invalid message size.\n")); error = EINVAL; goto fail; } sav->alg_auth = sa0->sadb_sa_auth; sav->alg_enc = sa0->sadb_sa_encrypt; sav->flags = sa0->sadb_sa_flags; /* * Verify that a nat-traversal port was specified if * the nat-traversal flag is set. */ if ((sav->flags & SADB_X_EXT_NATT) != 0) { if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa_2) || ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_port == 0) { ipseclog((LOG_DEBUG, "key_setsaval: natt port not set.\n")); error = EINVAL; goto fail; } sav->natt_encapsulated_src_port = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_src_port; sav->remote_ike_port = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_port; sav->natt_interval = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_interval; sav->natt_offload_interval = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_offload_interval; } /* * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that * SADB_X_EXT_NATT is set and SADB_X_EXT_NATT_KEEPALIVE is not * set (we're not behind nat) - otherwise clear it. */ if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) { if ((sav->flags & SADB_X_EXT_NATT) == 0 || (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0) { sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS; } } /* replay window */ if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) { if ((sav->flags2 & SADB_X_EXT_SA2_SEQ_PER_TRAFFIC_CLASS) == SADB_X_EXT_SA2_SEQ_PER_TRAFFIC_CLASS) { uint32_t range = (1ULL << (sizeof(((struct secreplay *)0)->count) * 8)) / MAX_REPLAY_WINDOWS; for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { sav->replay[i] = keydb_newsecreplay(sa0->sadb_sa_replay); if (sav->replay[i] == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* Allowed range for sequence per traffic class */ sav->replay[i]->count = i * range; sav->replay[i]->lastseq = ((i + 1) * range) - 1; } } else { sav->replay[0] = keydb_newsecreplay(sa0->sadb_sa_replay); if (sav->replay[0] == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } sav->replay[0]->lastseq = ~0; } } } /* Authentication keys */ if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) { const struct sadb_key *key0; int len; key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH]; len = mhp->extlen[SADB_EXT_KEY_AUTH]; error = 0; if (len < sizeof(*key0)) { ipseclog((LOG_DEBUG, "key_setsaval: invalid auth key ext len. len = %d\n", len)); error = EINVAL; goto fail; } switch (mhp->msg->sadb_msg_satype) { case SADB_SATYPE_AH: case SADB_SATYPE_ESP: if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) && sav->alg_auth != SADB_X_AALG_NULL) { error = EINVAL; } break; default: error = EINVAL; break; } if (error) { ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n")); goto fail; } sav->key_auth = (struct sadb_key *)key_newbuf(key0, len); if (sav->key_auth == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } } /* Encryption key */ if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) { const struct sadb_key *key0; int len; key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT]; len = mhp->extlen[SADB_EXT_KEY_ENCRYPT]; error = 0; if (len < sizeof(*key0)) { ipseclog((LOG_DEBUG, "key_setsaval: invalid encryption key ext len. len = %d\n", len)); error = EINVAL; goto fail; } switch (mhp->msg->sadb_msg_satype) { case SADB_SATYPE_ESP: if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) && sav->alg_enc != SADB_EALG_NULL) { ipseclog((LOG_DEBUG, "key_setsaval: invalid ESP algorithm.\n")); error = EINVAL; break; } sav->key_enc = (struct sadb_key *)key_newbuf(key0, len); if (sav->key_enc == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } break; case SADB_SATYPE_AH: default: error = EINVAL; break; } if (error) { ipseclog((LOG_DEBUG, "key_setsaval: invalid key_enc value.\n")); goto fail; } } /* set iv */ sav->ivlen = 0; switch (mhp->msg->sadb_msg_satype) { case SADB_SATYPE_ESP: #if IPSEC_ESP algo = esp_algorithm_lookup(sav->alg_enc); if (algo && algo->ivlen) { sav->ivlen = (*algo->ivlen)(algo, sav); } if (sav->ivlen == 0) { break; } KMALLOC_NOWAIT(sav->iv, caddr_t, sav->ivlen); if (sav->iv == 0) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sav->iv, caddr_t, sav->ivlen); lck_mtx_lock(sadb_mutex); if (sav->iv == 0) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } } /* initialize */ if (sav->alg_enc == SADB_X_EALG_AES_GCM) { bzero(sav->iv, sav->ivlen); } else { key_randomfill(sav->iv, sav->ivlen); } #endif break; case SADB_SATYPE_AH: break; default: ipseclog((LOG_DEBUG, "key_setsaval: invalid SA type.\n")); error = EINVAL; goto fail; } /* reset created */ microtime(&tv); sav->created = tv.tv_sec; /* make lifetime for CURRENT */ KMALLOC_NOWAIT(sav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); if (sav->lft_c == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); lck_mtx_lock(sadb_mutex); if (sav->lft_c == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } } microtime(&tv); sav->lft_c->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; sav->lft_c->sadb_lifetime_allocations = 0; sav->lft_c->sadb_lifetime_bytes = 0; sav->lft_c->sadb_lifetime_addtime = tv.tv_sec; sav->lft_c->sadb_lifetime_usetime = 0; /* lifetimes for HARD and SOFT */ { const struct sadb_lifetime *lft0; lft0 = (struct sadb_lifetime *) (void *)mhp->ext[SADB_EXT_LIFETIME_HARD]; if (lft0 != NULL) { if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) { ipseclog((LOG_DEBUG, "key_setsaval: invalid hard lifetime ext len.\n")); error = EINVAL; goto fail; } sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0, sizeof(*lft0)); if (sav->lft_h == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* to be initialize ? */ } lft0 = (struct sadb_lifetime *) (void *)mhp->ext[SADB_EXT_LIFETIME_SOFT]; if (lft0 != NULL) { if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) { ipseclog((LOG_DEBUG, "key_setsaval: invalid soft lifetime ext len.\n")); error = EINVAL; goto fail; } sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0, sizeof(*lft0)); if (sav->lft_s == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* to be initialize ? */ } } return 0; fail: /* initialization */ for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { if (sav->replay[i] != NULL) { keydb_delsecreplay(sav->replay[i]); sav->replay[i] = NULL; } } if (sav->key_auth != NULL) { bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); KFREE(sav->key_auth); sav->key_auth = NULL; } if (sav->key_enc != NULL) { bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc)); KFREE(sav->key_enc); sav->key_enc = NULL; } if (sav->sched) { bzero(sav->sched, sav->schedlen); KFREE(sav->sched); sav->sched = NULL; } if (sav->iv != NULL) { KFREE(sav->iv); sav->iv = NULL; } if (sav->lft_c != NULL) { KFREE(sav->lft_c); sav->lft_c = NULL; } if (sav->lft_h != NULL) { KFREE(sav->lft_h); sav->lft_h = NULL; } if (sav->lft_s != NULL) { KFREE(sav->lft_s); sav->lft_s = NULL; } return error; } /* * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*. * You must update these if need. * OUT: 0: success. * !0: failure. * * does not modify mbuf. does not free mbuf on error. */ int key_setsaval2(struct secasvar *sav, u_int8_t satype, u_int8_t alg_auth, u_int8_t alg_enc, u_int32_t flags, u_int8_t replay, struct sadb_key *key_auth, u_int16_t key_auth_len, struct sadb_key *key_enc, u_int16_t key_enc_len, u_int16_t natt_port, u_int32_t seq, u_int32_t spi, u_int32_t pid, struct sadb_lifetime *lifetime_hard, struct sadb_lifetime *lifetime_soft) { #if IPSEC_ESP const struct esp_algorithm *algo; #endif int error = 0; struct timeval tv; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* initialization */ for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { sav->replay[i] = NULL; } sav->key_auth = NULL; sav->key_enc = NULL; sav->sched = NULL; sav->schedlen = 0; sav->iv = NULL; sav->lft_c = NULL; sav->lft_h = NULL; sav->lft_s = NULL; sav->remote_ike_port = 0; sav->natt_last_activity = natt_now; sav->natt_encapsulated_src_port = 0; sav->alg_auth = alg_auth; sav->alg_enc = alg_enc; sav->flags = flags; sav->pid = pid; sav->seq = seq; key_setspi(sav, htonl(spi)); /* * Verify that a nat-traversal port was specified if * the nat-traversal flag is set. */ if ((sav->flags & SADB_X_EXT_NATT) != 0) { if (natt_port == 0) { ipseclog((LOG_DEBUG, "key_setsaval2: natt port not set.\n")); error = EINVAL; goto fail; } sav->remote_ike_port = natt_port; } /* * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that * SADB_X_EXT_NATT is set and SADB_X_EXT_NATT_KEEPALIVE is not * set (we're not behind nat) - otherwise clear it. */ if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) { if ((sav->flags & SADB_X_EXT_NATT) == 0 || (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0) { sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS; } } /* replay window */ if ((flags & SADB_X_EXT_OLD) == 0) { if ((sav->flags2 & SADB_X_EXT_SA2_SEQ_PER_TRAFFIC_CLASS) == SADB_X_EXT_SA2_SEQ_PER_TRAFFIC_CLASS) { uint32_t range = (1ULL << (sizeof(((struct secreplay *)0)->count) * 8)) / MAX_REPLAY_WINDOWS; for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { sav->replay[i] = keydb_newsecreplay(replay); if (sav->replay[i] == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* Allowed range for sequence per traffic class */ sav->replay[i]->count = i * range; sav->replay[i]->lastseq = ((i + 1) * range) - 1; } } else { sav->replay[0] = keydb_newsecreplay(replay); if (sav->replay[0] == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } sav->replay[0]->lastseq = ~0; } } /* Authentication keys */ sav->key_auth = (__typeof__(sav->key_auth))key_newbuf(key_auth, key_auth_len); if (sav->key_auth == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* Encryption key */ sav->key_enc = (__typeof__(sav->key_enc))key_newbuf(key_enc, key_enc_len); if (sav->key_enc == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } /* set iv */ sav->ivlen = 0; if (satype == SADB_SATYPE_ESP) { #if IPSEC_ESP algo = esp_algorithm_lookup(sav->alg_enc); if (algo && algo->ivlen) { sav->ivlen = (*algo->ivlen)(algo, sav); } if (sav->ivlen != 0) { KMALLOC_NOWAIT(sav->iv, caddr_t, sav->ivlen); if (sav->iv == 0) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sav->iv, caddr_t, sav->ivlen); lck_mtx_lock(sadb_mutex); if (sav->iv == 0) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } } /* initialize */ if (sav->alg_enc == SADB_X_EALG_AES_GCM) { bzero(sav->iv, sav->ivlen); } else { key_randomfill(sav->iv, sav->ivlen); } } #endif } /* reset created */ microtime(&tv); sav->created = tv.tv_sec; /* make lifetime for CURRENT */ KMALLOC_NOWAIT(sav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); if (sav->lft_c == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sav->lft_c, struct sadb_lifetime *, sizeof(struct sadb_lifetime)); lck_mtx_lock(sadb_mutex); if (sav->lft_c == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } } microtime(&tv); sav->lft_c->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; sav->lft_c->sadb_lifetime_allocations = 0; sav->lft_c->sadb_lifetime_bytes = 0; sav->lft_c->sadb_lifetime_addtime = tv.tv_sec; sav->lft_c->sadb_lifetime_usetime = 0; /* lifetimes for HARD and SOFT */ sav->lft_h = (__typeof__(sav->lft_h))key_newbuf(lifetime_hard, sizeof(*lifetime_hard)); if (sav->lft_h == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } sav->lft_s = (__typeof__(sav->lft_s))key_newbuf(lifetime_soft, sizeof(*lifetime_soft)); if (sav->lft_s == NULL) { ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n")); error = ENOBUFS; goto fail; } return 0; fail: /* initialization */ for (int i = 0; i < MAX_REPLAY_WINDOWS; i++) { if (sav->replay[i] != NULL) { keydb_delsecreplay(sav->replay[i]); sav->replay[i] = NULL; } } if (sav->key_auth != NULL) { bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth)); KFREE(sav->key_auth); sav->key_auth = NULL; } if (sav->key_enc != NULL) { bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc)); KFREE(sav->key_enc); sav->key_enc = NULL; } if (sav->sched) { bzero(sav->sched, sav->schedlen); KFREE(sav->sched); sav->sched = NULL; } if (sav->iv != NULL) { KFREE(sav->iv); sav->iv = NULL; } if (sav->lft_c != NULL) { KFREE(sav->lft_c); sav->lft_c = NULL; } if (sav->lft_h != NULL) { KFREE(sav->lft_h); sav->lft_h = NULL; } if (sav->lft_s != NULL) { KFREE(sav->lft_s); sav->lft_s = NULL; } return error; } /* * validation with a secasvar entry, and set SADB_SATYPE_MATURE. * OUT: 0: valid * other: errno */ static int key_mature( struct secasvar *sav) { int mature; int checkmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */ int mustmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */ mature = 0; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* check SPI value */ switch (sav->sah->saidx.proto) { case IPPROTO_ESP: case IPPROTO_AH: /* No reason to test if this is >= 0, because ntohl(sav->spi) is unsigned. */ if (ntohl(sav->spi) <= 255) { ipseclog((LOG_DEBUG, "key_mature: illegal range of SPI %u.\n", (u_int32_t)ntohl(sav->spi))); return EINVAL; } break; } /* check satype */ switch (sav->sah->saidx.proto) { case IPPROTO_ESP: /* check flags */ if ((sav->flags & SADB_X_EXT_OLD) && (sav->flags & SADB_X_EXT_DERIV)) { ipseclog((LOG_DEBUG, "key_mature: " "invalid flag (derived) given to old-esp.\n")); return EINVAL; } if (sav->alg_auth == SADB_AALG_NONE) { checkmask = 1; } else { checkmask = 3; } mustmask = 1; break; case IPPROTO_AH: /* check flags */ if (sav->flags & SADB_X_EXT_DERIV) { ipseclog((LOG_DEBUG, "key_mature: " "invalid flag (derived) given to AH SA.\n")); return EINVAL; } if (sav->alg_enc != SADB_EALG_NONE) { ipseclog((LOG_DEBUG, "key_mature: " "protocol and algorithm mismated.\n")); return EINVAL; } checkmask = 2; mustmask = 2; break; default: ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n")); return EPROTONOSUPPORT; } /* check authentication algorithm */ if ((checkmask & 2) != 0) { const struct ah_algorithm *algo; int keylen; algo = ah_algorithm_lookup(sav->alg_auth); if (!algo) { ipseclog((LOG_DEBUG, "key_mature: " "unknown authentication algorithm.\n")); return EINVAL; } /* algorithm-dependent check */ if (sav->key_auth) { keylen = sav->key_auth->sadb_key_bits; } else { keylen = 0; } if (keylen < algo->keymin || algo->keymax < keylen) { ipseclog((LOG_DEBUG, "key_mature: invalid AH key length %d " "(%d-%d allowed)\n", keylen, algo->keymin, algo->keymax)); return EINVAL; } if (algo->mature) { if ((*algo->mature)(sav)) { /* message generated in per-algorithm function*/ return EINVAL; } else { mature = SADB_SATYPE_AH; } } if ((mustmask & 2) != 0 && mature != SADB_SATYPE_AH) { ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for AH\n")); return EINVAL; } } /* check encryption algorithm */ if ((checkmask & 1) != 0) { #if IPSEC_ESP const struct esp_algorithm *algo; int keylen; algo = esp_algorithm_lookup(sav->alg_enc); if (!algo) { ipseclog((LOG_DEBUG, "key_mature: unknown encryption algorithm.\n")); return EINVAL; } /* algorithm-dependent check */ if (sav->key_enc) { keylen = sav->key_enc->sadb_key_bits; } else { keylen = 0; } if (keylen < algo->keymin || algo->keymax < keylen) { ipseclog((LOG_DEBUG, "key_mature: invalid ESP key length %d " "(%d-%d allowed)\n", keylen, algo->keymin, algo->keymax)); return EINVAL; } if (algo->mature) { if ((*algo->mature)(sav)) { /* message generated in per-algorithm function*/ return EINVAL; } else { mature = SADB_SATYPE_ESP; } } if ((mustmask & 1) != 0 && mature != SADB_SATYPE_ESP) { ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for ESP\n")); return EINVAL; } #else /*IPSEC_ESP*/ ipseclog((LOG_DEBUG, "key_mature: ESP not supported in this configuration\n")); return EINVAL; #endif } key_sa_chgstate(sav, SADB_SASTATE_MATURE); return 0; } /* * subroutine for SADB_GET and SADB_DUMP. */ static struct mbuf * key_setdumpsa( struct secasvar *sav, u_int8_t type, u_int8_t satype, u_int32_t seq, u_int32_t pid) { struct mbuf *result = NULL, *tres = NULL, *m; int l = 0; int i; void *p; int dumporder[] = { SADB_EXT_SA, SADB_X_EXT_SA2, SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT, SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY, }; m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt); if (m == NULL) { goto fail; } result = m; for (i = sizeof(dumporder) / sizeof(dumporder[0]) - 1; i >= 0; i--) { m = NULL; p = NULL; switch (dumporder[i]) { case SADB_EXT_SA: m = key_setsadbsa(sav); if (!m) { goto fail; } break; case SADB_X_EXT_SA2: m = key_setsadbxsa2(sav->sah->saidx.mode, sav->replay[0] ? sav->replay[0]->count : 0, sav->sah->saidx.reqid, sav->flags2); if (!m) { goto fail; } break; case SADB_EXT_ADDRESS_SRC: m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sav->sah->saidx.src, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { goto fail; } break; case SADB_EXT_ADDRESS_DST: m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sav->sah->saidx.dst, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { goto fail; } break; case SADB_EXT_KEY_AUTH: if (!sav->key_auth) { continue; } l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len); p = sav->key_auth; break; case SADB_EXT_KEY_ENCRYPT: if (!sav->key_enc) { continue; } l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len); p = sav->key_enc; break; case SADB_EXT_LIFETIME_CURRENT: if (!sav->lft_c) { continue; } l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len); p = sav->lft_c; break; case SADB_EXT_LIFETIME_HARD: if (!sav->lft_h) { continue; } l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len); p = sav->lft_h; break; case SADB_EXT_LIFETIME_SOFT: if (!sav->lft_s) { continue; } l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len); p = sav->lft_s; break; case SADB_EXT_ADDRESS_PROXY: case SADB_EXT_IDENTITY_SRC: case SADB_EXT_IDENTITY_DST: /* XXX: should we brought from SPD ? */ case SADB_EXT_SENSITIVITY: default: continue; } if ((!m && !p) || (m && p)) { goto fail; } if (p && tres) { M_PREPEND(tres, l, M_WAITOK, 1); if (!tres) { goto fail; } bcopy(p, mtod(tres, caddr_t), l); continue; } if (p) { m = key_alloc_mbuf(l); if (!m) { goto fail; } m_copyback(m, 0, l, p); } if (tres) { m_cat(m, tres); } tres = m; } m_cat(result, tres); if (sav->sah && (sav->sah->outgoing_if || sav->sah->ipsec_if)) { m = key_setsadbipsecif(NULL, ifindex2ifnet[sav->sah->outgoing_if], sav->sah->ipsec_if, 0); if (!m) { goto fail; } m_cat(result, m); } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return result; fail: m_freem(result); m_freem(tres); return NULL; } /* * set data into sadb_msg. */ static struct mbuf * key_setsadbmsg( u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq, pid_t pid, u_int16_t reserved) { struct mbuf *m; struct sadb_msg *p; int len; len = PFKEY_ALIGN8(sizeof(struct sadb_msg)); if (len > MCLBYTES) { return NULL; } MGETHDR(m, M_DONTWAIT, MT_DATA); if (m && len > MHLEN) { MCLGET(m, M_DONTWAIT); if ((m->m_flags & M_EXT) == 0) { m_freem(m); m = NULL; } } if (!m) { return NULL; } m->m_pkthdr.len = m->m_len = len; m->m_next = NULL; p = mtod(m, struct sadb_msg *); bzero(p, len); p->sadb_msg_version = PF_KEY_V2; p->sadb_msg_type = type; p->sadb_msg_errno = 0; p->sadb_msg_satype = satype; p->sadb_msg_len = PFKEY_UNIT64(tlen); p->sadb_msg_reserved = reserved; p->sadb_msg_seq = seq; p->sadb_msg_pid = (u_int32_t)pid; return m; } /* * copy secasvar data into sadb_address. */ static struct mbuf * key_setsadbsa( struct secasvar *sav) { struct mbuf *m; struct sadb_sa *p; int len; len = PFKEY_ALIGN8(sizeof(struct sadb_sa)); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_sa *); bzero(p, len); p->sadb_sa_len = PFKEY_UNIT64(len); p->sadb_sa_exttype = SADB_EXT_SA; p->sadb_sa_spi = sav->spi; p->sadb_sa_replay = (sav->replay[0] != NULL ? sav->replay[0]->wsize : 0); p->sadb_sa_state = sav->state; p->sadb_sa_auth = sav->alg_auth; p->sadb_sa_encrypt = sav->alg_enc; p->sadb_sa_flags = sav->flags; return m; } /* * set data into sadb_address. */ static struct mbuf * key_setsadbaddr( u_int16_t exttype, struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto) { struct mbuf *m; struct sadb_address *p; size_t len; len = PFKEY_ALIGN8(sizeof(struct sadb_address)) + PFKEY_ALIGN8(saddr->sa_len); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_address *); bzero(p, len); p->sadb_address_len = PFKEY_UNIT64(len); p->sadb_address_exttype = exttype; p->sadb_address_proto = ul_proto; if (prefixlen == FULLMASK) { switch (saddr->sa_family) { case AF_INET: prefixlen = sizeof(struct in_addr) << 3; break; case AF_INET6: prefixlen = sizeof(struct in6_addr) << 3; break; default: ; /*XXX*/ } } p->sadb_address_prefixlen = prefixlen; p->sadb_address_reserved = 0; bcopy(saddr, mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)), saddr->sa_len); return m; } static struct mbuf * key_setsadbipsecif(ifnet_t internal_if, ifnet_t outgoing_if, ifnet_t ipsec_if, int init_disabled) { struct mbuf *m; struct sadb_x_ipsecif *p; size_t len; len = PFKEY_ALIGN8(sizeof(struct sadb_x_ipsecif)); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_x_ipsecif *); bzero(p, len); p->sadb_x_ipsecif_len = PFKEY_UNIT64(len); p->sadb_x_ipsecif_exttype = SADB_X_EXT_IPSECIF; if (internal_if && internal_if->if_xname) { strlcpy(p->sadb_x_ipsecif_internal_if, internal_if->if_xname, IFXNAMSIZ); } if (outgoing_if && outgoing_if->if_xname) { strlcpy(p->sadb_x_ipsecif_outgoing_if, outgoing_if->if_xname, IFXNAMSIZ); } if (ipsec_if && ipsec_if->if_xname) { strlcpy(p->sadb_x_ipsecif_ipsec_if, ipsec_if->if_xname, IFXNAMSIZ); } p->sadb_x_ipsecif_init_disabled = init_disabled; return m; } /* * set data into sadb_session_id */ static struct mbuf * key_setsadbsession_id(u_int64_t session_ids[]) { struct mbuf *m; struct sadb_session_id *p; size_t len; len = PFKEY_ALIGN8(sizeof(*p)); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, __typeof__(p)); bzero(p, len); p->sadb_session_id_len = PFKEY_UNIT64(len); p->sadb_session_id_exttype = SADB_EXT_SESSION_ID; p->sadb_session_id_v[0] = session_ids[0]; p->sadb_session_id_v[1] = session_ids[1]; return m; } /* * copy stats data into sadb_sastat type. */ static struct mbuf * key_setsadbsastat(u_int32_t dir, struct sastat *stats, u_int32_t max_stats) { struct mbuf *m; struct sadb_sastat *p; int list_len, len; if (!stats) { return NULL; } list_len = sizeof(*stats) * max_stats; len = PFKEY_ALIGN8(sizeof(*p)) + PFKEY_ALIGN8(list_len); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, __typeof__(p)); bzero(p, len); p->sadb_sastat_len = PFKEY_UNIT64(len); p->sadb_sastat_exttype = SADB_EXT_SASTAT; p->sadb_sastat_dir = dir; p->sadb_sastat_list_len = max_stats; if (list_len) { bcopy(stats, mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(*p)), list_len); } return m; } #if 0 /* * set data into sadb_ident. */ static struct mbuf * key_setsadbident( u_int16_t exttype, u_int16_t idtype, caddr_t string, int stringlen, u_int64_t id) { struct mbuf *m; struct sadb_ident *p; size_t len; len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_ident *); bzero(p, len); p->sadb_ident_len = PFKEY_UNIT64(len); p->sadb_ident_exttype = exttype; p->sadb_ident_type = idtype; p->sadb_ident_reserved = 0; p->sadb_ident_id = id; bcopy(string, mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)), stringlen); return m; } #endif /* * set data into sadb_x_sa2. */ static struct mbuf * key_setsadbxsa2( u_int8_t mode, u_int32_t seq, u_int32_t reqid, u_int16_t flags) { struct mbuf *m; struct sadb_x_sa2 *p; size_t len; len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2)); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_x_sa2 *); bzero(p, len); p->sadb_x_sa2_len = PFKEY_UNIT64(len); p->sadb_x_sa2_exttype = SADB_X_EXT_SA2; p->sadb_x_sa2_mode = mode; p->sadb_x_sa2_reserved1 = 0; p->sadb_x_sa2_reserved2 = 0; p->sadb_x_sa2_sequence = seq; p->sadb_x_sa2_reqid = reqid; p->sadb_x_sa2_flags = flags; return m; } /* * set data into sadb_x_policy */ static struct mbuf * key_setsadbxpolicy( u_int16_t type, u_int8_t dir, u_int32_t id) { struct mbuf *m; struct sadb_x_policy *p; size_t len; len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy)); m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } return NULL; } p = mtod(m, struct sadb_x_policy *); bzero(p, len); p->sadb_x_policy_len = PFKEY_UNIT64(len); p->sadb_x_policy_exttype = SADB_X_EXT_POLICY; p->sadb_x_policy_type = type; p->sadb_x_policy_dir = dir; p->sadb_x_policy_id = id; return m; } /* %%% utilities */ /* * copy a buffer into the new buffer allocated. */ static void * key_newbuf( const void *src, u_int len) { caddr_t new; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); KMALLOC_NOWAIT(new, caddr_t, len); if (new == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(new, caddr_t, len); lck_mtx_lock(sadb_mutex); if (new == NULL) { ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n")); return NULL; } } bcopy(src, new, len); return new; } /* compare my own address * OUT: 1: true, i.e. my address. * 0: false */ int key_ismyaddr( struct sockaddr *sa) { #if INET struct sockaddr_in *sin; struct in_ifaddr *ia; #endif /* sanity check */ if (sa == NULL) { panic("key_ismyaddr: NULL pointer is passed.\n"); } switch (sa->sa_family) { #if INET case AF_INET: lck_rw_lock_shared(in_ifaddr_rwlock); sin = (struct sockaddr_in *)(void *)sa; for (ia = in_ifaddrhead.tqh_first; ia; ia = ia->ia_link.tqe_next) { IFA_LOCK_SPIN(&ia->ia_ifa); if (sin->sin_family == ia->ia_addr.sin_family && sin->sin_len == ia->ia_addr.sin_len && sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr) { IFA_UNLOCK(&ia->ia_ifa); lck_rw_done(in_ifaddr_rwlock); return 1; } IFA_UNLOCK(&ia->ia_ifa); } lck_rw_done(in_ifaddr_rwlock); break; #endif #if INET6 case AF_INET6: return key_ismyaddr6((struct sockaddr_in6 *)(void *)sa); #endif } return 0; } #if INET6 /* * compare my own address for IPv6. * 1: ours * 0: other * NOTE: derived ip6_input() in KAME. This is necessary to modify more. */ #include <netinet6/in6_var.h> static int key_ismyaddr6( struct sockaddr_in6 *sin6) { struct in6_ifaddr *ia; struct in6_multi *in6m; lck_rw_lock_shared(&in6_ifaddr_rwlock); for (ia = in6_ifaddrs; ia; ia = ia->ia_next) { IFA_LOCK(&ia->ia_ifa); if (key_sockaddrcmp((struct sockaddr *)&sin6, (struct sockaddr *)&ia->ia_addr, 0) == 0) { IFA_UNLOCK(&ia->ia_ifa); lck_rw_done(&in6_ifaddr_rwlock); return 1; } IFA_UNLOCK(&ia->ia_ifa); /* * XXX Multicast * XXX why do we care about multlicast here while we don't care * about IPv4 multicast?? * XXX scope */ in6m = NULL; in6_multihead_lock_shared(); IN6_LOOKUP_MULTI(&sin6->sin6_addr, ia->ia_ifp, in6m); in6_multihead_lock_done(); if (in6m != NULL) { lck_rw_done(&in6_ifaddr_rwlock); IN6M_REMREF(in6m); return 1; } } lck_rw_done(&in6_ifaddr_rwlock); /* loopback, just for safety */ if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)) { return 1; } return 0; } #endif /*INET6*/ /* * compare two secasindex structure. * flag can specify to compare 2 saidxes. * compare two secasindex structure without both mode and reqid. * don't compare port. * IN: * saidx0: source, it can be in SAD. * saidx1: object. * OUT: * 1 : equal * 0 : not equal */ static int key_cmpsaidx( struct secasindex *saidx0, struct secasindex *saidx1, int flag) { /* sanity */ if (saidx0 == NULL && saidx1 == NULL) { return 1; } if (saidx0 == NULL || saidx1 == NULL) { return 0; } if (saidx0->ipsec_ifindex != 0 && saidx0->ipsec_ifindex != saidx1->ipsec_ifindex) { return 0; } if (saidx0->proto != saidx1->proto) { return 0; } if (flag == CMP_EXACTLY) { if (saidx0->mode != saidx1->mode) { return 0; } if (saidx0->reqid != saidx1->reqid) { return 0; } if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 || bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0) { return 0; } } else { /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */ if (flag & CMP_REQID) { /* * If reqid of SPD is non-zero, unique SA is required. * The result must be of same reqid in this case. */ if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid) { return 0; } } if (flag & CMP_MODE) { if (saidx0->mode != IPSEC_MODE_ANY && saidx0->mode != saidx1->mode) { return 0; } } if (key_sockaddrcmp((struct sockaddr *)&saidx0->src, (struct sockaddr *)&saidx1->src, flag & CMP_PORT ? 1 : 0) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst, (struct sockaddr *)&saidx1->dst, flag & CMP_PORT ? 1 : 0) != 0) { return 0; } } return 1; } /* * compare two secindex structure exactly. * IN: * spidx0: source, it is often in SPD. * spidx1: object, it is often from PFKEY message. * OUT: * 1 : equal * 0 : not equal */ static int key_cmpspidx_exactly( struct secpolicyindex *spidx0, struct secpolicyindex *spidx1) { /* sanity */ if (spidx0 == NULL && spidx1 == NULL) { return 1; } if (spidx0 == NULL || spidx1 == NULL) { return 0; } if (spidx0->prefs != spidx1->prefs || spidx0->prefd != spidx1->prefd || spidx0->ul_proto != spidx1->ul_proto || spidx0->internal_if != spidx1->internal_if) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->src, (struct sockaddr *)&spidx1->src, 1) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst, (struct sockaddr *)&spidx1->dst, 1) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->src_range.start, (struct sockaddr *)&spidx1->src_range.start, 1) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->src_range.end, (struct sockaddr *)&spidx1->src_range.end, 1) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst_range.start, (struct sockaddr *)&spidx1->dst_range.start, 1) != 0) { return 0; } if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst_range.end, (struct sockaddr *)&spidx1->dst_range.end, 1) != 0) { return 0; } return 1; } /* * compare two secindex structure with mask. * IN: * spidx0: source, it is often in SPD. * spidx1: object, it is often from IP header. * OUT: * 1 : equal * 0 : not equal */ static int key_cmpspidx_withmask( struct secpolicyindex *spidx0, struct secpolicyindex *spidx1) { int spidx0_src_is_range = 0; int spidx0_dst_is_range = 0; /* sanity */ if (spidx0 == NULL && spidx1 == NULL) { return 1; } if (spidx0 == NULL || spidx1 == NULL) { return 0; } if (spidx0->src_range.start.ss_len > 0) { spidx0_src_is_range = 1; } if (spidx0->dst_range.start.ss_len > 0) { spidx0_dst_is_range = 1; } if ((spidx0_src_is_range ? spidx0->src_range.start.ss_family : spidx0->src.ss_family) != spidx1->src.ss_family || (spidx0_dst_is_range ? spidx0->dst_range.start.ss_family : spidx0->dst.ss_family) != spidx1->dst.ss_family || (spidx0_src_is_range ? spidx0->src_range.start.ss_len : spidx0->src.ss_len) != spidx1->src.ss_len || (spidx0_dst_is_range ? spidx0->dst_range.start.ss_len : spidx0->dst.ss_len) != spidx1->dst.ss_len) { return 0; } /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */ if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY && spidx0->ul_proto != spidx1->ul_proto) { return 0; } /* If spidx1 specifies interface, ignore src addr */ if (spidx1->internal_if != NULL) { if (spidx0->internal_if == NULL || spidx0->internal_if != spidx1->internal_if) { return 0; } /* Still check ports */ switch (spidx0->src.ss_family) { case AF_INET: if (spidx0_src_is_range && (satosin(&spidx1->src)->sin_port < satosin(&spidx0->src_range.start)->sin_port || satosin(&spidx1->src)->sin_port > satosin(&spidx0->src_range.end)->sin_port)) { return 0; } else if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY && satosin(&spidx0->src)->sin_port != satosin(&spidx1->src)->sin_port) { return 0; } break; case AF_INET6: if (spidx0_src_is_range && (satosin6(&spidx1->src)->sin6_port < satosin6(&spidx0->src_range.start)->sin6_port || satosin6(&spidx1->src)->sin6_port > satosin6(&spidx0->src_range.end)->sin6_port)) { return 0; } else if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY && satosin6(&spidx0->src)->sin6_port != satosin6(&spidx1->src)->sin6_port) { return 0; } break; default: break; } } else if (spidx0_src_is_range) { if (!key_is_addr_in_range(&spidx1->src, &spidx0->src_range)) { return 0; } } else { switch (spidx0->src.ss_family) { case AF_INET: if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY && satosin(&spidx0->src)->sin_port != satosin(&spidx1->src)->sin_port) { return 0; } if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr, (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs)) { return 0; } break; case AF_INET6: if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY && satosin6(&spidx0->src)->sin6_port != satosin6(&spidx1->src)->sin6_port) { return 0; } /* * scope_id check. if sin6_scope_id is 0, we regard it * as a wildcard scope, which matches any scope zone ID. */ if (satosin6(&spidx0->src)->sin6_scope_id && satosin6(&spidx1->src)->sin6_scope_id && satosin6(&spidx0->src)->sin6_scope_id != satosin6(&spidx1->src)->sin6_scope_id) { return 0; } if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr, (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs)) { return 0; } break; default: /* XXX */ if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0) { return 0; } break; } } if (spidx0_dst_is_range) { if (!key_is_addr_in_range(&spidx1->dst, &spidx0->dst_range)) { return 0; } } else { switch (spidx0->dst.ss_family) { case AF_INET: if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY && satosin(&spidx0->dst)->sin_port != satosin(&spidx1->dst)->sin_port) { return 0; } if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr, (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd)) { return 0; } break; case AF_INET6: if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY && satosin6(&spidx0->dst)->sin6_port != satosin6(&spidx1->dst)->sin6_port) { return 0; } /* * scope_id check. if sin6_scope_id is 0, we regard it * as a wildcard scope, which matches any scope zone ID. */ if (satosin6(&spidx0->src)->sin6_scope_id && satosin6(&spidx1->src)->sin6_scope_id && satosin6(&spidx0->dst)->sin6_scope_id != satosin6(&spidx1->dst)->sin6_scope_id) { return 0; } if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr, (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd)) { return 0; } break; default: /* XXX */ if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0) { return 0; } break; } } /* XXX Do we check other field ? e.g. flowinfo */ return 1; } static int key_is_addr_in_range(struct sockaddr_storage *addr, struct secpolicyaddrrange *addr_range) { int cmp = 0; if (addr == NULL || addr_range == NULL) { return 0; } /* Must be greater than or equal to start */ cmp = key_sockaddrcmp((struct sockaddr *)addr, (struct sockaddr *)&addr_range->start, 1); if (cmp != 0 && cmp != 1) { return 0; } /* Must be less than or equal to end */ cmp = key_sockaddrcmp((struct sockaddr *)addr, (struct sockaddr *)&addr_range->end, 1); if (cmp != 0 && cmp != -1) { return 0; } return 1; } /* * Return values: * -1: sa1 < sa2 * 0: sa1 == sa2 * 1: sa1 > sa2 * 2: Not comparable or error */ static int key_sockaddrcmp( struct sockaddr *sa1, struct sockaddr *sa2, int port) { int result = 0; int port_result = 0; if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) { return 2; } if (sa1->sa_len == 0) { return 0; } switch (sa1->sa_family) { case AF_INET: if (sa1->sa_len != sizeof(struct sockaddr_in)) { return 2; } result = memcmp(&satosin(sa1)->sin_addr.s_addr, &satosin(sa2)->sin_addr.s_addr, sizeof(satosin(sa1)->sin_addr.s_addr)); if (port) { if (satosin(sa1)->sin_port < satosin(sa2)->sin_port) { port_result = -1; } else if (satosin(sa1)->sin_port > satosin(sa2)->sin_port) { port_result = 1; } if (result == 0) { result = port_result; } else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) { return 2; } } break; case AF_INET6: if (sa1->sa_len != sizeof(struct sockaddr_in6)) { return 2; /*EINVAL*/ } if (satosin6(sa1)->sin6_scope_id != satosin6(sa2)->sin6_scope_id) { return 2; } result = memcmp(&satosin6(sa1)->sin6_addr.s6_addr[0], &satosin6(sa2)->sin6_addr.s6_addr[0], sizeof(struct in6_addr)); if (port) { if (satosin6(sa1)->sin6_port < satosin6(sa2)->sin6_port) { port_result = -1; } else if (satosin6(sa1)->sin6_port > satosin6(sa2)->sin6_port) { port_result = 1; } if (result == 0) { result = port_result; } else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) { return 2; } } break; default: result = memcmp(sa1, sa2, sa1->sa_len); break; } if (result < 0) { result = -1; } else if (result > 0) { result = 1; } return result; } /* * compare two buffers with mask. * IN: * addr1: source * addr2: object * bits: Number of bits to compare * OUT: * 1 : equal * 0 : not equal */ static int key_bbcmp( caddr_t p1, caddr_t p2, u_int bits) { u_int8_t mask; /* XXX: This could be considerably faster if we compare a word * at a time, but it is complicated on LSB Endian machines */ /* Handle null pointers */ if (p1 == NULL || p2 == NULL) { return p1 == p2; } while (bits >= 8) { if (*p1++ != *p2++) { return 0; } bits -= 8; } if (bits > 0) { mask = ~((1 << (8 - bits)) - 1); if ((*p1 & mask) != (*p2 & mask)) { return 0; } } return 1; /* Match! */ } /* * time handler. * scanning SPD and SAD to check status for each entries, * and do to remove or to expire. * XXX: year 2038 problem may remain. */ int key_timehandler_debug = 0; u_int32_t spd_count = 0, sah_count = 0, dead_sah_count = 0, empty_sah_count = 0, larval_sav_count = 0, mature_sav_count = 0, dying_sav_count = 0, dead_sav_count = 0; u_int64_t total_sav_count = 0; void key_timehandler(void) { u_int dir; struct timeval tv; struct secpolicy **spbuf = NULL, **spptr = NULL; struct secasvar **savexbuf = NULL, **savexptr = NULL; struct secasvar **savkabuf = NULL, **savkaptr = NULL; int spbufcount = 0, savbufcount = 0, spcount = 0, savexcount = 0, savkacount = 0, cnt; int stop_handler = 1; /* stop the timehandler */ microtime(&tv); /* pre-allocate buffers before taking the lock */ /* if allocation failures occur - portions of the processing will be skipped */ if ((spbufcount = ipsec_policy_count) != 0) { spbufcount += 256; KMALLOC_WAIT(spbuf, struct secpolicy **, spbufcount * sizeof(struct secpolicy *)); if (spbuf) { spptr = spbuf; } } if ((savbufcount = ipsec_sav_count) != 0) { savbufcount += 512; KMALLOC_WAIT(savexbuf, struct secasvar **, savbufcount * sizeof(struct secasvar *)); if (savexbuf) { savexptr = savexbuf; } KMALLOC_WAIT(savkabuf, struct secasvar **, savbufcount * sizeof(struct secasvar *)); if (savkabuf) { savkaptr = savkabuf; } } lck_mtx_lock(sadb_mutex); /* SPD */ if (spbuf) { struct secpolicy *sp, *nextsp; for (dir = 0; dir < IPSEC_DIR_MAX; dir++) { for (sp = LIST_FIRST(&sptree[dir]); sp != NULL; sp = nextsp) { /* don't prevent timehandler from stopping for generate policy */ if (sp->policy != IPSEC_POLICY_GENERATE) { stop_handler = 0; } spd_count++; nextsp = LIST_NEXT(sp, chain); if (sp->state == IPSEC_SPSTATE_DEAD) { key_freesp(sp, KEY_SADB_LOCKED); continue; } if (sp->lifetime == 0 && sp->validtime == 0) { continue; } if (spbuf && spcount < spbufcount) { /* the deletion will occur next time */ if ((sp->lifetime && tv.tv_sec - sp->created > sp->lifetime) || (sp->validtime && tv.tv_sec - sp->lastused > sp->validtime)) { //key_spdexpire(sp); sp->state = IPSEC_SPSTATE_DEAD; sp->refcnt++; *spptr++ = sp; spcount++; } } } } } /* SAD */ { struct secashead *sah, *nextsah; struct secasvar *sav, *nextsav; for (sah = LIST_FIRST(&sahtree); sah != NULL; sah = nextsah) { sah_count++; nextsah = LIST_NEXT(sah, chain); /* if sah has been dead, then delete it and process next sah. */ if (sah->state == SADB_SASTATE_DEAD) { key_delsah(sah); dead_sah_count++; continue; } if (LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]) == NULL && LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]) == NULL && LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]) == NULL && LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]) == NULL) { key_delsah(sah); empty_sah_count++; continue; } if (savbufcount == 0) { continue; } stop_handler = 0; /* if LARVAL entry doesn't become MATURE, delete it. */ for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]); sav != NULL; sav = nextsav) { larval_sav_count++; total_sav_count++; nextsav = LIST_NEXT(sav, chain); if (sav->lft_h != NULL) { /* If a hard lifetime is defined for the LARVAL SA, use it */ if (sav->lft_h->sadb_lifetime_addtime != 0 && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) { if (sav->always_expire) { key_send_delete(sav); sav = NULL; } else { key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); sav = NULL; } } } else { if (tv.tv_sec - sav->created > key_larval_lifetime) { key_freesav(sav, KEY_SADB_LOCKED); } } } /* * If this is a NAT traversal SA with no activity, * we need to send a keep alive. * * Performed outside of the loop before so we will * only ever send one keepalive. The first SA on * the list is the one that will be used for sending * traffic, so this is the one we use for determining * when to send the keepalive. */ if (savkabuf && savkacount < savbufcount) { sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]); //%%% should we check dying list if this is empty??? if (sav && (natt_keepalive_interval || sav->natt_interval) && (sav->flags & (SADB_X_EXT_NATT_KEEPALIVE | SADB_X_EXT_ESP_KEEPALIVE)) != 0) { sav->refcnt++; *savkaptr++ = sav; savkacount++; } } /* * check MATURE entry to start to send expire message * whether or not. */ for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]); sav != NULL; sav = nextsav) { mature_sav_count++; total_sav_count++; nextsav = LIST_NEXT(sav, chain); /* we don't need to check. */ if (sav->lft_s == NULL) { continue; } /* sanity check */ if (sav->lft_c == NULL) { ipseclog((LOG_DEBUG, "key_timehandler: " "There is no CURRENT time, why?\n")); continue; } /* check SOFT lifetime */ if (sav->lft_s->sadb_lifetime_addtime != 0 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) { /* * If always_expire is set, expire. Otherwise, * if the SA has not been used, delete immediately. */ if (sav->lft_c->sadb_lifetime_usetime == 0 && sav->always_expire == 0) { key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); sav = NULL; } else if (savexbuf && savexcount < savbufcount) { key_sa_chgstate(sav, SADB_SASTATE_DYING); sav->refcnt++; *savexptr++ = sav; savexcount++; } } /* check SOFT lifetime by bytes */ /* * XXX I don't know the way to delete this SA * when new SA is installed. Caution when it's * installed too big lifetime by time. */ else if (savexbuf && savexcount < savbufcount && sav->lft_s->sadb_lifetime_bytes != 0 && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) { /* * XXX If we keep to send expire * message in the status of * DYING. Do remove below code. */ //key_expire(sav); key_sa_chgstate(sav, SADB_SASTATE_DYING); sav->refcnt++; *savexptr++ = sav; savexcount++; } } /* check DYING entry to change status to DEAD. */ for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]); sav != NULL; sav = nextsav) { dying_sav_count++; total_sav_count++; nextsav = LIST_NEXT(sav, chain); /* we don't need to check. */ if (sav->lft_h == NULL) { continue; } /* sanity check */ if (sav->lft_c == NULL) { ipseclog((LOG_DEBUG, "key_timehandler: " "There is no CURRENT time, why?\n")); continue; } if (sav->lft_h->sadb_lifetime_addtime != 0 && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) { if (sav->always_expire) { key_send_delete(sav); sav = NULL; } else { key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); sav = NULL; } } #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */ else if (savbuf && savexcount < savbufcount && sav->lft_s != NULL && sav->lft_s->sadb_lifetime_addtime != 0 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) { /* * XXX: should be checked to be * installed the valid SA. */ /* * If there is no SA then sending * expire message. */ //key_expire(sav); sav->refcnt++; *savexptr++ = sav; savexcount++; } #endif /* check HARD lifetime by bytes */ else if (sav->lft_h->sadb_lifetime_bytes != 0 && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) { key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); sav = NULL; } } /* delete entry in DEAD */ for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]); sav != NULL; sav = nextsav) { dead_sav_count++; total_sav_count++; nextsav = LIST_NEXT(sav, chain); /* sanity check */ if (sav->state != SADB_SASTATE_DEAD) { ipseclog((LOG_DEBUG, "key_timehandler: " "invalid sav->state " "(queue: %d SA: %d): " "kill it anyway\n", SADB_SASTATE_DEAD, sav->state)); } /* * do not call key_freesav() here. * sav should already be freed, and sav->refcnt * shows other references to sav * (such as from SPD). */ } } } if (++key_timehandler_debug >= 300) { if (key_debug_level) { printf("%s: total stats for %u calls\n", __FUNCTION__, key_timehandler_debug); printf("%s: walked %u SPDs\n", __FUNCTION__, spd_count); printf("%s: walked %llu SAs: LARVAL SAs %u, MATURE SAs %u, DYING SAs %u, DEAD SAs %u\n", __FUNCTION__, total_sav_count, larval_sav_count, mature_sav_count, dying_sav_count, dead_sav_count); printf("%s: walked %u SAHs: DEAD SAHs %u, EMPTY SAHs %u\n", __FUNCTION__, sah_count, dead_sah_count, empty_sah_count); if (sah_search_calls) { printf("%s: SAH search cost %d iters per call\n", __FUNCTION__, (sah_search_count / sah_search_calls)); } } spd_count = 0; sah_count = 0; dead_sah_count = 0; empty_sah_count = 0; larval_sav_count = 0; mature_sav_count = 0; dying_sav_count = 0; dead_sav_count = 0; total_sav_count = 0; sah_search_count = 0; sah_search_calls = 0; key_timehandler_debug = 0; } #ifndef IPSEC_NONBLOCK_ACQUIRE /* ACQ tree */ { struct secacq *acq, *nextacq; for (acq = LIST_FIRST(&acqtree); acq != NULL; acq = nextacq) { stop_handler = 0; nextacq = LIST_NEXT(acq, chain); if (tv.tv_sec - acq->created > key_blockacq_lifetime && __LIST_CHAINED(acq)) { LIST_REMOVE(acq, chain); KFREE(acq); } } } #endif /* SP ACQ tree */ { struct secspacq *acq, *nextacq; for (acq = LIST_FIRST(&spacqtree); acq != NULL; acq = nextacq) { stop_handler = 0; nextacq = LIST_NEXT(acq, chain); if (tv.tv_sec - acq->created > key_blockacq_lifetime && __LIST_CHAINED(acq)) { LIST_REMOVE(acq, chain); KFREE(acq); } } } /* initialize random seed */ if (key_tick_init_random++ > key_int_random) { key_tick_init_random = 0; key_srandom(); } uint64_t acc_sleep_time = 0; absolutetime_to_nanoseconds(mach_absolutetime_asleep, &acc_sleep_time); natt_now = ++up_time + (acc_sleep_time / NSEC_PER_SEC); lck_mtx_unlock(sadb_mutex); /* send messages outside of sadb_mutex */ if (spbuf && spcount > 0) { cnt = spcount; while (cnt--) { key_spdexpire(*(--spptr)); } } if (savkabuf && savkacount > 0) { struct secasvar **savkaptr_sav = savkaptr; int cnt_send = savkacount; while (cnt_send--) { if (ipsec_send_natt_keepalive(*(--savkaptr))) { // <rdar://6768487> iterate (all over again) and update timestamps struct secasvar **savkaptr_update = savkaptr_sav; int cnt_update = savkacount; while (cnt_update--) { key_update_natt_keepalive_timestamp(*savkaptr, *(--savkaptr_update)); } } } } if (savexbuf && savexcount > 0) { cnt = savexcount; while (cnt--) { key_expire(*(--savexptr)); } } /* decrement ref counts and free buffers */ lck_mtx_lock(sadb_mutex); if (spbuf) { while (spcount--) { key_freesp(*spptr++, KEY_SADB_LOCKED); } KFREE(spbuf); } if (savkabuf) { while (savkacount--) { key_freesav(*savkaptr++, KEY_SADB_LOCKED); } KFREE(savkabuf); } if (savexbuf) { while (savexcount--) { key_freesav(*savexptr++, KEY_SADB_LOCKED); } KFREE(savexbuf); } if (stop_handler) { key_timehandler_running = 0; /* Turn on the ipsec bypass */ ipsec_bypass = 1; } else { /* do exchange to tick time !! */ (void)timeout((void *)key_timehandler, (void *)0, hz); } lck_mtx_unlock(sadb_mutex); return; } /* * to initialize a seed for random() */ static void key_srandom(void) { #ifdef __APPLE__ /* Our PRNG is based on Yarrow and doesn't need to be seeded */ random(); #else struct timeval tv; microtime(&tv); srandom(tv.tv_usec); #endif return; } u_int32_t key_random(void) { u_int32_t value; key_randomfill(&value, sizeof(value)); return value; } void key_randomfill( void *p, size_t l) { #ifdef __APPLE__ cc_rand_generate(p, l); #else size_t n; u_int32_t v; static int warn = 1; n = 0; n = (size_t)read_random(p, (u_int)l); /* last resort */ while (n < l) { v = random(); bcopy(&v, (u_int8_t *)p + n, l - n < sizeof(v) ? l - n : sizeof(v)); n += sizeof(v); if (warn) { printf("WARNING: pseudo-random number generator " "used for IPsec processing\n"); warn = 0; } } #endif } /* * map SADB_SATYPE_* to IPPROTO_*. * if satype == SADB_SATYPE then satype is mapped to ~0. * OUT: * 0: invalid satype. */ static u_int16_t key_satype2proto( u_int8_t satype) { switch (satype) { case SADB_SATYPE_UNSPEC: return IPSEC_PROTO_ANY; case SADB_SATYPE_AH: return IPPROTO_AH; case SADB_SATYPE_ESP: return IPPROTO_ESP; default: return 0; } /* NOTREACHED */ } /* * map IPPROTO_* to SADB_SATYPE_* * OUT: * 0: invalid protocol type. */ static u_int8_t key_proto2satype( u_int16_t proto) { switch (proto) { case IPPROTO_AH: return SADB_SATYPE_AH; case IPPROTO_ESP: return SADB_SATYPE_ESP; default: return 0; } /* NOTREACHED */ } static ifnet_t key_get_ipsec_if_from_message(const struct sadb_msghdr *mhp, int message_type) { struct sadb_x_ipsecif *ipsecifopts = NULL; ifnet_t ipsec_if = NULL; ipsecifopts = (struct sadb_x_ipsecif *)(void *)mhp->ext[message_type]; if (ipsecifopts != NULL) { if (ipsecifopts->sadb_x_ipsecif_ipsec_if[0]) { ifnet_find_by_name(ipsecifopts->sadb_x_ipsecif_ipsec_if, &ipsec_if); } } return ipsec_if; } static u_int key_get_outgoing_ifindex_from_message(const struct sadb_msghdr *mhp, int message_type) { struct sadb_x_ipsecif *ipsecifopts = NULL; ifnet_t outgoing_if = NULL; ipsecifopts = (struct sadb_x_ipsecif *)(void *)mhp->ext[message_type]; if (ipsecifopts != NULL) { if (ipsecifopts->sadb_x_ipsecif_outgoing_if[0]) { ifnet_find_by_name(ipsecifopts->sadb_x_ipsecif_outgoing_if, &outgoing_if); } } return outgoing_if ? outgoing_if->if_index : 0; } /* %%% PF_KEY */ /* * SADB_GETSPI processing is to receive * <base, (SA2), src address, dst address, (SPI range)> * from the IKMPd, to assign a unique spi value, to hang on the INBOUND * tree with the status of LARVAL, and send * <base, SA(*), address(SD)> * to the IKMPd. * * IN: mhp: pointer to the pointer to each header. * OUT: NULL if fail. * other if success, return pointer to the message to send. */ static int key_getspi( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_address *src0, *dst0; struct secasindex saidx; struct secashead *newsah; struct secasvar *newsav; ifnet_t ipsec_if = NULL; u_int8_t proto; u_int32_t spi; u_int8_t mode; u_int32_t reqid; int error; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_getspi: NULL pointer is passed.\n"); } if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) { ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) { ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_X_EXT_SA2] != NULL) { mode = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode; reqid = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid; } else { mode = IPSEC_MODE_ANY; reqid = 0; } src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]); dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]); ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } /* make sure if port number is zero. */ switch (((struct sockaddr *)(src0 + 1))->sa_family) { case AF_INET: if (((struct sockaddr *)(src0 + 1))->sa_len != sizeof(struct sockaddr_in)) { return key_senderror(so, m, EINVAL); } ((struct sockaddr_in *)(void *)(src0 + 1))->sin_port = 0; break; case AF_INET6: if (((struct sockaddr *)(src0 + 1))->sa_len != sizeof(struct sockaddr_in6)) { return key_senderror(so, m, EINVAL); } ((struct sockaddr_in6 *)(void *)(src0 + 1))->sin6_port = 0; break; default: ; /*???*/ } switch (((struct sockaddr *)(dst0 + 1))->sa_family) { case AF_INET: if (((struct sockaddr *)(dst0 + 1))->sa_len != sizeof(struct sockaddr_in)) { return key_senderror(so, m, EINVAL); } ((struct sockaddr_in *)(void *)(dst0 + 1))->sin_port = 0; break; case AF_INET6: if (((struct sockaddr *)(dst0 + 1))->sa_len != sizeof(struct sockaddr_in6)) { return key_senderror(so, m, EINVAL); } ((struct sockaddr_in6 *)(void *)(dst0 + 1))->sin6_port = 0; break; default: ; /*???*/ } /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); lck_mtx_lock(sadb_mutex); /* SPI allocation */ spi = key_do_getnewspi((struct sadb_spirange *) (void *)mhp->ext[SADB_EXT_SPIRANGE], &saidx); if (spi == 0) { lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, EINVAL); } /* get a SA index */ if ((newsah = key_getsah(&saidx)) == NULL) { /* create a new SA index: key_addspi is always used for inbound spi */ if ((newsah = key_newsah(&saidx, ipsec_if, key_get_outgoing_ifindex_from_message(mhp, SADB_X_EXT_IPSECIF), IPSEC_DIR_INBOUND)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } } /* get a new SA */ /* XXX rewrite */ newsav = key_newsav(m, mhp, newsah, &error, so); if (newsav == NULL) { /* XXX don't free new SA index allocated in above. */ lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, error); } /* set spi */ key_setspi(newsav, htonl(spi)); #ifndef IPSEC_NONBLOCK_ACQUIRE /* delete the entry in acqtree */ if (mhp->msg->sadb_msg_seq != 0) { struct secacq *acq; if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) { /* reset counter in order to deletion by timehandler. */ struct timeval tv; microtime(&tv); acq->created = tv.tv_sec; acq->count = 0; } } #endif lck_mtx_unlock(sadb_mutex); { struct mbuf *n, *nn; struct sadb_sa *m_sa; struct sadb_msg *newmsg; int off, len; /* create new sadb_msg to reply. */ len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) + PFKEY_ALIGN8(sizeof(struct sadb_sa)); if (len > MCLBYTES) { return key_senderror(so, m, ENOBUFS); } MGETHDR(n, M_WAITOK, MT_DATA); if (n && len > MHLEN) { MCLGET(n, M_WAITOK); if ((n->m_flags & M_EXT) == 0) { m_freem(n); n = NULL; } } if (!n) { return key_senderror(so, m, ENOBUFS); } n->m_len = len; n->m_next = NULL; off = 0; m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off); off += PFKEY_ALIGN8(sizeof(struct sadb_msg)); m_sa = (struct sadb_sa *)(void *)(mtod(n, caddr_t) + off); m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa)); m_sa->sadb_sa_exttype = SADB_EXT_SA; m_sa->sadb_sa_spi = htonl(spi); off += PFKEY_ALIGN8(sizeof(struct sadb_sa)); #if DIAGNOSTIC if (off != len) { panic("length inconsistency in key_getspi"); } #endif { int mbufItems[] = {SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST}; n->m_next = key_gather_mbuf(m, mhp, 0, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n->m_next) { m_freem(n); return key_senderror(so, m, ENOBUFS); } } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_sendup_mbuf(so, m, KEY_SENDUP_ONE); } } n->m_pkthdr.len = 0; for (nn = n; nn; nn = nn->m_next) { n->m_pkthdr.len += nn->m_len; } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_seq = newsav->seq; newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ONE); } } u_int32_t key_getspi2(struct sockaddr *src, struct sockaddr *dst, u_int8_t proto, u_int8_t mode, u_int32_t reqid, struct sadb_spirange *spirange) { u_int32_t spi; struct secasindex saidx; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, mode, reqid, src, dst, 0, &saidx); /* make sure if port number is zero. */ switch (((struct sockaddr *)&saidx.src)->sa_family) { case AF_INET: if (((struct sockaddr *)&saidx.src)->sa_len != sizeof(struct sockaddr_in)) { return 0; } ((struct sockaddr_in *)&saidx.src)->sin_port = 0; break; case AF_INET6: if (((struct sockaddr *)&saidx.src)->sa_len != sizeof(struct sockaddr_in6)) { return 0; } ((struct sockaddr_in6 *)&saidx.src)->sin6_port = 0; break; default: ; /*???*/ } switch (((struct sockaddr *)&saidx.dst)->sa_family) { case AF_INET: if (((struct sockaddr *)&saidx.dst)->sa_len != sizeof(struct sockaddr_in)) { return 0; } ((struct sockaddr_in *)&saidx.dst)->sin_port = 0; break; case AF_INET6: if (((struct sockaddr *)&saidx.dst)->sa_len != sizeof(struct sockaddr_in6)) { return 0; } ((struct sockaddr_in6 *)&saidx.dst)->sin6_port = 0; break; default: ; /*???*/ } lck_mtx_lock(sadb_mutex); /* SPI allocation */ spi = key_do_getnewspi(spirange, &saidx); lck_mtx_unlock(sadb_mutex); return spi; } /* * allocating new SPI * called by key_getspi() and key_getspi2(). * OUT: * 0: failure. * others: success. */ static u_int32_t key_do_getnewspi( struct sadb_spirange *spirange, struct secasindex *saidx) { u_int32_t newspi; u_int32_t keymin, keymax; int count = key_spi_trycnt; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* set spi range to allocate */ if (spirange != NULL) { keymin = spirange->sadb_spirange_min; keymax = spirange->sadb_spirange_max; } else { keymin = key_spi_minval; keymax = key_spi_maxval; } if (keymin == keymax) { if (key_checkspidup(saidx, keymin) != NULL) { ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", keymin)); return 0; } count--; /* taking one cost. */ newspi = keymin; } else { u_int32_t range = keymax - keymin + 1; /* overflow value of zero means full range */ /* init SPI */ newspi = 0; /* when requesting to allocate spi ranged */ while (count--) { u_int32_t rand_val = key_random(); /* generate pseudo-random SPI value ranged. */ newspi = (range == 0 ? rand_val : keymin + (rand_val % range)); if (key_checkspidup(saidx, newspi) == NULL) { break; } } if (count == 0 || newspi == 0) { ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n")); return 0; } } /* statistics */ keystat.getspi_count = (keystat.getspi_count + key_spi_trycnt - count) / 2; return newspi; } /* * SADB_UPDATE processing * receive * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),) * key(AE), (identity(SD),) (sensitivity)> * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL. * and send * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),) * (identity(SD),) (sensitivity)> * to the ikmpd. * * m will always be freed. */ static int key_update( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_sa *sa0; struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *sah; struct secasvar *sav; u_int16_t proto; u_int8_t mode; u_int32_t reqid; u_int16_t flags2; int error; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_update: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_SA] == NULL || mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL || (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) || (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && mhp->ext[SADB_EXT_KEY_AUTH] == NULL) || (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL && mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) || (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL && mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) { ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) || mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) { ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_X_EXT_SA2] != NULL) { mode = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode; reqid = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid; flags2 = ((struct sadb_x_sa2 *)(void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_flags; } else { mode = IPSEC_MODE_ANY; reqid = 0; flags2 = 0; } /* XXX boundary checking for other extensions */ sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]); dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]); ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); lck_mtx_lock(sadb_mutex); /* get a SA header */ if ((sah = key_getsah(&saidx)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: no SA index found.\n")); return key_senderror(so, m, ENOENT); } /* set spidx if there */ /* XXX rewrite */ error = key_setident(sah, m, mhp); if (error) { lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, error); } /* find a SA with sequence number. */ #if IPSEC_DOSEQCHECK if (mhp->msg->sadb_msg_seq != 0 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: no larval SA with sequence %u exists.\n", mhp->msg->sadb_msg_seq)); return key_senderror(so, m, ENOENT); } #else if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: no such a SA found (spi:%u)\n", (u_int32_t)ntohl(sa0->sadb_sa_spi))); return key_senderror(so, m, EINVAL); } #endif /* validity check */ if (sav->sah->saidx.proto != proto) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: protocol mismatched (DB=%u param=%u)\n", sav->sah->saidx.proto, proto)); return key_senderror(so, m, EINVAL); } #if IPSEC_DOSEQCHECK if (sav->spi != sa0->sadb_sa_spi) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: SPI mismatched (DB:%u param:%u)\n", (u_int32_t)ntohl(sav->spi), (u_int32_t)ntohl(sa0->sadb_sa_spi))); return key_senderror(so, m, EINVAL); } #endif if (sav->pid != mhp->msg->sadb_msg_pid) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_update: pid mismatched (DB:%u param:%u)\n", sav->pid, mhp->msg->sadb_msg_pid)); return key_senderror(so, m, EINVAL); } /* copy sav values */ error = key_setsaval(sav, m, mhp); if (error) { key_freesav(sav, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, error); } sav->flags2 = flags2; if (flags2 & SADB_X_EXT_SA2_DELETE_ON_DETACH) { sav->so = so; } /* * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that * this SA is for transport mode - otherwise clear it. */ if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0 && (sav->sah->saidx.mode != IPSEC_MODE_TRANSPORT || sav->sah->saidx.src.ss_family != AF_INET)) { sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS; } /* check SA values to be mature. */ if ((error = key_mature(sav)) != 0) { key_freesav(sav, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); return key_senderror(so, m, error); } lck_mtx_unlock(sadb_mutex); { struct mbuf *n; /* set msg buf from mhp */ n = key_getmsgbuf_x1(m, mhp); if (n == NULL) { ipseclog((LOG_DEBUG, "key_update: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } static int key_migrate(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_sa *sa0 = NULL; struct sadb_address *src0 = NULL; struct sadb_address *dst0 = NULL; struct sadb_address *src1 = NULL; struct sadb_address *dst1 = NULL; ifnet_t ipsec_if0 = NULL; ifnet_t ipsec_if1 = NULL; struct secasindex saidx0; struct secasindex saidx1; struct secashead *sah = NULL; struct secashead *newsah = NULL; struct secasvar *sav = NULL; u_int16_t proto; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_migrate: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_migrate: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_SA] == NULL || mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL || mhp->ext[SADB_EXT_MIGRATE_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_MIGRATE_ADDRESS_DST] == NULL) { ipseclog((LOG_DEBUG, "key_migrate: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) || mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_MIGRATE_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_MIGRATE_ADDRESS_DST] < sizeof(struct sadb_address)) { ipseclog((LOG_DEBUG, "key_migrate: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } lck_mtx_lock(sadb_mutex); sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]); dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]); src1 = (struct sadb_address *)(mhp->ext[SADB_EXT_MIGRATE_ADDRESS_SRC]); dst1 = (struct sadb_address *)(mhp->ext[SADB_EXT_MIGRATE_ADDRESS_DST]); ipsec_if0 = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); ipsec_if1 = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_MIGRATE_IPSECIF); /* Find existing SAH and SAV */ KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, ipsec_if0 ? ipsec_if0->if_index : 0, &saidx0); LIST_FOREACH(sah, &sahtree, chain) { if (sah->state != SADB_SASTATE_MATURE) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx0, CMP_HEAD) == 0) { continue; } sav = key_getsavbyspi(sah, sa0->sadb_sa_spi); if (sav && sav->state == SADB_SASTATE_MATURE) { break; } } if (sah == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_migrate: no mature SAH found.\n")); return key_senderror(so, m, ENOENT); } if (sav == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_migrate: no SA found.\n")); return key_senderror(so, m, ENOENT); } /* Find or create new SAH */ KEY_SETSECASIDX(proto, sah->saidx.mode, sah->saidx.reqid, src1 + 1, dst1 + 1, ipsec_if1 ? ipsec_if1->if_index : 0, &saidx1); if ((newsah = key_getsah(&saidx1)) == NULL) { if ((newsah = key_newsah(&saidx1, ipsec_if1, key_get_outgoing_ifindex_from_message(mhp, SADB_X_EXT_MIGRATE_IPSECIF), sah->dir)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_migrate: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } } /* Migrate SAV in to new SAH */ if (key_migratesav(sav, newsah) != 0) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_migrate: Failed to migrate SA to new SAH.\n")); return key_senderror(so, m, EINVAL); } /* Reset NAT values */ sav->flags = sa0->sadb_sa_flags; sav->natt_encapsulated_src_port = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_src_port; sav->remote_ike_port = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_port; sav->natt_interval = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_interval; sav->natt_offload_interval = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_offload_interval; sav->natt_last_activity = natt_now; /* * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that * SADB_X_EXT_NATT is set and SADB_X_EXT_NATT_KEEPALIVE is not * set (we're not behind nat) - otherwise clear it. */ if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) { if ((sav->flags & SADB_X_EXT_NATT) == 0 || (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0) { sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS; } } lck_mtx_unlock(sadb_mutex); { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_X_EXT_IPSECIF, SADB_EXT_MIGRATE_ADDRESS_SRC, SADB_EXT_MIGRATE_ADDRESS_DST, SADB_X_EXT_MIGRATE_IPSECIF}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL. * only called by key_update(). * OUT: * NULL : not found * others : found, pointer to a SA. */ #if IPSEC_DOSEQCHECK static struct secasvar * key_getsavbyseq( struct secashead *sah, u_int32_t seq) { struct secasvar *sav; u_int state; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); state = SADB_SASTATE_LARVAL; /* search SAD with sequence number ? */ LIST_FOREACH(sav, &sah->savtree[state], chain) { KEY_CHKSASTATE(state, sav->state, "key_getsabyseq"); if (sav->seq == seq) { sav->refcnt++; KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP key_getsavbyseq cause " "refcnt++:%d SA:0x%llx\n", sav->refcnt, (uint64_t)VM_KERNEL_ADDRPERM(sav))); return sav; } } return NULL; } #endif /* * SADB_ADD processing * add a entry to SA database, when received * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),) * key(AE), (identity(SD),) (sensitivity)> * from the ikmpd, * and send * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),) * (identity(SD),) (sensitivity)> * to the ikmpd. * * IGNORE identity and sensitivity messages. * * m will always be freed. */ static int key_add( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_sa *sa0; struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *newsah; struct secasvar *newsav; u_int16_t proto; u_int8_t mode; u_int32_t reqid; int error; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_add: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n")); bzero_keys(mhp); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_SA] == NULL || mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL || (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) || (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && mhp->ext[SADB_EXT_KEY_AUTH] == NULL) || (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL && mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) || (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL && mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) { ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n")); bzero_keys(mhp); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) || mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) { /* XXX need more */ ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n")); bzero_keys(mhp); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_X_EXT_SA2] != NULL) { mode = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode; reqid = ((struct sadb_x_sa2 *) (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid; } else { mode = IPSEC_MODE_ANY; reqid = 0; } sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC]; dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST]; ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); lck_mtx_lock(sadb_mutex); /* get a SA header */ if ((newsah = key_getsah(&saidx)) == NULL) { /* create a new SA header: key_addspi is always used for outbound spi */ if ((newsah = key_newsah(&saidx, ipsec_if, key_get_outgoing_ifindex_from_message(mhp, SADB_X_EXT_IPSECIF), IPSEC_DIR_OUTBOUND)) == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_add: No more memory.\n")); bzero_keys(mhp); return key_senderror(so, m, ENOBUFS); } } /* set spidx if there */ /* XXX rewrite */ error = key_setident(newsah, m, mhp); if (error) { lck_mtx_unlock(sadb_mutex); bzero_keys(mhp); return key_senderror(so, m, error); } /* create new SA entry. */ /* We can create new SA only if SPI is different. */ if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_add: SA already exists.\n")); bzero_keys(mhp); return key_senderror(so, m, EEXIST); } newsav = key_newsav(m, mhp, newsah, &error, so); if (newsav == NULL) { lck_mtx_unlock(sadb_mutex); bzero_keys(mhp); return key_senderror(so, m, error); } /* * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that * this SA is for transport mode - otherwise clear it. */ if ((newsav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0 && (newsah->saidx.mode != IPSEC_MODE_TRANSPORT || newsah->saidx.dst.ss_family != AF_INET)) { newsav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS; } /* check SA values to be mature. */ if ((error = key_mature(newsav)) != 0) { key_freesav(newsav, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); bzero_keys(mhp); return key_senderror(so, m, error); } lck_mtx_unlock(sadb_mutex); /* * don't call key_freesav() here, as we would like to keep the SA * in the database on success. */ { struct mbuf *n; /* set msg buf from mhp */ n = key_getmsgbuf_x1(m, mhp); if (n == NULL) { ipseclog((LOG_DEBUG, "key_update: No more memory.\n")); bzero_keys(mhp); return key_senderror(so, m, ENOBUFS); } // mh.ext points to the mbuf content. // Zero out Encryption and Integrity keys if present. bzero_keys(mhp); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* m is retained */ static int key_setident( struct secashead *sah, struct mbuf *m, const struct sadb_msghdr *mhp) { const struct sadb_ident *idsrc, *iddst; int idsrclen, iddstlen; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); /* sanity check */ if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_setident: NULL pointer is passed.\n"); } /* don't make buffer if not there */ if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL && mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) { sah->idents = NULL; sah->identd = NULL; return 0; } if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL || mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) { ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n")); return EINVAL; } idsrc = (const struct sadb_ident *) (void *)mhp->ext[SADB_EXT_IDENTITY_SRC]; iddst = (const struct sadb_ident *) (void *)mhp->ext[SADB_EXT_IDENTITY_DST]; idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC]; iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST]; /* validity check */ if (idsrc->sadb_ident_type != iddst->sadb_ident_type) { ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n")); return EINVAL; } switch (idsrc->sadb_ident_type) { case SADB_IDENTTYPE_PREFIX: case SADB_IDENTTYPE_FQDN: case SADB_IDENTTYPE_USERFQDN: default: /* XXX do nothing */ sah->idents = NULL; sah->identd = NULL; return 0; } /* make structure */ KMALLOC_NOWAIT(sah->idents, struct sadb_ident *, idsrclen); if (sah->idents == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sah->idents, struct sadb_ident *, idsrclen); lck_mtx_lock(sadb_mutex); if (sah->idents == NULL) { ipseclog((LOG_DEBUG, "key_setident: No more memory.\n")); return ENOBUFS; } } KMALLOC_NOWAIT(sah->identd, struct sadb_ident *, iddstlen); if (sah->identd == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(sah->identd, struct sadb_ident *, iddstlen); lck_mtx_lock(sadb_mutex); if (sah->identd == NULL) { KFREE(sah->idents); sah->idents = NULL; ipseclog((LOG_DEBUG, "key_setident: No more memory.\n")); return ENOBUFS; } } bcopy(idsrc, sah->idents, idsrclen); bcopy(iddst, sah->identd, iddstlen); return 0; } /* * m will not be freed on return. * it is caller's responsibility to free the result. */ static struct mbuf * key_getmsgbuf_x1( struct mbuf *m, const struct sadb_msghdr *mhp) { struct mbuf *n; int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA, SADB_X_EXT_SA2, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST, SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT, SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST}; /* sanity check */ if (m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_getmsgbuf_x1: NULL pointer is passed.\n"); } /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return NULL; } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return NULL; } } mtod(n, struct sadb_msg *)->sadb_msg_errno = 0; mtod(n, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); return n; } static int key_delete_all(struct socket *, struct mbuf *, const struct sadb_msghdr *, u_int16_t); /* * SADB_DELETE processing * receive * <base, SA(*), address(SD)> * from the ikmpd, and set SADB_SASTATE_DEAD, * and send, * <base, SA(*), address(SD)> * to the ikmpd. * * m will always be freed. */ static int key_delete( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_sa *sa0; struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *sah; struct secasvar *sav = NULL; u_int16_t proto; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_delete: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) { ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) { ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } lck_mtx_lock(sadb_mutex); if (mhp->ext[SADB_EXT_SA] == NULL) { /* * Caller wants us to delete all non-LARVAL SAs * that match the src/dst. This is used during * IKE INITIAL-CONTACT. */ ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n")); /* key_delete_all will unlock sadb_mutex */ return key_delete_all(so, m, mhp, proto); } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]); dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]); ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); /* get a SA header */ LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0) { continue; } /* get a SA with SPI. */ sav = key_getsavbyspi(sah, sa0->sadb_sa_spi); if (sav) { break; } } if (sah == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_delete: no SA found.\n")); return key_senderror(so, m, ENOENT); } key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); lck_mtx_unlock(sadb_mutex); sav = NULL; { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * delete all SAs for src/dst. Called from key_delete(). */ static int key_delete_all( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp, u_int16_t proto) { struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *sah; struct secasvar *sav, *nextsav; u_int stateidx, state; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]); dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]); ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0) { continue; } /* Delete all non-LARVAL SAs. */ for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { state = saorder_state_alive[stateidx]; if (state == SADB_SASTATE_LARVAL) { continue; } for (sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); /* sanity check */ if (sav->state != state) { ipseclog((LOG_DEBUG, "key_delete_all: " "invalid sav->state " "(queue: %d SA: %d)\n", state, sav->state)); continue; } key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); } } } lck_mtx_unlock(sadb_mutex); { struct mbuf *n; struct sadb_msg *newmsg; int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST}; /* create new sadb_msg to reply. */ n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems) / sizeof(int), mbufItems); if (!n) { return key_senderror(so, m, ENOBUFS); } if (n->m_len < sizeof(struct sadb_msg)) { n = m_pullup(n, sizeof(struct sadb_msg)); if (n == NULL) { return key_senderror(so, m, ENOBUFS); } } newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len); m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ALL); } } /* * SADB_GET processing * receive * <base, SA(*), address(SD)> * from the ikmpd, and get a SP and a SA to respond, * and send, * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE), * (identity(SD),) (sensitivity)> * to the ikmpd. * * m will always be freed. */ static int key_get( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_sa *sa0; struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *sah; struct secasvar *sav = NULL; u_int16_t proto; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_get: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_SA] == NULL || mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) { ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) || mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) { ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA]; src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC]; dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST]; ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); lck_mtx_lock(sadb_mutex); /* get a SA header */ LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0) { continue; } /* get a SA with SPI. */ sav = key_getsavbyspi(sah, sa0->sadb_sa_spi); if (sav) { break; } } if (sah == NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_get: no SA found.\n")); return key_senderror(so, m, ENOENT); } { struct mbuf *n; u_int8_t satype; /* map proto to satype */ if ((satype = key_proto2satype(sah->saidx.proto)) == 0) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n")); return key_senderror(so, m, EINVAL); } lck_mtx_unlock(sadb_mutex); /* create new sadb_msg to reply. */ n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq, mhp->msg->sadb_msg_pid); if (!n) { return key_senderror(so, m, ENOBUFS); } m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_ONE); } } /* * get SA stats by spi. * OUT: -1 : not found * 0 : found, arg pointer to a SA stats is updated. */ static int key_getsastatbyspi_one(u_int32_t spi, struct sastat *stat) { struct secashead *sah; struct secasvar *sav = NULL; if ((void *)stat == NULL) { return -1; } lck_mtx_lock(sadb_mutex); /* get a SA header */ LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } /* get a SA with SPI. */ sav = key_getsavbyspi(sah, spi); if (sav) { stat->spi = sav->spi; stat->created = sav->created; if (sav->lft_c) { bcopy(sav->lft_c, &stat->lft_c, sizeof(stat->lft_c)); } else { bzero(&stat->lft_c, sizeof(stat->lft_c)); } lck_mtx_unlock(sadb_mutex); return 0; } } lck_mtx_unlock(sadb_mutex); return -1; } /* * get SA stats collection by indices. * OUT: -1 : not found * 0 : found, arg pointers to a SA stats and 'maximum stats' are updated. */ static int key_getsastatbyspi(struct sastat *stat_arg, u_int32_t max_stat_arg, struct sastat *stat_res, u_int32_t stat_res_size, u_int32_t *max_stat_res) { int cur, found = 0; if (stat_arg == NULL || stat_res == NULL || max_stat_res == NULL) { return -1; } u_int32_t max_stats = stat_res_size / (sizeof(struct sastat)); max_stats = ((max_stat_arg <= max_stats) ? max_stat_arg : max_stats); for (cur = 0; cur < max_stats; cur++) { if (key_getsastatbyspi_one(stat_arg[cur].spi, &stat_res[found]) == 0) { found++; } } *max_stat_res = found; if (found) { return 0; } return -1; } /* XXX make it sysctl-configurable? */ static void key_getcomb_setlifetime( struct sadb_comb *comb) { comb->sadb_comb_soft_allocations = 1; comb->sadb_comb_hard_allocations = 1; comb->sadb_comb_soft_bytes = 0; comb->sadb_comb_hard_bytes = 0; comb->sadb_comb_hard_addtime = 86400; /* 1 day */ comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100; comb->sadb_comb_soft_usetime = 28800; /* 8 hours */ comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100; } #if IPSEC_ESP /* * XXX reorder combinations by preference * XXX no idea if the user wants ESP authentication or not */ static struct mbuf * key_getcomb_esp(void) { struct sadb_comb *comb; const struct esp_algorithm *algo; struct mbuf *result = NULL, *m, *n; int encmin; int i, off, o; int totlen; const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb)); m = NULL; for (i = 1; i <= SADB_EALG_MAX; i++) { algo = esp_algorithm_lookup(i); if (!algo) { continue; } if (algo->keymax < ipsec_esp_keymin) { continue; } if (algo->keymin < ipsec_esp_keymin) { encmin = ipsec_esp_keymin; } else { encmin = algo->keymin; } if (ipsec_esp_auth) { m = key_getcomb_ah(); } else { #if DIAGNOSTIC if (l > MLEN) { panic("assumption failed in key_getcomb_esp"); } #endif MGET(m, M_WAITOK, MT_DATA); if (m) { M_ALIGN(m, l); m->m_len = l; m->m_next = NULL; bzero(mtod(m, caddr_t), m->m_len); } } if (!m) { goto fail; } totlen = 0; for (n = m; n; n = n->m_next) { totlen += n->m_len; } #if DIAGNOSTIC if (totlen % l) { panic("assumption failed in key_getcomb_esp"); } #endif for (off = 0; off < totlen; off += l) { n = m_pulldown(m, off, l, &o); if (!n) { /* m is already freed */ goto fail; } comb = (struct sadb_comb *) (void *)(mtod(n, caddr_t) + o); bzero(comb, sizeof(*comb)); key_getcomb_setlifetime(comb); comb->sadb_comb_encrypt = i; comb->sadb_comb_encrypt_minbits = encmin; comb->sadb_comb_encrypt_maxbits = algo->keymax; } if (!result) { result = m; } else { m_cat(result, m); } } return result; fail: if (result) { m_freem(result); } return NULL; } #endif /* * XXX reorder combinations by preference */ static struct mbuf * key_getcomb_ah(void) { struct sadb_comb *comb; const struct ah_algorithm *algo; struct mbuf *m; int keymin; int i; const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb)); m = NULL; for (i = 1; i <= SADB_AALG_MAX; i++) { #if 1 /* we prefer HMAC algorithms, not old algorithms */ if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC) { continue; } #endif algo = ah_algorithm_lookup(i); if (!algo) { continue; } if (algo->keymax < ipsec_ah_keymin) { continue; } if (algo->keymin < ipsec_ah_keymin) { keymin = ipsec_ah_keymin; } else { keymin = algo->keymin; } if (!m) { #if DIAGNOSTIC if (l > MLEN) { panic("assumption failed in key_getcomb_ah"); } #endif MGET(m, M_WAITOK, MT_DATA); if (m) { M_ALIGN(m, l); m->m_len = l; m->m_next = NULL; } } else { M_PREPEND(m, l, M_WAITOK, 1); } if (!m) { return NULL; } comb = mtod(m, struct sadb_comb *); bzero(comb, sizeof(*comb)); key_getcomb_setlifetime(comb); comb->sadb_comb_auth = i; comb->sadb_comb_auth_minbits = keymin; comb->sadb_comb_auth_maxbits = algo->keymax; } return m; } /* * XXX no way to pass mode (transport/tunnel) to userland * XXX replay checking? * XXX sysctl interface to ipsec_{ah,esp}_keymin */ static struct mbuf * key_getprop( const struct secasindex *saidx) { struct sadb_prop *prop; struct mbuf *m, *n; const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop)); int totlen; switch (saidx->proto) { #if IPSEC_ESP case IPPROTO_ESP: m = key_getcomb_esp(); break; #endif case IPPROTO_AH: m = key_getcomb_ah(); break; default: return NULL; } if (!m) { return NULL; } M_PREPEND(m, l, M_WAITOK, 1); if (!m) { return NULL; } totlen = 0; for (n = m; n; n = n->m_next) { totlen += n->m_len; } prop = mtod(m, struct sadb_prop *); bzero(prop, sizeof(*prop)); prop->sadb_prop_len = PFKEY_UNIT64(totlen); prop->sadb_prop_exttype = SADB_EXT_PROPOSAL; prop->sadb_prop_replay = 32; /* XXX */ return m; } /* * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2(). * send * <base, SA, address(SD), (address(P)), x_policy, * (identity(SD),) (sensitivity,) proposal> * to KMD, and expect to receive * <base> with SADB_ACQUIRE if error occurred, * or * <base, src address, dst address, (SPI range)> with SADB_GETSPI * from KMD by PF_KEY. * * XXX x_policy is outside of RFC2367 (KAME extension). * XXX sensitivity is not supported. * * OUT: * 0 : succeed * others: error number */ static int key_acquire( struct secasindex *saidx, struct secpolicy *sp) { struct mbuf *result = NULL, *m; #ifndef IPSEC_NONBLOCK_ACQUIRE struct secacq *newacq; #endif u_int8_t satype; int error = -1; u_int32_t seq; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (saidx == NULL) { panic("key_acquire: NULL pointer is passed.\n"); } if ((satype = key_proto2satype(saidx->proto)) == 0) { panic("key_acquire: invalid proto is passed.\n"); } #ifndef IPSEC_NONBLOCK_ACQUIRE /* * We never do anything about acquirng SA. There is anather * solution that kernel blocks to send SADB_ACQUIRE message until * getting something message from IKEd. In later case, to be * managed with ACQUIRING list. */ /* get a entry to check whether sending message or not. */ lck_mtx_lock(sadb_mutex); if ((newacq = key_getacq(saidx)) != NULL) { if (key_blockacq_count < newacq->count) { /* reset counter and do send message. */ newacq->count = 0; } else { /* increment counter and do nothing. */ newacq->count++; lck_mtx_unlock(sadb_mutex); return 0; } } else { /* make new entry for blocking to send SADB_ACQUIRE. */ if ((newacq = key_newacq(saidx)) == NULL) { lck_mtx_unlock(sadb_mutex); return ENOBUFS; } /* add to acqtree */ LIST_INSERT_HEAD(&acqtree, newacq, chain); key_start_timehandler(); } seq = newacq->seq; lck_mtx_unlock(sadb_mutex); #else seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq)); #endif m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0); if (!m) { error = ENOBUFS; goto fail; } result = m; /* set sadb_address for saidx's. */ m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); /* XXX proxy address (optional) */ /* set sadb_x_policy */ if (sp) { m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); } /* XXX identity (optional) */ #if 0 if (idexttype && fqdn) { /* create identity extension (FQDN) */ struct sadb_ident *id; int fqdnlen; fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */ id = (struct sadb_ident *)p; bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen)); id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen)); id->sadb_ident_exttype = idexttype; id->sadb_ident_type = SADB_IDENTTYPE_FQDN; bcopy(fqdn, id + 1, fqdnlen); p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen); } if (idexttype) { /* create identity extension (USERFQDN) */ struct sadb_ident *id; int userfqdnlen; if (userfqdn) { /* +1 for terminating-NUL */ userfqdnlen = strlen(userfqdn) + 1; } else { userfqdnlen = 0; } id = (struct sadb_ident *)p; bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen)); id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen)); id->sadb_ident_exttype = idexttype; id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN; /* XXX is it correct? */ if (curproc && curproc->p_cred) { id->sadb_ident_id = curproc->p_cred->p_ruid; } if (userfqdn && userfqdnlen) { bcopy(userfqdn, id + 1, userfqdnlen); } p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen); } #endif /* XXX sensitivity (optional) */ /* create proposal/combination extension */ m = key_getprop(saidx); /* * outside of spec; make proposal/combination extension optional. */ if (m) { m_cat(result, m); } if ((result->m_flags & M_PKTHDR) == 0) { error = EINVAL; goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { error = ENOBUFS; goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED); fail: if (result) { m_freem(result); } return error; } #ifndef IPSEC_NONBLOCK_ACQUIRE static struct secacq * key_newacq( struct secasindex *saidx) { struct secacq *newacq; struct timeval tv; /* get new entry */ KMALLOC_NOWAIT(newacq, struct secacq *, sizeof(struct secacq)); if (newacq == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(newacq, struct secacq *, sizeof(struct secacq)); lck_mtx_lock(sadb_mutex); if (newacq == NULL) { ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n")); return NULL; } } bzero(newacq, sizeof(*newacq)); /* copy secindex */ bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx)); newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq); microtime(&tv); newacq->created = tv.tv_sec; newacq->count = 0; return newacq; } static struct secacq * key_getacq( struct secasindex *saidx) { struct secacq *acq; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); LIST_FOREACH(acq, &acqtree, chain) { if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY)) { return acq; } } return NULL; } static struct secacq * key_getacqbyseq( u_int32_t seq) { struct secacq *acq; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); LIST_FOREACH(acq, &acqtree, chain) { if (acq->seq == seq) { return acq; } } return NULL; } #endif static struct secspacq * key_newspacq( struct secpolicyindex *spidx) { struct secspacq *acq; struct timeval tv; /* get new entry */ KMALLOC_NOWAIT(acq, struct secspacq *, sizeof(struct secspacq)); if (acq == NULL) { lck_mtx_unlock(sadb_mutex); KMALLOC_WAIT(acq, struct secspacq *, sizeof(struct secspacq)); lck_mtx_lock(sadb_mutex); if (acq == NULL) { ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n")); return NULL; } } bzero(acq, sizeof(*acq)); /* copy secindex */ bcopy(spidx, &acq->spidx, sizeof(acq->spidx)); microtime(&tv); acq->created = tv.tv_sec; acq->count = 0; return acq; } static struct secspacq * key_getspacq( struct secpolicyindex *spidx) { struct secspacq *acq; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); LIST_FOREACH(acq, &spacqtree, chain) { if (key_cmpspidx_exactly(spidx, &acq->spidx)) { return acq; } } return NULL; } /* * SADB_ACQUIRE processing, * in first situation, is receiving * <base> * from the ikmpd, and clear sequence of its secasvar entry. * * In second situation, is receiving * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal> * from a user land process, and return * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal> * to the socket. * * m will always be freed. */ static int key_acquire2( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { const struct sadb_address *src0, *dst0; ifnet_t ipsec_if = NULL; struct secasindex saidx; struct secashead *sah; u_int16_t proto; int error; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_acquire2: NULL pointer is passed.\n"); } /* * Error message from KMd. * We assume that if error was occurred in IKEd, the length of PFKEY * message is equal to the size of sadb_msg structure. * We do not raise error even if error occurred in this function. */ lck_mtx_lock(sadb_mutex); if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) { #ifndef IPSEC_NONBLOCK_ACQUIRE struct secacq *acq; struct timeval tv; /* check sequence number */ if (mhp->msg->sadb_msg_seq == 0) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n")); m_freem(m); return 0; } if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) { /* * the specified larval SA is already gone, or we got * a bogus sequence number. we can silently ignore it. */ lck_mtx_unlock(sadb_mutex); m_freem(m); return 0; } /* reset acq counter in order to deletion by timehander. */ microtime(&tv); acq->created = tv.tv_sec; acq->count = 0; #endif lck_mtx_unlock(sadb_mutex); m_freem(m); return 0; } /* * This message is from user land. */ /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL || mhp->ext[SADB_EXT_ADDRESS_DST] == NULL || mhp->ext[SADB_EXT_PROPOSAL] == NULL) { /* error */ lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) || mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) { /* error */ lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n")); return key_senderror(so, m, EINVAL); } src0 = (const struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC]; dst0 = (const struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST]; ipsec_if = key_get_ipsec_if_from_message(mhp, SADB_X_EXT_IPSECIF); /* XXX boundary check against sa_len */ /* cast warnings */ KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, ipsec_if ? ipsec_if->if_index : 0, &saidx); /* get a SA index */ LIST_FOREACH(sah, &sahtree, chain) { if (sah->state == SADB_SASTATE_DEAD) { continue; } if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE | CMP_REQID)) { break; } } if (sah != NULL) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n")); return key_senderror(so, m, EEXIST); } lck_mtx_unlock(sadb_mutex); error = key_acquire(&saidx, NULL); if (error != 0) { ipseclog((LOG_DEBUG, "key_acquire2: error %d returned " "from key_acquire.\n", mhp->msg->sadb_msg_errno)); return key_senderror(so, m, error); } return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED); } /* * SADB_REGISTER processing. * If SATYPE_UNSPEC has been passed as satype, only return sadb_supported. * receive * <base> * from the ikmpd, and register a socket to send PF_KEY messages, * and send * <base, supported> * to KMD by PF_KEY. * If socket is detached, must free from regnode. * * m will always be freed. */ static int key_register( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct secreg *reg, *newreg = 0; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_register: NULL pointer is passed.\n"); } /* check for invalid register message */ if (mhp->msg->sadb_msg_satype >= sizeof(regtree) / sizeof(regtree[0])) { return key_senderror(so, m, EINVAL); } /* When SATYPE_UNSPEC is specified, only return sadb_supported. */ if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC) { goto setmsg; } /* create regnode */ KMALLOC_WAIT(newreg, struct secreg *, sizeof(*newreg)); if (newreg == NULL) { ipseclog((LOG_DEBUG, "key_register: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } bzero((caddr_t)newreg, sizeof(*newreg)); lck_mtx_lock(sadb_mutex); /* check whether existing or not */ LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) { if (reg->so == so) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_register: socket exists already.\n")); KFREE(newreg); return key_senderror(so, m, EEXIST); } } socket_lock(so, 1); newreg->so = so; ((struct keycb *)sotorawcb(so))->kp_registered++; socket_unlock(so, 1); /* add regnode to regtree. */ LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain); lck_mtx_unlock(sadb_mutex); setmsg: { struct mbuf *n; struct sadb_msg *newmsg; struct sadb_supported *sup; u_int len, alen, elen; int off; int i; struct sadb_alg *alg; /* create new sadb_msg to reply. */ alen = 0; for (i = 1; i <= SADB_AALG_MAX; i++) { if (ah_algorithm_lookup(i)) { alen += sizeof(struct sadb_alg); } } if (alen) { alen += sizeof(struct sadb_supported); } elen = 0; #if IPSEC_ESP for (i = 1; i <= SADB_EALG_MAX; i++) { if (esp_algorithm_lookup(i)) { elen += sizeof(struct sadb_alg); } } if (elen) { elen += sizeof(struct sadb_supported); } #endif len = sizeof(struct sadb_msg) + alen + elen; if (len > MCLBYTES) { return key_senderror(so, m, ENOBUFS); } MGETHDR(n, M_WAITOK, MT_DATA); if (n && len > MHLEN) { MCLGET(n, M_WAITOK); if ((n->m_flags & M_EXT) == 0) { m_freem(n); n = NULL; } } if (!n) { return key_senderror(so, m, ENOBUFS); } n->m_pkthdr.len = n->m_len = len; n->m_next = NULL; off = 0; m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off); newmsg = mtod(n, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(len); off += PFKEY_ALIGN8(sizeof(struct sadb_msg)); /* for authentication algorithm */ if (alen) { sup = (struct sadb_supported *)(void *)(mtod(n, caddr_t) + off); sup->sadb_supported_len = PFKEY_UNIT64(alen); sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH; off += PFKEY_ALIGN8(sizeof(*sup)); for (i = 1; i <= SADB_AALG_MAX; i++) { const struct ah_algorithm *aalgo; aalgo = ah_algorithm_lookup(i); if (!aalgo) { continue; } alg = (struct sadb_alg *) (void *)(mtod(n, caddr_t) + off); alg->sadb_alg_id = i; alg->sadb_alg_ivlen = 0; alg->sadb_alg_minbits = aalgo->keymin; alg->sadb_alg_maxbits = aalgo->keymax; off += PFKEY_ALIGN8(sizeof(*alg)); } } #if IPSEC_ESP /* for encryption algorithm */ if (elen) { sup = (struct sadb_supported *)(void *)(mtod(n, caddr_t) + off); sup->sadb_supported_len = PFKEY_UNIT64(elen); sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT; off += PFKEY_ALIGN8(sizeof(*sup)); for (i = 1; i <= SADB_EALG_MAX; i++) { const struct esp_algorithm *ealgo; ealgo = esp_algorithm_lookup(i); if (!ealgo) { continue; } alg = (struct sadb_alg *) (void *)(mtod(n, caddr_t) + off); alg->sadb_alg_id = i; if (ealgo && ealgo->ivlen) { /* * give NULL to get the value preferred by * algorithm XXX SADB_X_EXT_DERIV ? */ alg->sadb_alg_ivlen = (*ealgo->ivlen)(ealgo, NULL); } else { alg->sadb_alg_ivlen = 0; } alg->sadb_alg_minbits = ealgo->keymin; alg->sadb_alg_maxbits = ealgo->keymax; off += PFKEY_ALIGN8(sizeof(struct sadb_alg)); } } #endif #if DIAGNOSTIC if (off != len) { panic("length assumption failed in key_register"); } #endif m_freem(m); return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED); } } static void key_delete_all_for_socket(struct socket *so) { struct secashead *sah, *nextsah; struct secasvar *sav, *nextsav; u_int stateidx; u_int state; for (sah = LIST_FIRST(&sahtree); sah != NULL; sah = nextsah) { nextsah = LIST_NEXT(sah, chain); for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { state = saorder_state_any[stateidx]; for (sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); if (sav->flags2 & SADB_X_EXT_SA2_DELETE_ON_DETACH && sav->so == so) { key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); } } } } } /* * free secreg entry registered. * XXX: I want to do free a socket marked done SADB_RESIGER to socket. */ void key_freereg( struct socket *so) { struct secreg *reg; int i; /* sanity check */ if (so == NULL) { panic("key_freereg: NULL pointer is passed.\n"); } /* * check whether existing or not. * check all type of SA, because there is a potential that * one socket is registered to multiple type of SA. */ lck_mtx_lock(sadb_mutex); key_delete_all_for_socket(so); for (i = 0; i <= SADB_SATYPE_MAX; i++) { LIST_FOREACH(reg, &regtree[i], chain) { if (reg->so == so && __LIST_CHAINED(reg)) { LIST_REMOVE(reg, chain); KFREE(reg); break; } } } lck_mtx_unlock(sadb_mutex); return; } /* * SADB_EXPIRE processing * send * <base, SA, SA2, lifetime(C and one of HS), address(SD)> * to KMD by PF_KEY. * NOTE: We send only soft lifetime extension. * * OUT: 0 : succeed * others : error number */ static int key_expire( struct secasvar *sav) { int satype; struct mbuf *result = NULL, *m; int len; int error = -1; struct sadb_lifetime *lt; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (sav == NULL) { panic("key_expire: NULL pointer is passed.\n"); } if (sav->sah == NULL) { panic("key_expire: Why was SA index in SA NULL.\n"); } if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) { panic("key_expire: invalid proto is passed.\n"); } /* set msg header */ m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt); if (!m) { error = ENOBUFS; goto fail; } result = m; /* create SA extension */ m = key_setsadbsa(sav); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); /* create SA extension */ m = key_setsadbxsa2(sav->sah->saidx.mode, sav->replay[0] ? sav->replay[0]->count : 0, sav->sah->saidx.reqid, sav->flags2); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); /* create lifetime extension (current and soft) */ len = PFKEY_ALIGN8(sizeof(*lt)) * 2; m = key_alloc_mbuf(len); if (!m || m->m_next) { /*XXX*/ if (m) { m_freem(m); } error = ENOBUFS; goto fail; } bzero(mtod(m, caddr_t), len); lt = mtod(m, struct sadb_lifetime *); lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime)); lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations; lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes; lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime; lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime; lt = (struct sadb_lifetime *)(void *)(mtod(m, caddr_t) + len / 2); bcopy(sav->lft_s, lt, sizeof(*lt)); m_cat(result, m); /* set sadb_address for source */ m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sav->sah->saidx.src, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); /* set sadb_address for destination */ m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sav->sah->saidx.dst, FULLMASK, IPSEC_ULPROTO_ANY); if (!m) { error = ENOBUFS; goto fail; } m_cat(result, m); if ((result->m_flags & M_PKTHDR) == 0) { error = EINVAL; goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { error = ENOBUFS; goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED); fail: if (result) { m_freem(result); } return error; } /* * SADB_FLUSH processing * receive * <base> * from the ikmpd, and free all entries in secastree. * and send, * <base> * to the ikmpd. * NOTE: to do is only marking SADB_SASTATE_DEAD. * * m will always be freed. */ static int key_flush( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_msg *newmsg; struct secashead *sah, *nextsah; struct secasvar *sav, *nextsav; u_int16_t proto; u_int8_t state; u_int stateidx; /* sanity check */ if (so == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_flush: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } lck_mtx_lock(sadb_mutex); /* no SATYPE specified, i.e. flushing all SA. */ for (sah = LIST_FIRST(&sahtree); sah != NULL; sah = nextsah) { nextsah = LIST_NEXT(sah, chain); if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC && proto != sah->saidx.proto) { continue; } for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { state = saorder_state_any[stateidx]; for (sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); } } sah->state = SADB_SASTATE_DEAD; } lck_mtx_unlock(sadb_mutex); if (m->m_len < sizeof(struct sadb_msg) || sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) { ipseclog((LOG_DEBUG, "key_flush: No more memory.\n")); return key_senderror(so, m, ENOBUFS); } if (m->m_next) { m_freem(m->m_next); } m->m_next = NULL; m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg); newmsg = mtod(m, struct sadb_msg *); newmsg->sadb_msg_errno = 0; newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len); return key_sendup_mbuf(so, m, KEY_SENDUP_ALL); } /* * SADB_DUMP processing * dump all entries including status of DEAD in SAD. * receive * <base> * from the ikmpd, and dump all secasvar leaves * and send, * <base> ..... * to the ikmpd. * * m will always be freed. */ struct sav_dump_elem { struct secasvar *sav; u_int8_t satype; }; static int key_dump( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct secashead *sah; struct secasvar *sav; struct sav_dump_elem *savbuf = NULL, *elem_ptr; u_int16_t proto; u_int stateidx; u_int8_t satype; u_int8_t state; int cnt = 0, cnt2, bufcount; struct mbuf *n; int error = 0; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_dump: NULL pointer is passed.\n"); } /* map satype to proto */ if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) { ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n")); return key_senderror(so, m, EINVAL); } if ((bufcount = ipsec_sav_count) <= 0) { error = ENOENT; goto end; } bufcount += 512; /* extra */ KMALLOC_WAIT(savbuf, struct sav_dump_elem*, bufcount * sizeof(struct sav_dump_elem)); if (savbuf == NULL) { ipseclog((LOG_DEBUG, "key_dump: No more memory.\n")); error = ENOMEM; goto end; } /* count sav entries to be sent to the userland. */ lck_mtx_lock(sadb_mutex); elem_ptr = savbuf; LIST_FOREACH(sah, &sahtree, chain) { if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC && proto != sah->saidx.proto) { continue; } /* map proto to satype */ if ((satype = key_proto2satype(sah->saidx.proto)) == 0) { lck_mtx_unlock(sadb_mutex); ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n")); error = EINVAL; goto end; } for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_any); stateidx++) { state = saorder_state_any[stateidx]; LIST_FOREACH(sav, &sah->savtree[state], chain) { if (cnt == bufcount) { break; /* out of buffer space */ } elem_ptr->sav = sav; elem_ptr->satype = satype; sav->refcnt++; elem_ptr++; cnt++; } } } lck_mtx_unlock(sadb_mutex); if (cnt == 0) { error = ENOENT; goto end; } /* send this to the userland, one at a time. */ elem_ptr = savbuf; cnt2 = cnt; while (cnt2) { n = key_setdumpsa(elem_ptr->sav, SADB_DUMP, elem_ptr->satype, --cnt2, mhp->msg->sadb_msg_pid); if (!n) { error = ENOBUFS; goto end; } key_sendup_mbuf(so, n, KEY_SENDUP_ONE); elem_ptr++; } end: if (savbuf) { if (cnt) { elem_ptr = savbuf; lck_mtx_lock(sadb_mutex); while (cnt--) { key_freesav((elem_ptr++)->sav, KEY_SADB_LOCKED); } lck_mtx_unlock(sadb_mutex); } KFREE(savbuf); } if (error) { return key_senderror(so, m, error); } m_freem(m); return 0; } /* * SADB_X_PROMISC processing * * m will always be freed. */ static int key_promisc( struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { int olen; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("key_promisc: NULL pointer is passed.\n"); } olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len); if (olen < sizeof(struct sadb_msg)) { #if 1 return key_senderror(so, m, EINVAL); #else m_freem(m); return 0; #endif } else if (olen == sizeof(struct sadb_msg)) { /* enable/disable promisc mode */ struct keycb *kp; socket_lock(so, 1); if ((kp = (struct keycb *)sotorawcb(so)) == NULL) { return key_senderror(so, m, EINVAL); } mhp->msg->sadb_msg_errno = 0; switch (mhp->msg->sadb_msg_satype) { case 0: case 1: kp->kp_promisc = mhp->msg->sadb_msg_satype; break; default: socket_unlock(so, 1); return key_senderror(so, m, EINVAL); } socket_unlock(so, 1); /* send the original message back to everyone */ mhp->msg->sadb_msg_errno = 0; return key_sendup_mbuf(so, m, KEY_SENDUP_ALL); } else { /* send packet as is */ m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg))); /* TODO: if sadb_msg_seq is specified, send to specific pid */ return key_sendup_mbuf(so, m, KEY_SENDUP_ALL); } } static int(*const key_typesw[])(struct socket *, struct mbuf *, const struct sadb_msghdr *) = { NULL, /* SADB_RESERVED */ key_getspi, /* SADB_GETSPI */ key_update, /* SADB_UPDATE */ key_add, /* SADB_ADD */ key_delete, /* SADB_DELETE */ key_get, /* SADB_GET */ key_acquire2, /* SADB_ACQUIRE */ key_register, /* SADB_REGISTER */ NULL, /* SADB_EXPIRE */ key_flush, /* SADB_FLUSH */ key_dump, /* SADB_DUMP */ key_promisc, /* SADB_X_PROMISC */ NULL, /* SADB_X_PCHANGE */ key_spdadd, /* SADB_X_SPDUPDATE */ key_spdadd, /* SADB_X_SPDADD */ key_spddelete, /* SADB_X_SPDDELETE */ key_spdget, /* SADB_X_SPDGET */ NULL, /* SADB_X_SPDACQUIRE */ key_spddump, /* SADB_X_SPDDUMP */ key_spdflush, /* SADB_X_SPDFLUSH */ key_spdadd, /* SADB_X_SPDSETIDX */ NULL, /* SADB_X_SPDEXPIRE */ key_spddelete2, /* SADB_X_SPDDELETE2 */ key_getsastat, /* SADB_GETSASTAT */ key_spdenable, /* SADB_X_SPDENABLE */ key_spddisable, /* SADB_X_SPDDISABLE */ key_migrate, /* SADB_MIGRATE */ }; static void bzero_mbuf(struct mbuf *m) { struct mbuf *mptr = m; struct sadb_msg *msg = NULL; int offset = 0; if (!mptr) { return; } if (mptr->m_len >= sizeof(struct sadb_msg)) { msg = mtod(mptr, struct sadb_msg *); if (msg->sadb_msg_type != SADB_ADD && msg->sadb_msg_type != SADB_UPDATE) { return; } offset = sizeof(struct sadb_msg); } bzero(mptr->m_data + offset, mptr->m_len - offset); mptr = mptr->m_next; while (mptr != NULL) { bzero(mptr->m_data, mptr->m_len); mptr = mptr->m_next; } } static void bzero_keys(const struct sadb_msghdr *mh) { int extlen = 0; int offset = 0; if (!mh) { return; } offset = sizeof(struct sadb_key); if (mh->ext[SADB_EXT_KEY_ENCRYPT]) { struct sadb_key *key = (struct sadb_key*)mh->ext[SADB_EXT_KEY_ENCRYPT]; extlen = key->sadb_key_bits >> 3; if (mh->extlen[SADB_EXT_KEY_ENCRYPT] >= offset + extlen) { bzero((uint8_t *)mh->ext[SADB_EXT_KEY_ENCRYPT] + offset, extlen); } else { bzero(mh->ext[SADB_EXT_KEY_ENCRYPT], mh->extlen[SADB_EXT_KEY_ENCRYPT]); } } if (mh->ext[SADB_EXT_KEY_AUTH]) { struct sadb_key *key = (struct sadb_key*)mh->ext[SADB_EXT_KEY_AUTH]; extlen = key->sadb_key_bits >> 3; if (mh->extlen[SADB_EXT_KEY_AUTH] >= offset + extlen) { bzero((uint8_t *)mh->ext[SADB_EXT_KEY_AUTH] + offset, extlen); } else { bzero(mh->ext[SADB_EXT_KEY_AUTH], mh->extlen[SADB_EXT_KEY_AUTH]); } } } static int key_validate_address_pair(struct sadb_address *src0, struct sadb_address *dst0) { u_int plen = 0; /* check upper layer protocol */ if (src0->sadb_address_proto != dst0->sadb_address_proto) { ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } /* check family */ if (PFKEY_ADDR_SADDR(src0)->sa_family != PFKEY_ADDR_SADDR(dst0)->sa_family) { ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } if (PFKEY_ADDR_SADDR(src0)->sa_len != PFKEY_ADDR_SADDR(dst0)->sa_len) { ipseclog((LOG_DEBUG, "key_parse: address struct size mismatched.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } switch (PFKEY_ADDR_SADDR(src0)->sa_family) { case AF_INET: if (PFKEY_ADDR_SADDR(src0)->sa_len != sizeof(struct sockaddr_in)) { PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } break; case AF_INET6: if (PFKEY_ADDR_SADDR(src0)->sa_len != sizeof(struct sockaddr_in6)) { PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } break; default: ipseclog((LOG_DEBUG, "key_parse: unsupported address family.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EAFNOSUPPORT; } switch (PFKEY_ADDR_SADDR(src0)->sa_family) { case AF_INET: plen = sizeof(struct in_addr) << 3; break; case AF_INET6: plen = sizeof(struct in6_addr) << 3; break; default: plen = 0; /*fool gcc*/ break; } /* check max prefix length */ if (src0->sadb_address_prefixlen > plen || dst0->sadb_address_prefixlen > plen) { ipseclog((LOG_DEBUG, "key_parse: illegal prefixlen.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr); return EINVAL; } /* * prefixlen == 0 is valid because there can be a case when * all addresses are matched. */ return 0; } /* * parse sadb_msg buffer to process PFKEYv2, * and create a data to response if needed. * I think to be dealed with mbuf directly. * IN: * msgp : pointer to pointer to a received buffer pulluped. * This is rewrited to response. * so : pointer to socket. * OUT: * length for buffer to send to user process. */ int key_parse( struct mbuf *m, struct socket *so) { struct sadb_msg *msg; struct sadb_msghdr mh; u_int orglen; int error; int target; Boolean keyAligned = FALSE; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); /* sanity check */ if (m == NULL || so == NULL) { panic("key_parse: NULL pointer is passed.\n"); } #if 0 /*kdebug_sadb assumes msg in linear buffer*/ KEYDEBUG(KEYDEBUG_KEY_DUMP, ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n")); kdebug_sadb(msg)); #endif if (m->m_len < sizeof(struct sadb_msg)) { m = m_pullup(m, sizeof(struct sadb_msg)); if (!m) { return ENOBUFS; } } msg = mtod(m, struct sadb_msg *); orglen = PFKEY_UNUNIT64(msg->sadb_msg_len); target = KEY_SENDUP_ONE; if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) { ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invlen); error = EINVAL; goto senderror; } if (msg->sadb_msg_version != PF_KEY_V2) { ipseclog((LOG_DEBUG, "key_parse: PF_KEY version %u is mismatched.\n", msg->sadb_msg_version)); PFKEY_STAT_INCREMENT(pfkeystat.out_invver); error = EINVAL; goto senderror; } if (msg->sadb_msg_type > SADB_MAX) { ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n", msg->sadb_msg_type)); PFKEY_STAT_INCREMENT(pfkeystat.out_invmsgtype); error = EINVAL; goto senderror; } /* for old-fashioned code - should be nuked */ if (m->m_pkthdr.len > MCLBYTES) { m_freem(m); return ENOBUFS; } if (m->m_next) { struct mbuf *n; MGETHDR(n, M_WAITOK, MT_DATA); if (n && m->m_pkthdr.len > MHLEN) { MCLGET(n, M_WAITOK); if ((n->m_flags & M_EXT) == 0) { m_free(n); n = NULL; } } if (!n) { bzero_mbuf(m); m_freem(m); return ENOBUFS; } m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t)); n->m_pkthdr.len = n->m_len = m->m_pkthdr.len; n->m_next = NULL; bzero_mbuf(m); m_freem(m); m = n; } /* align the mbuf chain so that extensions are in contiguous region. */ error = key_align(m, &mh); if (error) { return error; } if (m->m_next) { /*XXX*/ bzero_mbuf(m); m_freem(m); return ENOBUFS; } keyAligned = TRUE; msg = mh.msg; /* check SA type */ switch (msg->sadb_msg_satype) { case SADB_SATYPE_UNSPEC: switch (msg->sadb_msg_type) { case SADB_GETSPI: case SADB_UPDATE: case SADB_ADD: case SADB_DELETE: case SADB_GET: case SADB_ACQUIRE: case SADB_EXPIRE: ipseclog((LOG_DEBUG, "key_parse: must specify satype " "when msg type=%u.\n", msg->sadb_msg_type)); PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype); error = EINVAL; goto senderror; } break; case SADB_SATYPE_AH: case SADB_SATYPE_ESP: switch (msg->sadb_msg_type) { case SADB_X_SPDADD: case SADB_X_SPDDELETE: case SADB_X_SPDGET: case SADB_X_SPDDUMP: case SADB_X_SPDFLUSH: case SADB_X_SPDSETIDX: case SADB_X_SPDUPDATE: case SADB_X_SPDDELETE2: case SADB_X_SPDENABLE: case SADB_X_SPDDISABLE: ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n", msg->sadb_msg_type)); PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype); error = EINVAL; goto senderror; } break; case SADB_SATYPE_RSVP: case SADB_SATYPE_OSPFV2: case SADB_SATYPE_RIPV2: case SADB_SATYPE_MIP: ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n", msg->sadb_msg_satype)); PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype); error = EOPNOTSUPP; goto senderror; case 1: /* XXX: What does it do? */ if (msg->sadb_msg_type == SADB_X_PROMISC) { break; } /*FALLTHROUGH*/ default: ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n", msg->sadb_msg_satype)); PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype); error = EINVAL; goto senderror; } /* Validate address fields for matching families, lengths, etc. */ void *src0 = mh.ext[SADB_EXT_ADDRESS_SRC]; void *dst0 = mh.ext[SADB_EXT_ADDRESS_DST]; if (mh.ext[SADB_X_EXT_ADDR_RANGE_SRC_START] != NULL && mh.ext[SADB_X_EXT_ADDR_RANGE_SRC_END] != NULL) { error = key_validate_address_pair((struct sadb_address *)(mh.ext[SADB_X_EXT_ADDR_RANGE_SRC_START]), (struct sadb_address *)(mh.ext[SADB_X_EXT_ADDR_RANGE_SRC_END])); if (error != 0) { goto senderror; } if (src0 == NULL) { src0 = mh.ext[SADB_X_EXT_ADDR_RANGE_SRC_START]; } } if (mh.ext[SADB_X_EXT_ADDR_RANGE_DST_START] != NULL && mh.ext[SADB_X_EXT_ADDR_RANGE_DST_END] != NULL) { error = key_validate_address_pair((struct sadb_address *)(mh.ext[SADB_X_EXT_ADDR_RANGE_DST_START]), (struct sadb_address *)(mh.ext[SADB_X_EXT_ADDR_RANGE_DST_END])); if (error != 0) { goto senderror; } if (dst0 == NULL) { dst0 = mh.ext[SADB_X_EXT_ADDR_RANGE_DST_START]; } } if (src0 != NULL && dst0 != NULL) { error = key_validate_address_pair((struct sadb_address *)(src0), (struct sadb_address *)(dst0)); if (error != 0) { goto senderror; } } if (msg->sadb_msg_type >= sizeof(key_typesw) / sizeof(key_typesw[0]) || key_typesw[msg->sadb_msg_type] == NULL) { PFKEY_STAT_INCREMENT(pfkeystat.out_invmsgtype); error = EINVAL; goto senderror; } error = (*key_typesw[msg->sadb_msg_type])(so, m, &mh); return error; senderror: if (keyAligned) { bzero_keys(&mh); } else { bzero_mbuf(m); } msg->sadb_msg_errno = error; return key_sendup_mbuf(so, m, target); } static int key_senderror( struct socket *so, struct mbuf *m, int code) { struct sadb_msg *msg; LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); if (m->m_len < sizeof(struct sadb_msg)) { panic("invalid mbuf passed to key_senderror"); } msg = mtod(m, struct sadb_msg *); msg->sadb_msg_errno = code; return key_sendup_mbuf(so, m, KEY_SENDUP_ONE); } /* * set the pointer to each header into message buffer. * m will be freed on error. * XXX larger-than-MCLBYTES extension? */ static int key_align( struct mbuf *m, struct sadb_msghdr *mhp) { struct mbuf *n; struct sadb_ext *ext; size_t off, end; int extlen; int toff; /* sanity check */ if (m == NULL || mhp == NULL) { panic("key_align: NULL pointer is passed.\n"); } if (m->m_len < sizeof(struct sadb_msg)) { panic("invalid mbuf passed to key_align"); } /* initialize */ bzero(mhp, sizeof(*mhp)); mhp->msg = mtod(m, struct sadb_msg *); mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */ end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len); extlen = end; /*just in case extlen is not updated*/ for (off = sizeof(struct sadb_msg); off < end; off += extlen) { n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff); if (!n) { /* m is already freed */ return ENOBUFS; } ext = (struct sadb_ext *)(void *)(mtod(n, caddr_t) + toff); /* set pointer */ switch (ext->sadb_ext_type) { case SADB_EXT_SA: case SADB_EXT_ADDRESS_SRC: case SADB_EXT_ADDRESS_DST: case SADB_EXT_ADDRESS_PROXY: case SADB_EXT_LIFETIME_CURRENT: case SADB_EXT_LIFETIME_HARD: case SADB_EXT_LIFETIME_SOFT: case SADB_EXT_KEY_AUTH: case SADB_EXT_KEY_ENCRYPT: case SADB_EXT_IDENTITY_SRC: case SADB_EXT_IDENTITY_DST: case SADB_EXT_SENSITIVITY: case SADB_EXT_PROPOSAL: case SADB_EXT_SUPPORTED_AUTH: case SADB_EXT_SUPPORTED_ENCRYPT: case SADB_EXT_SPIRANGE: case SADB_X_EXT_POLICY: case SADB_X_EXT_SA2: case SADB_EXT_SESSION_ID: case SADB_EXT_SASTAT: case SADB_X_EXT_IPSECIF: case SADB_X_EXT_ADDR_RANGE_SRC_START: case SADB_X_EXT_ADDR_RANGE_SRC_END: case SADB_X_EXT_ADDR_RANGE_DST_START: case SADB_X_EXT_ADDR_RANGE_DST_END: case SADB_EXT_MIGRATE_ADDRESS_SRC: case SADB_EXT_MIGRATE_ADDRESS_DST: case SADB_X_EXT_MIGRATE_IPSECIF: /* duplicate check */ /* * XXX Are there duplication payloads of either * KEY_AUTH or KEY_ENCRYPT ? */ if (mhp->ext[ext->sadb_ext_type] != NULL) { ipseclog((LOG_DEBUG, "key_align: duplicate ext_type %u " "is passed.\n", ext->sadb_ext_type)); bzero_mbuf(m); m_freem(m); PFKEY_STAT_INCREMENT(pfkeystat.out_dupext); return EINVAL; } break; default: ipseclog((LOG_DEBUG, "key_align: invalid ext_type %u is passed.\n", ext->sadb_ext_type)); bzero_mbuf(m); m_freem(m); PFKEY_STAT_INCREMENT(pfkeystat.out_invexttype); return EINVAL; } extlen = PFKEY_UNUNIT64(ext->sadb_ext_len); if (key_validate_ext(ext, extlen)) { bzero_mbuf(m); m_freem(m); PFKEY_STAT_INCREMENT(pfkeystat.out_invlen); return EINVAL; } n = m_pulldown(m, off, extlen, &toff); if (!n) { /* m is already freed */ return ENOBUFS; } ext = (struct sadb_ext *)(void *)(mtod(n, caddr_t) + toff); mhp->ext[ext->sadb_ext_type] = ext; mhp->extoff[ext->sadb_ext_type] = off; mhp->extlen[ext->sadb_ext_type] = extlen; } if (off != end) { bzero_mbuf(m); m_freem(m); PFKEY_STAT_INCREMENT(pfkeystat.out_invlen); return EINVAL; } return 0; } static int key_validate_ext( const struct sadb_ext *ext, int len) { struct sockaddr *sa; enum { NONE, ADDR } checktype = NONE; int baselen = 0; const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len); if (len != PFKEY_UNUNIT64(ext->sadb_ext_len)) { return EINVAL; } /* if it does not match minimum/maximum length, bail */ if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) || ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0])) { return EINVAL; } if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type]) { return EINVAL; } if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type]) { return EINVAL; } /* more checks based on sadb_ext_type XXX need more */ switch (ext->sadb_ext_type) { case SADB_EXT_ADDRESS_SRC: case SADB_EXT_ADDRESS_DST: case SADB_EXT_ADDRESS_PROXY: case SADB_X_EXT_ADDR_RANGE_SRC_START: case SADB_X_EXT_ADDR_RANGE_SRC_END: case SADB_X_EXT_ADDR_RANGE_DST_START: case SADB_X_EXT_ADDR_RANGE_DST_END: case SADB_EXT_MIGRATE_ADDRESS_SRC: case SADB_EXT_MIGRATE_ADDRESS_DST: baselen = PFKEY_ALIGN8(sizeof(struct sadb_address)); checktype = ADDR; break; case SADB_EXT_IDENTITY_SRC: case SADB_EXT_IDENTITY_DST: if (((struct sadb_ident *)(uintptr_t)(size_t)ext)-> sadb_ident_type == SADB_X_IDENTTYPE_ADDR) { baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident)); checktype = ADDR; } else { checktype = NONE; } break; default: checktype = NONE; break; } switch (checktype) { case NONE: break; case ADDR: sa = (struct sockaddr *)((caddr_t)(uintptr_t)ext + baselen); if (len < baselen + sal) { return EINVAL; } if (baselen + PFKEY_ALIGN8(sa->sa_len) != len) { return EINVAL; } break; } /* check key bits length */ if (ext->sadb_ext_type == SADB_EXT_KEY_AUTH || ext->sadb_ext_type == SADB_EXT_KEY_ENCRYPT) { struct sadb_key *key = (struct sadb_key *)(uintptr_t)ext; if (len < (sizeof(struct sadb_key) + _KEYLEN(key))) { return EINVAL; } } return 0; } /* * XXX: maybe This function is called after INBOUND IPsec processing. * * Special check for tunnel-mode packets. * We must make some checks for consistency between inner and outer IP header. * * xxx more checks to be provided */ int key_checktunnelsanity( struct secasvar *sav, __unused u_int family, __unused caddr_t src, __unused caddr_t dst) { /* sanity check */ if (sav->sah == NULL) { panic("sav->sah == NULL at key_checktunnelsanity"); } /* XXX: check inner IP header */ return 1; } /* record data transfer on SA, and update timestamps */ void key_sa_recordxfer( struct secasvar *sav, struct mbuf *m) { if (!sav) { panic("key_sa_recordxfer called with sav == NULL"); } if (!m) { panic("key_sa_recordxfer called with m == NULL"); } if (!sav->lft_c) { return; } lck_mtx_lock(sadb_mutex); /* * XXX Currently, there is a difference of bytes size * between inbound and outbound processing. */ sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len; /* to check bytes lifetime is done in key_timehandler(). */ /* * We use the number of packets as the unit of * sadb_lifetime_allocations. We increment the variable * whenever {esp,ah}_{in,out}put is called. */ sav->lft_c->sadb_lifetime_allocations++; /* XXX check for expires? */ /* * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock, * in seconds. HARD and SOFT lifetime are measured by the time * difference (again in seconds) from sadb_lifetime_usetime. * * usetime * v expire expire * -----+-----+--------+---> t * <--------------> HARD * <-----> SOFT */ { struct timeval tv; microtime(&tv); sav->lft_c->sadb_lifetime_usetime = tv.tv_sec; /* XXX check for expires? */ } lck_mtx_unlock(sadb_mutex); return; } /* dumb version */ void key_sa_routechange( struct sockaddr *dst) { struct secashead *sah; struct route *ro; lck_mtx_lock(sadb_mutex); LIST_FOREACH(sah, &sahtree, chain) { ro = (struct route *)&sah->sa_route; if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) { ROUTE_RELEASE(ro); } } lck_mtx_unlock(sadb_mutex); return; } void key_sa_chgstate( struct secasvar *sav, u_int8_t state) { if (sav == NULL) { panic("key_sa_chgstate called with sav == NULL"); } if (sav->state == state) { return; } LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED); if (__LIST_CHAINED(sav)) { LIST_REMOVE(sav, chain); } sav->state = state; LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain); } void key_sa_stir_iv( struct secasvar *sav) { lck_mtx_lock(sadb_mutex); if (!sav->iv) { panic("key_sa_stir_iv called with sav == NULL"); } key_randomfill(sav->iv, sav->ivlen); lck_mtx_unlock(sadb_mutex); } /* XXX too much? */ static struct mbuf * key_alloc_mbuf( int l) { struct mbuf *m = NULL, *n; int len, t; len = l; while (len > 0) { MGET(n, M_DONTWAIT, MT_DATA); if (n && len > MLEN) { MCLGET(n, M_DONTWAIT); } if (!n) { m_freem(m); return NULL; } n->m_next = NULL; n->m_len = 0; n->m_len = M_TRAILINGSPACE(n); /* use the bottom of mbuf, hoping we can prepend afterwards */ if (n->m_len > len) { t = (n->m_len - len) & ~(sizeof(long) - 1); n->m_data += t; n->m_len = len; } len -= n->m_len; if (m) { m_cat(m, n); } else { m = n; } } return m; } static struct mbuf * key_setdumpsastats(u_int32_t dir, struct sastat *stats, u_int32_t max_stats, u_int64_t session_ids[], u_int32_t seq, u_int32_t pid) { struct mbuf *result = NULL, *m = NULL; m = key_setsadbmsg(SADB_GETSASTAT, 0, 0, seq, pid, 0); if (!m) { goto fail; } result = m; m = key_setsadbsession_id(session_ids); if (!m) { goto fail; } m_cat(result, m); m = key_setsadbsastat(dir, stats, max_stats); if (!m) { goto fail; } m_cat(result, m); if ((result->m_flags & M_PKTHDR) == 0) { goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return result; fail: if (result) { m_freem(result); } return NULL; } /* * SADB_GETSASTAT processing * dump all stats for matching entries in SAD. * * m will always be freed. */ static int key_getsastat(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { struct sadb_session_id *session_id; u_int32_t bufsize, arg_count, res_count; struct sadb_sastat *sa_stats_arg; struct sastat *sa_stats_sav = NULL; struct mbuf *n; int error = 0; /* sanity check */ if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL) { panic("%s: NULL pointer is passed.\n", __FUNCTION__); } if (mhp->ext[SADB_EXT_SESSION_ID] == NULL) { printf("%s: invalid message is passed. missing session-id.\n", __FUNCTION__); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SESSION_ID] < sizeof(struct sadb_session_id)) { printf("%s: invalid message is passed. short session-id.\n", __FUNCTION__); return key_senderror(so, m, EINVAL); } if (mhp->ext[SADB_EXT_SASTAT] == NULL) { printf("%s: invalid message is passed. missing stat args.\n", __FUNCTION__); return key_senderror(so, m, EINVAL); } if (mhp->extlen[SADB_EXT_SASTAT] < sizeof(*sa_stats_arg)) { printf("%s: invalid message is passed. short stat args.\n", __FUNCTION__); return key_senderror(so, m, EINVAL); } LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); // exit early if there are no active SAs if (ipsec_sav_count <= 0) { printf("%s: No active SAs.\n", __FUNCTION__); error = ENOENT; goto end; } bufsize = (ipsec_sav_count + 1) * sizeof(*sa_stats_sav); KMALLOC_WAIT(sa_stats_sav, __typeof__(sa_stats_sav), bufsize); if (sa_stats_sav == NULL) { printf("%s: No more memory.\n", __FUNCTION__); error = ENOMEM; goto end; } bzero(sa_stats_sav, bufsize); sa_stats_arg = (__typeof__(sa_stats_arg)) (void *)mhp->ext[SADB_EXT_SASTAT]; arg_count = sa_stats_arg->sadb_sastat_list_len; // exit early if there are no requested SAs if (arg_count == 0) { printf("%s: No SAs requested.\n", __FUNCTION__); error = ENOENT; goto end; } res_count = 0; if (key_getsastatbyspi((struct sastat *)(sa_stats_arg + 1), arg_count, sa_stats_sav, bufsize, &res_count)) { printf("%s: Error finding SAs.\n", __FUNCTION__); error = ENOENT; goto end; } if (!res_count) { printf("%s: No SAs found.\n", __FUNCTION__); error = ENOENT; goto end; } session_id = (__typeof__(session_id)) (void *)mhp->ext[SADB_EXT_SESSION_ID]; /* send this to the userland. */ n = key_setdumpsastats(sa_stats_arg->sadb_sastat_dir, sa_stats_sav, res_count, session_id->sadb_session_id_v, mhp->msg->sadb_msg_seq, mhp->msg->sadb_msg_pid); if (!n) { printf("%s: No bufs to dump stats.\n", __FUNCTION__); error = ENOBUFS; goto end; } key_sendup_mbuf(so, n, KEY_SENDUP_ALL); end: if (sa_stats_sav) { KFREE(sa_stats_sav); } if (error) { return key_senderror(so, m, error); } m_freem(m); return 0; } static void key_update_natt_keepalive_timestamp(struct secasvar *sav_sent, struct secasvar *sav_update) { struct secasindex saidx_swap_sent_addr; // exit early if two SAs are identical, or if sav_update is current if (sav_sent == sav_update || sav_update->natt_last_activity == natt_now) { return; } // assuming that (sav_update->remote_ike_port != 0 && (esp_udp_encap_port & 0xFFFF) != 0) bzero(&saidx_swap_sent_addr, sizeof(saidx_swap_sent_addr)); memcpy(&saidx_swap_sent_addr.src, &sav_sent->sah->saidx.dst, sizeof(saidx_swap_sent_addr.src)); memcpy(&saidx_swap_sent_addr.dst, &sav_sent->sah->saidx.src, sizeof(saidx_swap_sent_addr.dst)); saidx_swap_sent_addr.proto = sav_sent->sah->saidx.proto; saidx_swap_sent_addr.mode = sav_sent->sah->saidx.mode; // we ignore reqid for split-tunnel setups if (key_cmpsaidx(&sav_sent->sah->saidx, &sav_update->sah->saidx, CMP_MODE | CMP_PORT) || key_cmpsaidx(&saidx_swap_sent_addr, &sav_update->sah->saidx, CMP_MODE | CMP_PORT)) { sav_update->natt_last_activity = natt_now; } } static int key_send_delsp(struct secpolicy *sp) { struct mbuf *result = NULL, *m; if (sp == NULL) { goto fail; } /* set msg header */ m = key_setsadbmsg(SADB_X_SPDDELETE, 0, 0, 0, 0, 0); if (!m) { goto fail; } result = m; /* set sadb_address(es) for source */ if (sp->spidx.src_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_START, (struct sockaddr *)&sp->spidx.src_range.start, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_SRC_END, (struct sockaddr *)&sp->spidx.src_range.end, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } /* set sadb_address(es) for destination */ if (sp->spidx.dst_range.start.ss_len > 0) { m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_START, (struct sockaddr *)&sp->spidx.dst_range.start, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); m = key_setsadbaddr(SADB_X_EXT_ADDR_RANGE_DST_END, (struct sockaddr *)&sp->spidx.dst_range.end, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } else { m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd, sp->spidx.ul_proto); if (!m) { goto fail; } m_cat(result, m); } /* set secpolicy */ m = key_sp2msg(sp); if (!m) { goto fail; } m_cat(result, m); if ((result->m_flags & M_PKTHDR) == 0) { goto fail; } if (result->m_len < sizeof(struct sadb_msg)) { result = m_pullup(result, sizeof(struct sadb_msg)); if (result == NULL) { goto fail; } } result->m_pkthdr.len = 0; for (m = result; m; m = m->m_next) { result->m_pkthdr.len += m->m_len; } mtod(result, struct sadb_msg *)->sadb_msg_len = PFKEY_UNIT64(result->m_pkthdr.len); return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED); fail: if (result) { m_free(result); } return -1; } void key_delsp_for_ipsec_if(ifnet_t ipsec_if) { struct secashead *sah; struct secasvar *sav, *nextsav; u_int stateidx; u_int state; struct secpolicy *sp, *nextsp; int dir; if (ipsec_if == NULL) { return; } LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED); lck_mtx_lock(sadb_mutex); for (dir = 0; dir < IPSEC_DIR_MAX; dir++) { for (sp = LIST_FIRST(&sptree[dir]); sp != NULL; sp = nextsp) { nextsp = LIST_NEXT(sp, chain); if (sp->ipsec_if == ipsec_if) { ifnet_release(sp->ipsec_if); sp->ipsec_if = NULL; key_send_delsp(sp); sp->state = IPSEC_SPSTATE_DEAD; key_freesp(sp, KEY_SADB_LOCKED); } } } LIST_FOREACH(sah, &sahtree, chain) { if (sah->ipsec_if == ipsec_if) { /* This SAH is linked to the IPsec interface. It now needs to close. */ ifnet_release(sah->ipsec_if); sah->ipsec_if = NULL; for (stateidx = 0; stateidx < _ARRAYLEN(saorder_state_alive); stateidx++) { state = saorder_state_any[stateidx]; for (sav = LIST_FIRST(&sah->savtree[state]); sav != NULL; sav = nextsav) { nextsav = LIST_NEXT(sav, chain); key_sa_chgstate(sav, SADB_SASTATE_DEAD); key_freesav(sav, KEY_SADB_LOCKED); } } sah->state = SADB_SASTATE_DEAD; } } lck_mtx_unlock(sadb_mutex); } __private_extern__ u_int32_t key_fill_offload_frames_for_savs(ifnet_t ifp, struct ifnet_keepalive_offload_frame *frames_array, u_int32_t frames_array_count, size_t frame_data_offset) { struct secashead *sah = NULL; struct secasvar *sav = NULL; struct ifnet_keepalive_offload_frame *frame = frames_array; u_int32_t frame_index = 0; if (frame == NULL || frames_array_count == 0) { return frame_index; } lck_mtx_lock(sadb_mutex); LIST_FOREACH(sah, &sahtree, chain) { LIST_FOREACH(sav, &sah->savtree[SADB_SASTATE_MATURE], chain) { if (ipsec_fill_offload_frame(ifp, sav, frame, frame_data_offset)) { frame_index++; if (frame_index >= frames_array_count) { lck_mtx_unlock(sadb_mutex); return frame_index; } frame = &(frames_array[frame_index]); } } } lck_mtx_unlock(sadb_mutex); return frame_index; }
25.267175
165
0.656238
[ "object" ]
b7cc177b19b5f3e2b6d160cd4dd080a46c4da556
6,662
h
C
common/beerocks/bcl/include/bcl/network/network_utils.h
DanielEdriPurpl/prplMesh
6c9f9d1773e5caf8aa906af70b2b8df92ca94139
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
85
2018-10-24T22:18:35.000Z
2022-02-24T09:11:56.000Z
common/beerocks/bcl/include/bcl/network/network_utils.h
DanielEdriPurpl/prplMesh
6c9f9d1773e5caf8aa906af70b2b8df92ca94139
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
1,105
2018-10-03T14:04:58.000Z
2020-08-14T21:22:55.000Z
common/beerocks/bcl/include/bcl/network/network_utils.h
orenvor/prplMesh
aebd37e7e194acd9fefa3cdd64fb84a8c9f733bd
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
43
2018-11-12T22:51:40.000Z
2021-12-26T07:40:39.000Z
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * SPDX-FileCopyrightText: 2016-2020 the prplMesh contributors (see AUTHORS.md) * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #ifndef _NETWORK_UTILS_H_ #define _NETWORK_UTILS_H_ #include "../beerocks_os_utils.h" #include "socket.h" #include "net_struct.h" #include <cstdint> #include <easylogging++.h> #include <string> #include <vector> #include <netinet/ether.h> #include <netinet/ip.h> // IP_MAXPACKET (which is 65535) #define ETH_HDRLEN 14 // Ethernet header length #define IP4_HDRLEN 20 // IPv4 header length #define ARP_HDRLEN 28 // ARP header length // Define some constants. #ifndef ARPOP_REQUEST #define ARPOP_REQUEST 1 // Taken from <linux/if_arp.h> #define ARPOP_REPLY 2 #endif namespace beerocks { namespace net { class network_utils { public: static const std::string ZERO_IP_STRING; static const std::string ZERO_MAC_STRING; static const sMacAddr ZERO_MAC; static const std::string WILD_MAC_STRING; static const std::string MULTICAST_1905_MAC_ADDR; typedef struct { uint16_t htype; uint16_t ptype; uint8_t hlen; uint8_t plen; uint16_t opcode; uint8_t sender_mac[6]; uint8_t sender_ip[4]; uint8_t target_mac[6]; uint8_t target_ip[4]; } arp_hdr; typedef struct { std::string iface; uint32_t iface_idx; std::string connection_name; std::string mac; std::string ip; std::string netmask; std::string broadcast_ip; std::string gw; } ip_info; typedef struct { std::string iface; std::string mac; std::string ip; std::string netmask; std::string ip_gw; std::string broadcast_ip; } iface_info; typedef struct { struct ether_addr hwa; struct in_addr ipa; struct in_addr bcast; struct in_addr nmask; } raw_iface_info; static bool is_valid_mac(std::string mac); static std::string ipv4_to_string(const net::sIpv4Addr &ip); static std::string ipv4_to_string(const uint8_t *ipv4); static std::string ipv4_to_string(uint32_t ip); static net::sIpv4Addr ipv4_from_string(const std::string &ip_str); static void ipv4_from_string(uint8_t *buf, const std::string &ip); static uint32_t uint_ipv4_from_array(void *ip); static uint32_t uint_ipv4_from_string(const std::string &ip_str); static std::vector<network_utils::ip_info> get_ip_list(); static int get_iface_info(network_utils::iface_info &info, const std::string &iface_name); static bool get_raw_iface_info(const std::string &iface_name, raw_iface_info &info); /** * @brief Get the arp table as unordered map object of pairs <MAC, IP> or <IP, MAC>. * The key of the map can be either a MAC address or an IP address, depends on the 'mac_as_key' * argument value. * If 'mac_as_key' is 'true' then the key is a MAC address, otherwise the key is an IP address. * * @param[in] mac_as_key Decide whether the key of the returned unordered map object * is a MAC or an IP. * @return std::shared_ptr<std::unordered_map<std::string, std::string>> */ static std::shared_ptr<std::unordered_map<std::string, std::string>> get_arp_table(bool mac_as_key = true); //temp static std::string get_mac_from_arp_table(const std::string &ipv4); static std::vector<std::string> linux_get_iface_list_from_bridge(const std::string &bridge); /** * @brief Gets the interface index corresponding to a particular name. * * @param iface_name The name of the network interface. * @return interface index or 0 if no interface exists with the name given. */ static uint32_t linux_get_iface_index(const std::string &iface_name); /** * @brief Gets the interface name corresponding to a particular index. * * @param iface_index The index of the network interface. * @return interface name or empty string if no interface exists with the index given. */ static std::string linux_get_iface_name(uint32_t iface_index); static bool linux_add_iface_to_bridge(const std::string &bridge, const std::string &iface); static bool linux_remove_iface_from_bridge(const std::string &bridge, const std::string &iface); static bool linux_iface_ctrl(const std::string &iface, bool up, std::string ip = "", const std::string &netmask = ""); static bool linux_iface_get_mac(const std::string &iface, std::string &mac); /** * @brief Gets the interface name of the network interface with given MAC address. * * @param[in] mac MAC address of the network interface. * @param[out] iface On success, name of the network interface. On error, empty string. * * @return True on success and false otherwise. */ static bool linux_iface_get_name(const sMacAddr &mac, std::string &iface); static bool linux_iface_get_ip(const std::string &iface, std::string &ip); static bool linux_iface_get_pci_info(const std::string &iface, std::string &pci_id); static bool linux_iface_exists(const std::string &iface); static bool linux_iface_is_up(const std::string &iface); static bool linux_iface_is_up_and_running(const std::string &iface); /** * @brief Gets the speed of a network interface. * * @param[in] iface Name of the network interface. * @param[out] speed On success, speed in Mbps of the network interface as defined in SPEED_* * macros included in ethtool.h * * @return True if speed could be successfully obtained and false otherwise. */ static bool linux_iface_get_speed(const std::string &iface, uint32_t &speed); /** * @brief Gets interface statistics for the given network interface. * * @param[in] iface Name of the local network interface. * @param[out] iface_stats Interface statistics. * * @return True on success and false otherwise. */ static bool get_iface_stats(const std::string &iface, sInterfaceStats &iface_stats); static bool arp_send(const std::string &iface, const std::string &dst_ip, const std::string &src_ip, sMacAddr dst_mac, sMacAddr src_mac, int count, int arp_socket = -1); static bool icmp_send(const std::string &ip, uint16_t id, int count, int icmp_socket); static uint16_t icmp_checksum(uint16_t *buf, int32_t len); }; } // namespace net } // namespace beerocks #endif //_NETWORK_UTILS_H_
36.010811
100
0.68553
[ "object", "vector" ]
b7cd95434e6c9edea17b1be20a40279bcbb0c307
13,831
h
C
util/alphaev67-unknown-linux-gnu/alphaev67-unknown-linux-gnu/include/c++/4.3.2/ext/typelist.h
qiyancos/gem5-withChinese-Comment
aae692c99effa43035ebc8702a5bc5dd68bd6773
[ "BSD-3-Clause" ]
37
2015-01-11T20:08:48.000Z
2022-01-06T17:25:22.000Z
util/alphaev67-unknown-linux-gnu/alphaev67-unknown-linux-gnu/include/c++/4.3.2/ext/typelist.h
qiyancos/gem5-withChinese-Comment
aae692c99effa43035ebc8702a5bc5dd68bd6773
[ "BSD-3-Clause" ]
26
2019-09-20T06:46:05.000Z
2022-03-11T08:07:14.000Z
util/alphaev67-unknown-linux-gnu/alphaev67-unknown-linux-gnu/include/c++/4.3.2/ext/typelist.h
qiyancos/gem5-withChinese-Comment
aae692c99effa43035ebc8702a5bc5dd68bd6773
[ "BSD-3-Clause" ]
14
2019-07-15T06:42:39.000Z
2022-02-15T10:32:28.000Z
// -*- C++ -*- // Copyright (C) 2005, 2006 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice and // this permission notice appear in supporting documentation. None of // the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. /** * @file typelist.h * Contains typelist_chain definitions. * Typelists are an idea by Andrei Alexandrescu. */ #ifndef _TYPELIST_H #define _TYPELIST_H 1 #include <ext/type_traits.h> _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx) /** @namespace __gnu_cxx::typelist * @brief GNU typelist extensions for public compile-time use. */ namespace typelist { struct null_type { }; template<typename Root> struct node { typedef Root root; }; // Forward declarations of functors. template<typename Hd, typename Typelist> struct chain { typedef Hd head; typedef Typelist tail; }; template<typename Fn, class Typelist> void apply(Fn&, Typelist); template<typename Typelist0, typename Typelist1> struct append; template<typename Typelist_Typelist> struct append_typelist; template<typename Typelist, typename T> struct contains; template<typename Typelist, template<typename T> class Pred> struct filter; template<typename Typelist, int i> struct at_index; template<typename Typelist, template<typename T> class Transform> struct transform; template<typename Typelist_Typelist> struct flatten; template<typename Typelist> struct from_first; template<typename T1> struct create1; template<typename T1, typename T2> struct create2; template<typename T1, typename T2, typename T3> struct create3; template<typename T1, typename T2, typename T3, typename T4> struct create4; template<typename T1, typename T2, typename T3, typename T4, typename T5> struct create5; template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> struct create6; } // namespace typelist _GLIBCXX_END_NAMESPACE _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx) namespace typelist { namespace detail { template<typename Fn, typename Typelist_Chain> struct apply_; template<typename Fn, typename Hd, typename Tl> struct apply_<Fn, chain<Hd, Tl> > { void operator() (Fn& f) { f.operator()(Hd()); apply_<Fn, Tl> next; next(f); } }; template<typename Fn> struct apply_<Fn, null_type> { void operator()(Fn&) { } }; template<typename Typelist_Chain0, typename Typelist_Chain1> struct append_; template<typename Hd, typename Tl, typename Typelist_Chain> struct append_<chain<Hd, Tl>, Typelist_Chain> { private: typedef append_<Tl, Typelist_Chain> append_type; public: typedef chain<Hd, typename append_type::type> type; }; template<typename Typelist_Chain> struct append_<null_type, Typelist_Chain> { typedef Typelist_Chain type; }; template<typename Typelist_Chain> struct append_<Typelist_Chain, null_type> { typedef Typelist_Chain type; }; template<> struct append_<null_type, null_type> { typedef null_type type; }; template<typename Typelist_Typelist_Chain> struct append_typelist_; template<typename Hd> struct append_typelist_<chain<Hd, null_type> > { typedef chain<Hd, null_type> type; }; template<typename Hd, typename Tl> struct append_typelist_<chain< Hd, Tl> > { private: typedef typename append_typelist_<Tl>::type rest_type; public: typedef typename append<Hd, node<rest_type> >::type::root type; }; template<typename Typelist_Chain, typename T> struct contains_; template<typename T> struct contains_<null_type, T> { enum { value = false }; }; template<typename Hd, typename Tl, typename T> struct contains_<chain<Hd, Tl>, T> { enum { value = contains_<Tl, T>::value }; }; template<typename Tl, typename T> struct contains_<chain<T, Tl>, T> { enum { value = true }; }; template<typename Typelist_Chain, template<typename T> class Pred> struct chain_filter_; template<template<typename T> class Pred> struct chain_filter_<null_type, Pred> { typedef null_type type; }; template<typename Hd, typename Tl, template<typename T> class Pred> struct chain_filter_<chain<Hd, Tl>, Pred> { private: enum { include_hd = Pred<Hd>::value }; typedef typename chain_filter_<Tl, Pred>::type rest_type; typedef chain<Hd, rest_type> chain_type; public: typedef typename __conditional_type<include_hd, chain_type, rest_type>::__type type; }; template<typename Typelist_Chain, int i> struct chain_at_index_; template<typename Hd, typename Tl> struct chain_at_index_<chain<Hd, Tl>, 0> { typedef Hd type; }; template<typename Hd, typename Tl, int i> struct chain_at_index_<chain<Hd, Tl>, i> { typedef typename chain_at_index_<Tl, i - 1>::type type; }; template<class Typelist_Chain, template<typename T> class Transform> struct chain_transform_; template<template<typename T> class Transform> struct chain_transform_<null_type, Transform> { typedef null_type type; }; template<class Hd, class Tl, template<typename T> class Transform> struct chain_transform_<chain<Hd, Tl>, Transform> { private: typedef typename chain_transform_<Tl, Transform>::type rest_type; typedef typename Transform<Hd>::type transform_type; public: typedef chain<transform_type, rest_type> type; }; template<typename Typelist_Typelist_Chain> struct chain_flatten_; template<typename Hd_Tl> struct chain_flatten_<chain<Hd_Tl, null_type> > { typedef typename Hd_Tl::root type; }; template<typename Hd_Typelist, class Tl_Typelist> struct chain_flatten_<chain<Hd_Typelist, Tl_Typelist> > { private: typedef typename chain_flatten_<Tl_Typelist>::type rest_type; typedef append<Hd_Typelist, node<rest_type> > append_type; public: typedef typename append_type::type::root type; }; } // namespace detail } // namespace typelist _GLIBCXX_END_NAMESPACE #define _GLIBCXX_TYPELIST_CHAIN1(X0) __gnu_cxx::typelist::chain<X0, __gnu_cxx::typelist::null_type> #define _GLIBCXX_TYPELIST_CHAIN2(X0, X1) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN1(X1) > #define _GLIBCXX_TYPELIST_CHAIN3(X0, X1, X2) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN2(X1, X2) > #define _GLIBCXX_TYPELIST_CHAIN4(X0, X1, X2, X3) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN3(X1, X2, X3) > #define _GLIBCXX_TYPELIST_CHAIN5(X0, X1, X2, X3, X4) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN4(X1, X2, X3, X4) > #define _GLIBCXX_TYPELIST_CHAIN6(X0, X1, X2, X3, X4, X5) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN5(X1, X2, X3, X4, X5) > #define _GLIBCXX_TYPELIST_CHAIN7(X0, X1, X2, X3, X4, X5, X6) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN6(X1, X2, X3, X4, X5, X6) > #define _GLIBCXX_TYPELIST_CHAIN8(X0, X1, X2, X3, X4, X5, X6, X7) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN7(X1, X2, X3, X4, X5, X6, X7) > #define _GLIBCXX_TYPELIST_CHAIN9(X0, X1, X2, X3, X4, X5, X6, X7, X8) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN8(X1, X2, X3, X4, X5, X6, X7, X8) > #define _GLIBCXX_TYPELIST_CHAIN10(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN9(X1, X2, X3, X4, X5, X6, X7, X8, X9) > #define _GLIBCXX_TYPELIST_CHAIN11(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN10(X1, X2, X3, X4, X5, X6, X7, X8, X9, X10) > #define _GLIBCXX_TYPELIST_CHAIN12(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN11(X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11) > #define _GLIBCXX_TYPELIST_CHAIN13(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN12(X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12) > #define _GLIBCXX_TYPELIST_CHAIN14(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN13(X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13) > #define _GLIBCXX_TYPELIST_CHAIN15(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14) __gnu_cxx::typelist::chain<X0, _GLIBCXX_TYPELIST_CHAIN14(X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14) > _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx) namespace typelist { template<typename Fn, class Typelist> void apply(Fn& fn, Typelist) { detail::apply_<Fn, typename Typelist::root> a; a(fn); } template<typename Typelist0, typename Typelist1> struct append { private: typedef typename Typelist0::root root0_type; typedef typename Typelist1::root root1_type; typedef detail::append_<root0_type, root1_type> append_type; public: typedef node<typename append_type::type> type; }; template<typename Typelist_Typelist> struct append_typelist { private: typedef typename Typelist_Typelist::root root_type; typedef detail::append_typelist_<root_type> append_type; public: typedef node<typename append_type::type> type; }; template<typename Typelist, typename T> struct contains { private: typedef typename Typelist::root root_type; public: enum { value = detail::contains_<root_type, T>::value }; }; template<typename Typelist, template<typename T> class Pred> struct filter { private: typedef typename Typelist::root root_type; typedef detail::chain_filter_<root_type, Pred> filter_type; public: typedef node<typename filter_type::type> type; }; template<typename Typelist, int i> struct at_index { private: typedef typename Typelist::root root_type; typedef detail::chain_at_index_<root_type, i> index_type; public: typedef typename index_type::type type; }; template<typename Typelist, template<typename T> class Transform> struct transform { private: typedef typename Typelist::root root_type; typedef detail::chain_transform_<root_type, Transform> transform_type; public: typedef node<typename transform_type::type> type; }; template<typename Typelist_Typelist> struct flatten { private: typedef typename Typelist_Typelist::root root_type; typedef typename detail::chain_flatten_<root_type>::type flatten_type; public: typedef node<flatten_type> type; }; template<typename Typelist> struct from_first { private: typedef typename at_index<Typelist, 0>::type first_type; public: typedef node<chain<first_type, null_type> > type; }; template<typename T1> struct create1 { typedef node<_GLIBCXX_TYPELIST_CHAIN1(T1)> type; }; template<typename T1, typename T2> struct create2 { typedef node<_GLIBCXX_TYPELIST_CHAIN2(T1,T2)> type; }; template<typename T1, typename T2, typename T3> struct create3 { typedef node<_GLIBCXX_TYPELIST_CHAIN3(T1,T2,T3)> type; }; template<typename T1, typename T2, typename T3, typename T4> struct create4 { typedef node<_GLIBCXX_TYPELIST_CHAIN4(T1,T2,T3,T4)> type; }; template<typename T1, typename T2, typename T3, typename T4, typename T5> struct create5 { typedef node<_GLIBCXX_TYPELIST_CHAIN5(T1,T2,T3,T4,T5)> type; }; template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> struct create6 { typedef node<_GLIBCXX_TYPELIST_CHAIN6(T1,T2,T3,T4,T5,T6)> type; }; } // namespace typelist _GLIBCXX_END_NAMESPACE #endif
28.995807
218
0.692358
[ "transform" ]
b7d06c6430957ee030314a38acf9c98d508e6604
6,995
c
C
ext/ruby_prof/rp_measurement.c
smcgivern/ruby-prof
e6c7d9b605e327f4852104ac2dcd989ad80310f9
[ "BSD-2-Clause" ]
null
null
null
ext/ruby_prof/rp_measurement.c
smcgivern/ruby-prof
e6c7d9b605e327f4852104ac2dcd989ad80310f9
[ "BSD-2-Clause" ]
null
null
null
ext/ruby_prof/rp_measurement.c
smcgivern/ruby-prof
e6c7d9b605e327f4852104ac2dcd989ad80310f9
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2005-2019 Shugo Maeda <shugo@ruby-lang.org> and Charlie Savage <cfis@savagexi.com> Please see the LICENSE file for copyright and distribution information */ #include "rp_measurement.h" VALUE mMeasure; VALUE cRpMeasurement; prof_measurer_t* prof_measurer_allocations(bool track_allocations); prof_measurer_t* prof_measurer_memory(bool track_allocations); prof_measurer_t* prof_measurer_process_time(bool track_allocations); prof_measurer_t* prof_measurer_wall_time(bool track_allocations); void rp_init_measure_allocations(void); void rp_init_measure_memory(void); void rp_init_measure_process_time(void); void rp_init_measure_wall_time(void); prof_measurer_t* prof_get_measurer(prof_measure_mode_t measure, bool track_allocations) { switch (measure) { case MEASURE_WALL_TIME: return prof_measurer_wall_time(track_allocations); case MEASURE_PROCESS_TIME: return prof_measurer_process_time(track_allocations); case MEASURE_ALLOCATIONS: return prof_measurer_allocations(track_allocations); case MEASURE_MEMORY: return prof_measurer_memory(track_allocations); default: rb_raise(rb_eArgError, "Unknown measure mode: %d", measure); } }; double prof_measure(prof_measurer_t* measurer, rb_trace_arg_t* trace_arg) { double measurement = measurer->measure(trace_arg); return measurement * measurer->multiplier; } /* ======= prof_measurement_t ========*/ prof_measurement_t* prof_measurement_create(void) { prof_measurement_t* result = ALLOC(prof_measurement_t); result->total_time = 0; result->self_time = 0; result->wait_time = 0; result->called = 0; result->object = Qnil; return result; } void prof_measurement_mark(void* data) { prof_measurement_t* measurement_data = (prof_measurement_t*)data; if (measurement_data->object != Qnil) rb_gc_mark(measurement_data->object); } static void prof_measurement_ruby_gc_free(void* data) { // Measurements are freed by their owning object (call info or method) prof_measurement_t* measurement = (prof_measurement_t*)data; measurement->object = Qnil; } void prof_measurement_free(prof_measurement_t* measurement) { /* Has this measurement object been accessed by Ruby? If yes clean it up so to avoid a segmentation fault. */ if (measurement->object != Qnil) { RDATA(measurement->object)->dmark = NULL; RDATA(measurement->object)->dfree = NULL; RDATA(measurement->object)->data = NULL; measurement->object = Qnil; } xfree(measurement); } size_t prof_measurement_size(const void* data) { return sizeof(prof_measurement_t); } VALUE prof_measurement_wrap(prof_measurement_t* measurement) { if (measurement->object == Qnil) { measurement->object = Data_Wrap_Struct(cRpMeasurement, NULL, prof_measurement_ruby_gc_free, measurement); } return measurement->object; } static VALUE prof_measurement_allocate(VALUE klass) { prof_measurement_t* measurement = prof_measurement_create(); measurement->object = prof_measurement_wrap(measurement); return measurement->object; } prof_measurement_t* prof_get_measurement(VALUE self) { /* Can't use Data_Get_Struct because that triggers the event hook ending up in endless recursion. */ prof_measurement_t* result = DATA_PTR(self); if (!result) rb_raise(rb_eRuntimeError, "This RubyProf::Measurement instance has already been freed, likely because its profile has been freed."); return result; } /* call-seq: total_time -> float Returns the total amount of time spent in this method and its children. */ static VALUE prof_measurement_total_time(VALUE self) { prof_measurement_t* result = prof_get_measurement(self); return rb_float_new(result->total_time); } /* call-seq: self_time -> float Returns the total amount of time spent in this method. */ static VALUE prof_measurement_self_time(VALUE self) { prof_measurement_t* result = prof_get_measurement(self); return rb_float_new(result->self_time); } /* call-seq: wait_time -> float Returns the total amount of time this method waited for other threads. */ static VALUE prof_measurement_wait_time(VALUE self) { prof_measurement_t* result = prof_get_measurement(self); return rb_float_new(result->wait_time); } /* call-seq: called -> int Returns the total amount of times this method was called. */ static VALUE prof_measurement_called(VALUE self) { prof_measurement_t* result = prof_get_measurement(self); return INT2NUM(result->called); } /* call-seq: called=n -> n Sets the call count to n. */ static VALUE prof_measurement_set_called(VALUE self, VALUE called) { prof_measurement_t* result = prof_get_measurement(self); result->called = NUM2INT(called); return called; } /* :nodoc: */ static VALUE prof_measurement_dump(VALUE self) { prof_measurement_t* measurement_data = prof_get_measurement(self); VALUE result = rb_hash_new(); rb_hash_aset(result, ID2SYM(rb_intern("total_time")), rb_float_new(measurement_data->total_time)); rb_hash_aset(result, ID2SYM(rb_intern("self_time")), rb_float_new(measurement_data->self_time)); rb_hash_aset(result, ID2SYM(rb_intern("wait_time")), rb_float_new(measurement_data->wait_time)); rb_hash_aset(result, ID2SYM(rb_intern("called")), INT2FIX(measurement_data->called)); return result; } /* :nodoc: */ static VALUE prof_measurement_load(VALUE self, VALUE data) { prof_measurement_t* measurement = prof_get_measurement(self); measurement->object = self; measurement->total_time = rb_num2dbl(rb_hash_aref(data, ID2SYM(rb_intern("total_time")))); measurement->self_time = rb_num2dbl(rb_hash_aref(data, ID2SYM(rb_intern("self_time")))); measurement->wait_time = rb_num2dbl(rb_hash_aref(data, ID2SYM(rb_intern("wait_time")))); measurement->called = FIX2INT(rb_hash_aref(data, ID2SYM(rb_intern("called")))); return data; } void rp_init_measure() { mMeasure = rb_define_module_under(mProf, "Measure"); rp_init_measure_wall_time(); rp_init_measure_process_time(); rp_init_measure_allocations(); rp_init_measure_memory(); cRpMeasurement = rb_define_class_under(mProf, "Measurement", rb_cData); rb_undef_method(CLASS_OF(cRpMeasurement), "new"); rb_define_alloc_func(cRpMeasurement, prof_measurement_allocate); rb_define_method(cRpMeasurement, "called", prof_measurement_called, 0); rb_define_method(cRpMeasurement, "called=", prof_measurement_set_called, 1); rb_define_method(cRpMeasurement, "total_time", prof_measurement_total_time, 0); rb_define_method(cRpMeasurement, "self_time", prof_measurement_self_time, 0); rb_define_method(cRpMeasurement, "wait_time", prof_measurement_wait_time, 0); rb_define_method(cRpMeasurement, "_dump_data", prof_measurement_dump, 0); rb_define_method(cRpMeasurement, "_load_data", prof_measurement_load, 1); }
31.509009
141
0.749535
[ "object" ]
b7d2a4bad0b5c2fce99cd962a6ae9d3950f54f39
2,420
h
C
Css343Lab4/ShowHistory.h
Whompithian/css343-project4
b527c4a35126c0be41bf0a2c0d70d1a2d986b164
[ "MIT" ]
null
null
null
Css343Lab4/ShowHistory.h
Whompithian/css343-project4
b527c4a35126c0be41bf0a2c0d70d1a2d986b164
[ "MIT" ]
null
null
null
Css343Lab4/ShowHistory.h
Whompithian/css343-project4
b527c4a35126c0be41bf0a2c0d70d1a2d986b164
[ "MIT" ]
null
null
null
/* * File: ShowHistory.h * Author: brendan * * Created on March 2, 2012, 4:27 PM */ #ifndef _SHOWHISTORY_H #define _SHOWHISTORY_H #include "Transaction.h" class ShowHistory : public Transaction { public: ShowHistory(); virtual ~ShowHistory(); /**---------------------- create() -------------------------------------------- * Creates a new ShowHistory object and returns a Transaction pointer to it. * @param infile A character stream containing information used to create the * desired type of Transaction. The first line must consist only * of an integer. * @pre infile contains a valid initialization string. * @post A new ShowHistory object exists. The characters used to initialize the * ShowHistory have been removed from infile. * @return A Transaction pointer to a ShowHistory object. */ virtual Transaction* create(ifstream& infile) const; /**---------------------- copy() ---------------------------------------------- * Creates a new ShowHistory object that is a copy of this one and returns a * Transaction pointer to it. * @pre None. * @post A new ShowHistory object exists that is a copy of this one. * @return A Transaction pointer to a new ShowHistory object. */ virtual Transaction* copy(void) const; /**---------------------- process() ------------------------------------------- * Processes this ShowHistory in some MOVIEStore. A Customer is located in the * target and that Customer's showHitory() method is called. * @param target A pointer to a MOVIEStore to act upon. * @pre MOVIEStore provides the expected interface. The Customer identified by * this Transaction exists in the target. * @post target remains unaltered. */ virtual bool process(MOVIEStore& target) const; /**---------------------- display() ------------------------------------------- * Displays information about this Transaction, including its type. If this * Transaction holds a Merch object, then display() is called on that object to * also display its information. * @param output The character stream to which this Transaction will display * its information. * @pre Merch defines a display() method. * @post output contains a character string that describes this Transaction. */ virtual void display(ostream& output) const; private: }; // end class ShowHistory #endif /* _SHOWHISTORY_H */
34.571429
79
0.638017
[ "object" ]
b7d69562af4f6961af7060c18445036991c44c65
3,317
h
C
third_party/txt/src/minikin/MinikinFont.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
5,823
2015-09-20T02:43:18.000Z
2022-03-31T23:38:55.000Z
third_party/txt/src/minikin/MinikinFont.h
shoryukenn/engine
0dc86cda19d55aba8b719231c11306eeaca4b798
[ "BSD-3-Clause" ]
20,081
2015-09-19T16:07:59.000Z
2022-03-31T23:33:26.000Z
third_party/txt/src/minikin/MinikinFont.h
shoryukenn/engine
0dc86cda19d55aba8b719231c11306eeaca4b798
[ "BSD-3-Clause" ]
5,383
2015-09-24T22:49:53.000Z
2022-03-31T14:33:51.000Z
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINIKIN_FONT_H #define MINIKIN_FONT_H #include <memory> #include <string> #include <minikin/FontFamily.h> #include <minikin/Hyphenator.h> // An abstraction for platform fonts, allowing Minikin to be used with // multiple actual implementations of fonts. namespace minikin { class MinikinFont; // Possibly move into own .h file? // Note: if you add a field here, either add it to LayoutCacheKey or to // skipCache() struct MinikinPaint { MinikinPaint() : font(nullptr), size(0), scaleX(0), skewX(0), letterSpacing(0), wordSpacing(0), paintFlags(0), fakery(), hyphenEdit(), fontFeatureSettings() {} bool skipCache() const { return !fontFeatureSettings.empty(); } MinikinFont* font; float size; float scaleX; float skewX; float letterSpacing; float wordSpacing; uint32_t paintFlags; FontFakery fakery; HyphenEdit hyphenEdit; std::string fontFeatureSettings; }; // Only a few flags affect layout, but those that do should have values // consistent with Android's paint flags. enum MinikinPaintFlags { LinearTextFlag = 0x40, }; struct MinikinRect { float mLeft, mTop, mRight, mBottom; bool isEmpty() const { return mLeft == mRight || mTop == mBottom; } void set(const MinikinRect& r) { mLeft = r.mLeft; mTop = r.mTop; mRight = r.mRight; mBottom = r.mBottom; } void offset(float dx, float dy) { mLeft += dx; mTop += dy; mRight += dx; mBottom += dy; } void setEmpty() { mLeft = mTop = mRight = mBottom = 0; } void join(const MinikinRect& r); }; // Callback for freeing data typedef void (*MinikinDestroyFunc)(void* data); class MinikinFont { public: explicit MinikinFont(int32_t uniqueId) : mUniqueId(uniqueId) {} virtual ~MinikinFont(); virtual float GetHorizontalAdvance(uint32_t glyph_id, const MinikinPaint& paint) const = 0; virtual void GetBounds(MinikinRect* bounds, uint32_t glyph_id, const MinikinPaint& paint) const = 0; virtual hb_face_t* CreateHarfBuzzFace() const { return nullptr; } virtual const std::vector<minikin::FontVariation>& GetAxes() const = 0; virtual std::shared_ptr<MinikinFont> createFontWithVariation( const std::vector<FontVariation>&) const { return nullptr; } static uint32_t MakeTag(char c1, char c2, char c3, char c4) { return ((uint32_t)c1 << 24) | ((uint32_t)c2 << 16) | ((uint32_t)c3 << 8) | (uint32_t)c4; } int32_t GetUniqueId() const { return mUniqueId; } private: const int32_t mUniqueId; }; } // namespace minikin #endif // MINIKIN_FONT_H
26.11811
78
0.672897
[ "vector" ]
a1052e7460961c849d01b67868b42cff2c147da7
5,503
h
C
fdbrpc/ITLSPlugin.h
fkorotkov/foundationdb
6adbd5b3876640be918286cb8e09ed434fa1bca6
[ "Apache-2.0" ]
1
2019-10-16T04:00:57.000Z
2019-10-16T04:00:57.000Z
fdbrpc/ITLSPlugin.h
prettyshuang/foundationdb
90773ec03b54440eab64bb0fba232a760c2a5230
[ "Apache-2.0" ]
1
2021-06-25T15:16:31.000Z
2021-06-25T15:16:31.000Z
fdbrpc/ITLSPlugin.h
prettyshuang/foundationdb
90773ec03b54440eab64bb0fba232a760c2a5230
[ "Apache-2.0" ]
1
2021-03-08T01:43:55.000Z
2021-03-08T01:43:55.000Z
/* * ITLSPlugin.h * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FDB_ITLSPLUGIN_H #define FDB_ITLSPLUGIN_H #pragma once #include <stdint.h> struct ITLSSession { enum { SUCCESS = 0, WANT_READ = -1, WANT_WRITE = -2, FAILED = -3 }; virtual void addref() = 0; virtual void delref() = 0; // handshake should return SUCCESS if the handshake is complete, // FAILED on fatal error, or one of WANT_READ or WANT_WRITE if the // handshake should be reattempted after more data can be // read/written on the underlying connection. virtual int handshake() = 0; // read should return the (non-zero) number of bytes read, // WANT_READ or WANT_WRITE if the operation is blocked by the // underlying stream, or FAILED if there is an error (including a // closed connection). virtual int read(uint8_t* data, int length) = 0; // write should return the (non-zero) number of bytes written, or // WANT_READ or WANT_WRITE if the operation is blocked by the // underlying stream, or FAILED if there is an error. virtual int write(const uint8_t* data, int length) = 0; }; // Returns the number of bytes sent (possibly 0), or -1 on error // (including connection close) typedef int (*TLSSendCallbackFunc)(void* ctx, const uint8_t* buf, int len); // Returns the number of bytes read (possibly 0), or -1 on error // (including connection close) typedef int (*TLSRecvCallbackFunc)(void* ctx, uint8_t* buf, int len); struct ITLSPolicy { virtual void addref() = 0; virtual void delref() = 0; // set_cert_data should import the provided certificate list and // associate it with this policy. cert_data will point to a PEM // encoded certificate list, ordered such that each certificate // certifies the one befor it. // // cert_data may additionally contain key information, which must // be ignored. // // set_cert_data should return true if the operation succeeded, // and false otherwise. After the first call to create_session for // a given policy, set_cert_data should immediately return false // if called. virtual bool set_cert_data(const uint8_t* cert_data, int cert_len) = 0; // set_key_data should import the provided private key and // associate it with this policy. key_data will point to a PEM // encoded key. // // key_data may additionally contain certificate information, // which must be ignored. // // set_key_data should return true if the operation succeeded, and // false otherwise. After the first call to create_session for a // given policy, set_key_data should immediately return false if // called. virtual bool set_key_data(const uint8_t* key_data, int key_len) = 0; // set_verify_peers should modify the validation rules for // verifying a peer during connection handshake. The format of // verify_peers is implementation specific. // // set_verify_peers should return true if the operation succeed, // and false otherwise. After the first call to create_session for // a given policy, set_verify_peers should immediately return // false if called. virtual bool set_verify_peers(const uint8_t* verify_peers, int verify_peers_len) = 0; // create_session should return a new object that implements // ITLSSession, associated with this policy. After the first call // to create_session for a given policy, further calls to // ITLSPolicy::set_* will fail and return false. // // The newly created session should use send_func and recv_func to // send and receive data on the underlying transport, and must // provide send_ctx/recv_ctx to the callbacks. // // uid should only be provided when invoking an ITLSLogFunc, which // will use it to identify this session. virtual ITLSSession* create_session(bool is_client, TLSSendCallbackFunc send_func, void* send_ctx, TLSRecvCallbackFunc recv_func, void* recv_ctx, void* uid ) = 0; }; // Logs a message/error to the appropriate trace log. // // event must be a valid XML attribute value. uid may be NULL or the // uid provided to ITLSPolicy::create_session by the caller. is_error // should be true for errors and false for informational messages. The // remaining arguments must be pairs of (const char*); the first of // each pair must be a valid XML attribute name, and the second a // valid XML attribute value. The final parameter must be NULL. typedef void (*ITLSLogFunc)(const char* event, void* uid, int is_error, ...); struct ITLSPlugin { virtual void addref() = 0; virtual void delref() = 0; // create_policy should return a new object that implements // ITLSPolicy. // // The newly created policy, and any session further created from // the policy, should use logf to log any messages or errors that // occur. virtual ITLSPolicy* create_policy( ITLSLogFunc logf ) = 0; static inline const char* get_plugin_type_name_and_version() { return "ITLSPlugin"; } }; #endif /* FDB_ITLSPLUGIN_H */
39.028369
163
0.746684
[ "object" ]
a10a81acb8aa9ada91ba92d176c152f1a0f9f3bb
37,645
h
C
Server/Servers/include/isabRouteElement.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Servers/include/isabRouteElement.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Servers/include/isabRouteElement.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services 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 Vodafone Group Services Ltd 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. */ #ifndef ISABROUTEELEMENT_11_H #define ISABROUTEELEMENT_11_H #include "DataBuffer.h" #ifndef THINCLIENT # include "RouteElement.h" #else # define VectorElement Object // include our "RouteElement" # include "PdaNavigatorProt.h" #endif /** * */ class IsabRouteElement { public: // There is a corresponding enum in PdaNavigatorProt.h enum PointType{ nav_route_point_end = 0x0000, EPT = 0x0000, nav_route_point_start = 0x0001, SPT = 0x0001, nav_route_point_ahead = 0x0002, nav_route_point_left = 0x0003, nav_route_point_right = 0x0004, nav_route_point_uturn = 0x0005, nav_route_point_startat = 0x0006, nav_route_point_finally = 0x0007, nav_route_point_enter_rdbt= 0x0008, nav_route_point_exit_rdbt = 0x0009, nav_route_point_ahead_rdbt= 0x000a, nav_route_point_left_rdbt = 0x000b, nav_route_point_right_rdbt= 0x000c, nav_route_point_exitat = 0x000d, nav_route_point_on = 0x000e, nav_route_point_park_car = 0x000f, nav_route_point_keep_left = 0x0010, nav_route_point_keep_right= 0x0011, nav_route_point_start_with_uturn = 0x0012, nav_rotue_point_uturn_rdbt = 0x0013, nav_route_point_follow_road = 0x0014, nav_route_point_enter_ferry = 0x0015, nav_route_point_exit_ferry = 0x0016, nav_route_point_change_ferry= 0x0017, nav_route_point_delta = 0x03fe, FULL_TPT = 0x03fe, nav_route_point_max = 0x03ff, nav_meta_point_origo = 0x8000, ORIGO = 0x8000, nav_meta_point_scale = 0x8001, SCALE = 0x8001, nav_meta_point_mini_delta_points = 0x8002, nav_meta_point_micro_delta_points = 0x8003, nav_meta_point_meta = 0x8005, nav_meta_point_time_dist_left_points=0x8006, nav_meta_point_landmark = 0x8007, nav_meta_point_lane_info = 0x8008, nav_meta_point_lane_data = 0x8009, nav_meta_point_signpost = 0x800a, nav_meta_point_max = 0x807f }; enum ObjectType_t { IsabRouteType = 0, OrigoType, ScaleType, MiniType, MicroDeltaType, TPTType, WPTType, TimeDistLeftType, MetaPTType, LandmarkPTType, LaneInfoPTType, LaneDataPTType, SignPostPTType, }; /** * Creates a new, empty IsabRouteElement. */ IsabRouteElement(ObjectType_t objType); /** * Cleans up. */ virtual ~IsabRouteElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; // might be difference between thinclient and mc2 alignment in // readnextshort / readnextlong static IsabRouteElement* createFromBuf(DataBuffer* buf); /** * Checks if the type of this object is the specified. * @param cmp The type to check. * @return True if correct type. */ bool typeIs(ObjectType_t cmp) const { bool result = false; if (m_objectType == cmp) { result = true; } else { if (m_objectType == IsabRouteType) { # ifdef THINCLIENT showMessage(TEXT("warning: type not set for IsabRouteElement")); # endif } } return result; } protected: // The type of this object. ObjectType_t m_objectType; private: /// Private default. IsabRouteElement() {}; /** Dummy variable for stupid compiler for navigator. Alignment-problem * This one will be removed !!! */ uint16 m_dummy; }; class OrigoElement : public IsabRouteElement { public: /** * Creates a new Origo Element. * @param origoLon (X) The longitude origo for this projection. * @param origoLat (Y) The latitude origo for this projection. * @param nextOrigo The position of the next origo in this array. */ OrigoElement(int32 origoLon, int32 origoLat, int16 nextOrigo); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. */ OrigoElement(DataBuffer* buf); /** * Destruct. */ virtual ~OrigoElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ int write(uint8* buf, int pos) const; /** * Sets the next origo for this element. * @param pos The next origo position. */ void setNextOrigo(uint16 pos); /** * Get the longitude. * @return The longitude. */ int32 getLon() const { return m_origoLon; } /** * Get the latitude. * @return The latitude. */ int32 getLat() const { return m_origoLat; } private: /** * The origo in longitude (X) direction. This is for the projected "minimap". */ int32 m_origoLon; /** * The origo in latitude (Y) direction. This is for the projected "minimap". */ int32 m_origoLat; /** * The index to the next origo inte the array. */ int16 m_nextOrigo; }; class WPTorTPTElement : public IsabRouteElement { public: /** * A genral trackpoint along the route path. * @param lon Distance in 1/4 meters from current origo. * @param lat Distance in 1/4 meters from current origo. */ WPTorTPTElement( ObjectType_t objType, int16 lon, int16 lat, uint8 flags, uint16 meters, uint8 speedlimit, uint16 nameIndex ); /** * A general trackpoint along the route path. * @param lon Distance in 1/4 meters from current origo. * @param lat Distance in 1/4 meters from current origo. */ WPTorTPTElement(ObjectType_t objType); /** * Destruct. */ virtual ~WPTorTPTElement(); /** * Gets the distance, in meters. * 32 bits for thinclient, 16 bits in server and navigator! * @return The distance, in meters. */ uint32 getDistance() const { return m_meters; } /** * Sets the distance, in meters. * 32 bits for thinclient, 16 bits in server and navigator! * @param meters The distance, in meters. */ void setDistance(uint32 meters) { m_meters=meters; } /** * Returns true if highway bit is set. * @return True if highway bit is set. */ bool isHighway() const { return m_flags & 1; // first bit is highway bit } /** * Returns all the flags. * @return All the flags. */ uint8 getFlags() const { return m_flags; // all of them } /** * Returns the speed limit. * @return The speed limit. */ uint8 getSpeedLimit() const { return m_speedLimit; } /** * Returns the lon (x) value. * @return The lon value. */ int16 getLon() const { return m_lon; } /** * Returns the lat (y) value. * @return The lat value. */ int16 getLat() const { return m_lat; } uint16 getTextIndex() const { return m_nameIndex; } /** * Set the name index. * * @param nameIndex The index to set. */ void setNameIndex( uint16 nameIndex ); /** * Set the latitude. */ void setLat( int16 lat ) { m_lat = lat; } /** * Set the longitude. */ void setLon( int16 lon ) { m_lon = lon; } protected: /** * Distance in 1/4 meters from current origo. */ int16 m_lon; /** * Distance in 1/4 meters from current origo. */ int16 m_lat; /** * The special flags on this segment. These include * autobahn etc. */ uint8 m_flags; /** * The speedLimit on this segment. */ uint8 m_speedLimit; /** * Meters left to next wpt or tpt. * 32 bits for thinclient, 16 bits in server and navigator! */ uint32 m_meters; /** * Index in NavStringTable. */ uint16 m_nameIndex; }; class WPTElement : public WPTorTPTElement { public: /** * Creates a new WPT element. * * @param speedLimit The speedlimit for this segment. * @param lon The position in 1/4 meters from local origo. * @param lat The position in 1/4 meters from local origo. * @param nameIndex Index in NavStingTable. * @param crossingKind The type of crossing. */ WPTElement(uint16 type, uint8 speedLimit, int16 lon, int16 lat, uint8 flags, uint16 meters, uint16 nameIndex, uint8 exitCount, RouteElement::navcrossingkind_t crossingKind); /** * Destruct. */ virtual ~WPTElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. * @param pointDesc The action and other bits. */ WPTElement(DataBuffer* buf, uint16 pointDesc); uint16 getAction() const { return m_type; } RouteElement::navcrossingkind_t getCrossingType() const { return m_crossingKind; } uint8 getExitCount() const { return m_exitCount; } void setNewType(uint16 type) { m_type = type; } void setNewExitCount(uint8 exitCount) { m_exitCount = exitCount; } private: /** * The type of this WPT. ahead, left, right.... */ uint16 m_type; /** * Index in NavStingTable. */ uint8 m_exitCount; /** * The type of crossing. */ RouteElement::navcrossingkind_t m_crossingKind; }; class TPTElement : public WPTorTPTElement { public: /** * A trackpoint along the route path. * @param lon Distance in 1/4 meters from current origo. * @param lat Distance in 1/4 meters from current origo. */ TPTElement(int16 lon, int16 lat, uint8 flags, uint16 meters, uint8 speedlimit); /** * Destruct. */ virtual ~TPTElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. */ TPTElement(DataBuffer* buf); protected: }; class ScaleElement : public IsabRouteElement { public: /** * Creates a ScaelElement * @param integerPart The integer part of cos(lat). * @param restPart The restPart of the cos(lat) calculation. */ ScaleElement(uint32 integerPart, uint32 restPart, uint16 refLat, // y uint16 refLon); // x /** * Destruct. */ virtual ~ScaleElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. */ ScaleElement(DataBuffer* buf); uint32 getIntegerPart() const { return m_integerPart; } uint32 getRestPart() const { return m_restPart; } uint16 getRefLon() const { return m_refLon; // x } uint16 getRefLat() const { return m_refLat; // y } protected: uint32 m_integerPart; uint32 m_restPart; uint16 m_refLon; uint16 m_refLat; }; class MiniElement : public IsabRouteElement { public: /** * Creates a MiniElement */ MiniElement(); /** * Creates a MiniElement * @param lon1 The lon part in first point. * @param lat1 The lat part in first point. * @param lon2 The lon part in second point. * @param lat2 The lat part in second point. */ MiniElement(int16 lon1, int16 lat1, int16 lon2, int16 lat2, uint8 speedLimit1, uint8 speedLimit2); /** * Destruct. */ virtual ~MiniElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. */ MiniElement(DataBuffer* buf); /** * Set the lon1 and lat1 inpoint. * @param lon1 The 1:st point. * @param lat1 The 1:st point. */ void set1(int16 lon, int16 lat); /** * Set the speedLimit from lon1 and lat1. * @param speedLimit The speedLimit from this point. */ void setSpeedLimit1(uint8 speedLimit); /** * Set the lon2 and lat2 in point. * @param lon2 The 2:nd point. * @param lat2 The 2:nd point. */ void set2(int16 lon, int16 lat); int16 getLat1() const {return m_lat1;} int16 getLat2() const {return m_lat2;} int16 getLon1() const {return m_lon1;} int16 getLon2() const {return m_lon2;} uint8 getSpeed1() const {return m_speedLimit1;} uint8 getSpeed2() const {return m_speedLimit2;} /** * Set the speedLimit from lon2 and lat2. * @param speedLimit The speedLimit from this point. */ void setSpeedLimit2(uint8 speedLimit); protected: int16 m_lon1; int16 m_lat1; int16 m_lon2; int16 m_lat2; uint8 m_speedLimit1; uint8 m_speedLimit2; }; class MicroDeltaElement : public IsabRouteElement { public: /** * Creates a MiniDeltaElement */ MicroDeltaElement(); /** * Creates a MicroDeltaElement * @param x1 The x part in first delta point. * @param y1 The y part in first delta point. * @param x2 The y part in second delta point. * @param y2 The y part in second delta point. * @param x3 The y part in 3:d delta point. * @param y3 The y part in 3:d delta point. * @param x4 The y part in 4:th delta point. * @param y4 The y part in 4:th delta point. * @param x5 The y part in 5:th delta point. * @param y5 The y part in 5:th delta point. */ MicroDeltaElement(int8 x1, int8 y1, int8 x2, int8 y2, int8 x3, int8 y3, int8 x4, int8 y4, int8 x5, int8 y5); /** * Destruct. */ virtual ~MicroDeltaElement(); /** * Writes the contents of this element to buf at position pos. * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write(uint8* buf, int pos) const; /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * @param buf The buffer to read from. */ MicroDeltaElement(DataBuffer* buf); /** * Set the x1 and y1 in deltapoint. * @param x1 The 1:st delta. * @param y1 The 1:st delta. */ void setDelta1(int8 x, int8 y); /** * Set the x2 and y2 in deltapoint. * @param x2 The 2:st delta. * @param y2 The 2:st delta. */ void setDelta2(int8 x, int8 y); /** * Set the x2 and y2 in deltapoint. * @param x2 The 2:st delta. * @param y2 The 2:st delta. */ void setDelta3(int8 x, int8 y); /** * Set the x2 and y2 in deltapoint. * @param x2 The 2:st delta. * @param y2 The 2:st delta. */ void setDelta4(int8 x, int8 y); /** * Set the x2 and y2 in deltapoint. * @param x2 The 2:st delta. * @param y2 The 2:st delta. */ void setDelta5(int8 x, int8 y); int8 getLat1() const { return m_y1; } int8 getLon1() const { return m_x1; } int8 getLat2() const { return m_y2; } int8 getLon2() const { return m_x2; } int8 getLat3() const { return m_y3; } int8 getLon3() const { return m_x3; } int8 getLat4() const { return m_y4; } int8 getLon4() const { return m_x4; } int8 getLat5() const { return m_y5; } int8 getLon5() const { return m_x5; } protected: int8 m_x1; int8 m_y1; int8 m_x2; int8 m_y2; int8 m_x3; int8 m_y3; int8 m_x4; int8 m_y4; int8 m_x5; int8 m_y5; }; /** * A meto point telling the total time, estimated, and distance left to goal. * Only present for protover >= 0x05. * */ class TimeDistLeftElement : public IsabRouteElement { public: /** * Creates a TimeDistLeftElement. * * @param timeLeft The time left. * @param distLeft The distance left. */ TimeDistLeftElement( uint32 timeLeft, uint32 distLeft ); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ TimeDistLeftElement( DataBuffer* buf ); /** * Destruct. */ virtual ~TimeDistLeftElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; /** * Get the estimated time left. * * @return The estimated time left. */ uint32 getTimeLeft() const; /** * Set the estimated time left. * * @param time The estimated time left. */ void setTimeLeft( uint32 time); /** * Get the distance left. * * @return The distance left. */ uint32 getDistLeft() const; /** * Returns the speed limit. * NB! Only used for calculations. * * @return The speed limit. */ uint8 getSpeed() const { return m_speedLimit; } /** * Stss the speed limit. * NB! Only used for calculations. * * @param speed The speed limit. */ void setSpeed( uint8 speed ) { m_speedLimit = speed; } protected: /** * The time left to goal. */ uint32 m_timeLeft; /** * The distance left to goal. */ uint32 m_distLeft; /** * The speed limit, NB! Only used for calculations. */ uint8 m_speedLimit; }; /** * A meta point. * Only present for protover >= 0x07. * Meta point 0x8005 1000000000000101 - Meta point, uint16 type + 4 x uint16 *The meta point can be used for any kind of values which need data in 16-bit units. uint16 type; uint16 a; uint16 b; uint16 c; uint16 d; The following types are defined: 0x1 Additional Text Information This datum may be appended once or several times after a wpt+tde combo. Additional text information to be displayed between that point in the route and the next crossing (the one the waypoint describes). The first uint16 is a flag field telling if to pop up a box or just present the text. The second uint16 is an index into the street name buffer, the following two are taken together to form an uint32 that is the distance before the crossing the waypoint refers to. The distance is set to zero for signs at the turning point. 0x2 Additional Sound Information Additional sound to be played at this point More detailed sound information, Half way reached, Commercial etc. 0x3 Additional Trackpoint Information Additional information needed for next trackpoint. Currently the first uint16 holds an extended flags section. Only two extended flag is defined to describe left-hand/right-hand side driving. The two least significant bits are 0=no change, 1=change to left-hand, 2=change to right-hand driving and 3=unused. 0x4 Segmented Route And End Is Near Advise that new phonecall is made to Navigator Server to download next part of a segmented route. If a route is too large to transfer to the Navigator in one piece, the route can be sent in a number of smaller segments with automatic routing at the end of the segment. 0x5 Report Point Reached Instructs the Navigator to initiate contact with server to report when the point is passed. Can be used for vehicle tracking, automatic road pricing etc. * */ class MetaPTElement : public IsabRouteElement { public: /** * Types of meta points. */ enum metapoint_t { /// Additional Text Information additional_text = 0x1, /// Additional Sound Information additional_sound = 0x2, /// Additional Trackpoint Information additional_trackpoint = 0x3, /// Segmented Route And End Is Near Advise segmented_route_end_is_near = 0x4, /// Report Point Reached report_point_reached = 0x5 }; /** * Create a MetaPTElement. * * @param a The a data. * @param b The b data. * @param c The c data. * @param d The d data. */ MetaPTElement( metapoint_t type, uint16 a, uint16 b, uint16 c, uint16 d ); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ MetaPTElement( DataBuffer* buf ); /** * Destruct. */ virtual ~MetaPTElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; /** * Get the type of meta point. */ metapoint_t getType() const; /** * Get the a data. */ uint16 getDataA() const; /** * Get the b data. */ uint16 getDataB() const; /** * Get the c data. */ uint16 getDataC() const; /** * Get the D data. */ uint16 getDataD() const; /** * Set the a data. * * @param value The new value. */ void setDataA( uint16 value ); /** * Set the b data. * * @param value The new value. */ void setDataB( uint16 value ); /** * Set the C data. * * @param value The new value. */ void setDataC( uint16 value ); /** * Set the d data. * * @param value The new value. */ void setDataD( uint16 value ); protected: /** * The type of meta point. */ metapoint_t m_type; /** * The a data. */ uint16 m_dataa; /** * The b data. */ uint16 m_datab; /** * The c data. */ uint16 m_datac; /** * The d data. */ uint16 m_datad; }; class LandmarkPTElement : public IsabRouteElement { public: /** * Create a LandmarkPTElement. * * @param detour. * @param lm_side. * @param lm_type. * @param distance. * @param lm_location. * @param isStart. * @param isStop. * @param landmarkID. */ LandmarkPTElement(bool detour, uint8 lm_side, uint8 lm_type, uint8 lm_location, int32 distance, uint16 strNbr, bool isStart, bool isStop, int16 landmarkID, uint32 distID = MAX_UINT32); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ LandmarkPTElement( DataBuffer* buf ); /** * Destruct. */ virtual ~LandmarkPTElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; uint32 getLandmarkRouteID() const; uint32 getLandmarkServerID() const; /** * Set the isStart. */ void setisStart( bool on ); /** * Set the isEnd. */ void setisEnd( bool on ); /** * Get the isStart. */ bool getisStart() const; /** * Get the isEnd. */ bool getisEnd() const; /** * Set the isSetour. */ void setisDetour( bool on ); /** * Get the isDetour. */ bool getisDetour() const; /** * Set the distance. */ void setDistance( int32 distance ); /** * Get the distance. */ int32 getDistance() const; /** * Get the strNameIdx. */ uint16 getStrNameIdx() const; protected: /** * The a data. */ uint16 m_flags; /** * The b data. */ int32 m_distance; /** * The c data. */ uint16 m_strNameIdx; /** * The d data. */ uint16 m_idStartStop; /** * The id of the distrubance. */ uint32 m_distID; }; /** * A start of lane data, with some lanes. * */ class LaneInfoPTElement : public IsabRouteElement { public: /** * Create a LaneInfoPTElement. * * @param stopOfLanesFlag If this is a end of lanes. * @param reminderOfLanesFlag If this is a reminder of lanes. * @param nbrLanes The total number of lanes in this and following * lane datas. * @param lane0 A lane. * @param lane1 A lane. * @param lane2 A lane. * @param lane3 A lane. * @param distance Distance from the lanes to the next crossing. */ LaneInfoPTElement( bool stopOfLanesFlag, bool reminderOfLanesFlag, uint8 nbrLanes, uint8 lane0, uint8 lane1, uint8 lane2, uint8 lane3, int32 distance ); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ LaneInfoPTElement( DataBuffer* buf ); /** * Destructor. */ virtual ~LaneInfoPTElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; /** * Get the stopOfLanesFlag. */ bool getStopOfLanesFlag() const; /** * Get the reminderOfLanesFlag. */ bool getReminderOfLanesFlag() const; /** * Get the nbrLanes. */ uint8 getNbrLanes() const; /** * Get the lane 0. */ uint8 getLane0() const; /** * Get the lane 1. */ uint8 getLane1() const; /** * Get the lane 2. */ uint8 getLane2() const; /** * Get the lane 3. */ uint8 getLane3() const; /** * Get the distance. */ int32 getDistance() const; protected: /** * Bit-mapped flags */ uint8 m_flags; /** * The number of lanes. */ uint8 m_nbrLanes; /// A lane. uint8 m_lane0; /// A lane. uint8 m_lane1; /// A lane. uint8 m_lane2; /// A lane. uint8 m_lane3; /** * Distance from the lanes to the next crossing. */ int32 m_distance; }; /** * Lane data, 10 lanes. Follows a Lane info element. * */ class LaneDataPTElement : public IsabRouteElement { public: /** * Create a LaneDataPTElement. * * @param lane0 A lane. * @param lane1 A lane. * @param lane2 A lane. * @param lane3 A lane. * @param lane4 A lane. * @param lane5 A lane. * @param lane6 A lane. * @param lane7 A lane. * @param lane8 A lane. * @param lane9 A lane. */ LaneDataPTElement( uint8 lane0, uint8 lane1, uint8 lane2, uint8 lane3, uint8 lane4, uint8 lane5, uint8 lane6, uint8 lane7, uint8 lane8, uint8 lane9 ); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ LaneDataPTElement( DataBuffer* buf ); /** * Destructor. */ virtual ~LaneDataPTElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; /** * Get the lane 0. */ uint8 getLane0() const; /** * Get the lane 1. */ uint8 getLane1() const; /** * Get the lane 2. */ uint8 getLane2() const; /** * Get the lane 3. */ uint8 getLane3() const; /** * Get the lane 4. */ uint8 getLane4() const; /** * Get the lane 5. */ uint8 getLane5() const; /** * Get the lane 6. */ uint8 getLane6() const; /** * Get the lane 7. */ uint8 getLane7() const; /** * Get the lane 8. */ uint8 getLane8() const; /** * Get the lane 9. */ uint8 getLane9() const; protected: /// A lane. uint8 m_lane0; /// A lane. uint8 m_lane1; /// A lane. uint8 m_lane2; /// A lane. uint8 m_lane3; /// A lane. uint8 m_lane4; /// A lane. uint8 m_lane5; /// A lane. uint8 m_lane6; /// A lane. uint8 m_lane7; /// A lane. uint8 m_lane8; /// A lane. uint8 m_lane9; }; /** * A signpost. * */ class SignPostPTElement : public IsabRouteElement { public: /** * Create a SignPostPTElement. * * @param signPostTextIndex The index in the string table of the text. * @param textColor The color of the text. * @param backgroundColor The color of the background. * @param frontColor The color of the front. * @param distance Distance from the sign post to the next crossing. */ SignPostPTElement( uint16 signPostTextIndex, byte textColor, byte backgroundColor, byte frontColor, int32 distance ); /** * Constructor. * Creates from databuffer. * Reverse of write, except for action field. * * @param buf The buffer to read from. */ SignPostPTElement( DataBuffer* buf ); /** * Destructor. */ virtual ~SignPostPTElement(); /** * Writes the contents of this element to buf at position pos. * * @param buf The buf to write to. * @param pos The position in the buffer. */ virtual int write( uint8* buf, int pos ) const; /** * Get the SignPostTextIndex. */ uint16 getSignPostTextIndex() const; /** * Get the textColor. */ byte getTextColor() const; /** * Get the backgroundColor. */ byte getBackgroundColor() const; /** * Get the frontColor. */ byte getFrontColor() const; /** * Get the distance. */ int32 getDistance() const; protected: /** * Index into the string table. */ uint16 m_signPostTextIndex; /** * The color of the text in the signpost. */ byte m_textColor; /** * The color of the background of the signpost. */ byte m_backgroundColor; /** * The color of the front of the signpost. */ byte m_frontColor; /** * Not used right now. */ byte m_reserved; /** * Distance from the signpost to the next crossing. */ int32 m_distance; }; // ======================================================================= // Implementation of inlined methods = inline bool LaneInfoPTElement::getStopOfLanesFlag() const { return (m_flags & 0x1) != 0; } inline bool LaneInfoPTElement::getReminderOfLanesFlag() const { return (m_flags & 0x2) != 0; } inline uint8 LaneInfoPTElement::getNbrLanes() const { return m_nbrLanes; } inline uint8 LaneInfoPTElement::getLane0() const { return m_lane0; } inline uint8 LaneInfoPTElement::getLane1() const { return m_lane1; } inline uint8 LaneInfoPTElement::getLane2() const { return m_lane2; } inline uint8 LaneInfoPTElement::getLane3() const { return m_lane3; } inline int32 LaneInfoPTElement::getDistance() const { return m_distance; } inline uint8 LaneDataPTElement::getLane0() const { return m_lane0; } inline uint8 LaneDataPTElement::getLane1() const { return m_lane1; } inline uint8 LaneDataPTElement::getLane2() const { return m_lane2; } inline uint8 LaneDataPTElement::getLane3() const { return m_lane3; } inline uint8 LaneDataPTElement::getLane4() const { return m_lane4; } inline uint8 LaneDataPTElement::getLane5() const { return m_lane5; } inline uint8 LaneDataPTElement::getLane6() const { return m_lane6; } inline uint8 LaneDataPTElement::getLane7() const { return m_lane7; } inline uint8 LaneDataPTElement::getLane8() const { return m_lane8; } inline uint8 LaneDataPTElement::getLane9() const { return m_lane9; } inline uint16 SignPostPTElement::getSignPostTextIndex() const { return m_signPostTextIndex; } inline byte SignPostPTElement::getTextColor() const { return m_textColor; } inline byte SignPostPTElement::getBackgroundColor() const { return m_backgroundColor; } inline byte SignPostPTElement::getFrontColor() const { return m_frontColor; } inline int32 SignPostPTElement::getDistance() const { return m_distance; } #endif
22.623197
755
0.564882
[ "object" ]
a10cf4b45ae1a8af7321de10fdc32469cff3704e
667
h
C
CondFormats/DataRecord/interface/HcalChannelQualityRcd.h
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
2
2020-01-21T11:23:39.000Z
2020-01-21T11:23:42.000Z
CondFormats/DataRecord/interface/HcalChannelQualityRcd.h
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
CondFormats/DataRecord/interface/HcalChannelQualityRcd.h
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
3
2017-06-07T15:22:28.000Z
2019-02-28T20:48:30.000Z
// this file is generated automatically by /afs/fnal.gov/files/home/room1/ratnikov/bin/makeNewClass.sh // name: ratnikov, date: Thu Oct 20 01:13:51 CDT 2005 #ifndef HcalChannelQualityRcd_H #define HcalChannelQualityRcd_H #include "FWCore/Framework/interface/DependentRecordImplementation.h" #include "Geometry/Records/interface/HcalRecNumberingRecord.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" class HcalChannelQualityRcd : public edm::eventsetup::DependentRecordImplementation< HcalChannelQualityRcd, boost::mpl::vector<HcalRecNumberingRecord, IdealGeometryRecord> > {}; #endif
55.583333
103
0.748126
[ "geometry", "vector" ]
a1150ae299d31dfecbea82fbe090f687e74c67c7
9,321
h
C
tensorflow/compiler/xla/service/hlo_value.h
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tensorflow/compiler/xla/service/hlo_value.h
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tensorflow/compiler/xla/service/hlo_value.h
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_HLO_VALUE_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_VALUE_H_ #include <stddef.h> #include <string> #include <vector> #include "absl/types/span.h" #include "tensorflow/compiler/xla/service/buffer_value.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/shape_tree.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" namespace xla { // Abstraction which identifies a specific point in the XLA graph. An // HloPosition specifies a ShapeIndex within the output of a specific // instruction. struct HloPosition { HloInstruction* instruction; ShapeIndex index; // Returns the shape at this position. const Shape& shape() const; string ToString() const; bool operator==(const HloPosition& other) const { return instruction == other.instruction && index == other.index; } bool operator!=(const HloPosition& other) const { return !(*this == other); } // Stable less-than operator using instruction id and index. bool operator<(const HloPosition& other) const { return instruction->unique_id() < other.instruction->unique_id() || (instruction->unique_id() == other.instruction->unique_id() && index < other.index); } }; std::ostream& operator<<(std::ostream& out, const HloPosition& position); // Defines a single use of an HLO value. struct HloUse { // Instruction at which the value is used. HloInstruction* instruction; // The operand number in which the value is appears. int64 operand_number; // The shape index within the operand in which the value appears. ShapeIndex operand_index; string ToString() const; bool operator==(const HloUse& other) const { return instruction == other.instruction && operand_number == other.operand_number && operand_index == other.operand_index; } bool operator!=(const HloUse& other) const { return !(*this == other); } }; std::ostream& operator<<(std::ostream& out, const HloUse& use); // HloDataflowAnalysis uses this subclass of BufferValue. class HloValue : public BufferValue { public: // Predicate comparing HloValues by increasing id, useful for std::sort. static bool IdLessThan(const HloValue* a, const HloValue* b) { return a->id() < b->id(); } // Predicate comparing HloValues by equal id, useful for std::unique. static bool IdEqual(const HloValue* a, const HloValue* b) { return a->id() == b->id(); } // Construct an HloValue defined by 'instruction' at shape index 'index'. If // is_phi is true, then this value is a phi value, for example, at the // parameter of a while body computation. Phi values are only used in the SSA // dataflow analysis (HloDataflowAnalysis::ssa_form_ is true). HloValue(Id id, HloInstruction* instruction, const ShapeIndex& index, bool is_phi = false); ~HloValue() override {} // Sets the positions in the module at which the HloValue appears. Updates // uses. Should be called once and only once. The defining position should not // be included in 'positions' as this is set at construction time. void SetPositionsAndComputeUses(absl::Span<const HloPosition> positions); // Returns whether this value is a phi value. bool is_phi() const { return is_phi_; } // Return the position where this value is defined. const HloPosition& defining_position() const { return positions_[0]; } // Return the instruction which defines this HloValue. HloInstruction* defining_instruction() const { return defining_position().instruction; } HloInstruction* instruction() const override { return defining_instruction(); } // Return the shape index at which this HloValue is defined in the output of // its defining instruction. const ShapeIndex& defining_index() const { return defining_position().index; } const ShapeIndex& index() const override { return defining_index(); } // Return the shape of this HloValue. const Shape& shape() const override { return defining_position().shape(); } // Return all positions of the HloValue in the module. const std::vector<HloPosition>& positions() const { return positions_; } // Return all uses of the HloValue. const std::vector<HloUse>& uses() const { return uses_; } // Get whether this HloValue is live out of the module. bool live_out_of_module() const { return live_out_of_module_; } bool operator==(const HloValue& other) const; bool operator!=(const HloValue& other) const; // Return a single-line string representation of the value. string ToShortString() const; string ToString(int indent) const; string ToString() const override { return ToString(0); } private: // Whether this instruction is a phi value. const bool is_phi_; // The set of positions of this HloValue. The first element is always the // position of the definition. std::vector<HloPosition> positions_; // The set of uses of this HloValue. std::vector<HloUse> uses_; // Whether this value is live out of the HLO module. bool live_out_of_module_ = false; }; std::ostream& operator<<(std::ostream& out, const HloValue& hlo_value); // A class representing the possible set of HloValues at a particular point // (shape index in the output of an instruction) in the XLA graph. This set // contains the set of reaching HloValue definitions. For a simple array-shaped // instruction like Add, the HloValueSet of the top-level of the instruction's // output trivially contains only the HloValue defined by the instruction. For // instructions which have non-trivial dataflow such as Tuple or Select, the // HloValueSets of the instruction's output contains one or more HloValues // defined by the instruction's operands or defined further up in the XLA graph. class HloValueSet { public: HloValueSet() = default; explicit HloValueSet(absl::Span<const HloValue* const> values) : values_(values.begin(), values.end()) { SortAndUniquifyValues(); } // Sets this value set to the union of the given value sets. Returns whether // this value set changed. bool AssignUnionOf(absl::Span<const HloValueSet* const> inputs); // Return the vector of HloValues in the set. Values in the vector are unique // and stably sorted by value id. const std::vector<const HloValue*>& values() const { return values_; } // Adds the value to the set. Returns true iff the value was added and didn't // already exist in the set. bool AddValue(const HloValue* value); // Clear all values from the set. void Clear() { values_.clear(); } // Return the unique HLO value in the set. CHECKs if the set does not contain // exactly one value. const HloValue& GetUniqueValue() const { CHECK_EQ(values_.size(), 1); return *values_[0]; } bool operator==(const HloValueSet& other) const { if (values_.size() != other.values_.size()) return false; for (size_t i = 0; i < values_.size(); ++i) { if (values_[i]->id() != other.values_[i]->id()) { return false; } } return true; } bool operator!=(const HloValueSet& other) const { return !(*this == other); } string ToString() const; private: // Sorts value_ and removes duplicates. This should be called after adding any // elements to values_. void SortAndUniquifyValues(); // HloValues sorted by HloValue::Id. std::vector<const HloValue*> values_; }; std::ostream& operator<<(std::ostream& out, const HloValueSet& hlo_value); // A class collecting the HloValues which might be contained in the output of // an HLO instruction. For array-shaped instructions, an InstructionValueSet // trivially holds a single HloValueSet. Tuple-shaped InstructionValueSets // hold multiple HloValueSets. class InstructionValueSet : public ShapeTree<HloValueSet> { public: InstructionValueSet(const Shape& shape) : ShapeTree<HloValueSet>(shape) {} // Sets this value set to the union of the given value sets. Returns whether // this value set changed. bool AssignUnionOf(absl::Span<const InstructionValueSet* const> inputs); // Returns true if any value sets for any subshape element is not a // singleton. bool IsAmbiguous() const; string ToString() const; }; std::ostream& operator<<(std::ostream& out, const InstructionValueSet& instruction_value_set); } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_HLO_VALUE_H_
35.576336
80
0.720631
[ "shape", "vector" ]
a115ba43d682d758251165446ed5f643c376d1e2
8,801
h
C
PlugIns/OgrePlugin/include/components/OgreRenderComponent.h
gsage/engine
d1492700d60fb9142c83a861ae091bdd3fc3ae08
[ "MIT" ]
14
2016-12-22T15:31:36.000Z
2022-02-28T11:48:27.000Z
PlugIns/OgrePlugin/include/components/OgreRenderComponent.h
gsage/engine
d1492700d60fb9142c83a861ae091bdd3fc3ae08
[ "MIT" ]
3
2016-09-10T09:54:17.000Z
2018-03-27T11:42:28.000Z
PlugIns/OgrePlugin/include/components/OgreRenderComponent.h
gsage/engine
d1492700d60fb9142c83a861ae091bdd3fc3ae08
[ "MIT" ]
4
2016-08-04T23:28:22.000Z
2021-06-01T06:33:01.000Z
/* ----------------------------------------------------------------------------- This file is a part of Gsage engine Copyright (c) 2014-2016 Artem Chernyshev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _OgreRenderComponent_H_ #define _OgreRenderComponent_H_ #include <OgreNode.h> #include "AnimationScheduler.h" #include "EventDispatcher.h" #include "Definitions.h" #include "GeometryPrimitives.h" #include "components/RenderComponent.h" namespace Ogre { class Vector3; class SceneManager; } namespace Gsage { class SceneNodeWrapper; class OgreRenderSystem; class ResourceManager; class OgreObjectManager; /** * Ogre render system component */ class GSAGE_OGRE_PLUGIN_API OgreRenderComponent : public EventDispatcher, public RenderComponent { public: enum RotationAxis { X_AXIS, Y_AXIS, Z_AXIS, NONE }; static const std::string SYSTEM; static const Event::Type POSITION_CHANGE; OgreRenderComponent(); virtual ~OgreRenderComponent(); /** * Set scene manager instance * * @param sceneManager Ogre::SceneManager instance to allow creating objects on scene * @param resourceManager ResourceManager* instance to allow component loading additional resource * @param objectManager OgreObjectManager instance to allow creating root tree */ inline void prepare(Ogre::SceneManager* sceneManager, ResourceManager* resourceManager, OgreObjectManager* objectManager) { mSceneManager = sceneManager; mResourceManager = resourceManager; mObjectManager = objectManager; } /** * Set render component position * @param position New position */ void setPosition(const Ogre::Vector3& position); /** * Set render component orientation (equal to Ogre::SceneNode::setOrientation) * @param orientation Orientation quaternion (absolute) */ void setOrientation(const Ogre::Quaternion& orientation); /** * Rotates render component * @param rotation Rotation quaternion (relative) */ void rotate(const Ogre::Quaternion& rotation); /** * Equalient to Ogre::Node lookAt * @param position Position to look at * @param rotationAxis rotate only in one axis * @param transformSpace ogre transform space */ void lookAt(const Ogre::Vector3& position, const Geometry::RotationAxis rotationAxis, Geometry::TransformSpace transformSpace = Geometry::TS_WORLD); /** * Equalient to Ogre::Node lookAt * @param position Position to look at */ void lookAt(const Ogre::Vector3& position); /** * Get current position */ const Ogre::Vector3 getOgrePosition(); /** * Get current scale */ const Ogre::Vector3 getOgreScale(); /** * Get current direction vector, uses orientationVector from config to detect front of the object */ const Ogre::Vector3 getOgreDirection(); /** * Get object orientation */ const Ogre::Quaternion getOgreOrientation(); /** * Get object orientation with respect to the direction vector */ const Ogre::Quaternion getOgreFaceOrientation(); // RenderComponent implementation /** * Rotates render component using Gsage::Quaternion * @param rotation Rotation quaternion (relative) */ void rotate(const Gsage::Quaternion& rotation); /** * Equalient to Ogre::Node lookAt * @param position Position to look at * @param rotationAxis rotate only in one axis * @param transformSpace ogre transform space */ void lookAt(const Gsage::Vector3& position, const Geometry::RotationAxis rotationAxis, Geometry::TransformSpace transformSpace = Geometry::TS_WORLD); /** * @param position Position to look at */ void lookAt(const Gsage::Vector3& position); /** * Set position by using Gsage::Vector * @param position New position */ void setPosition(const Gsage::Vector3& position); /** * Set orientation using Gsage::Quaternion * @param orientation Orientation quaternion (absolute) */ void setOrientation(const Gsage::Quaternion& orientation); /** * Get current position */ const Gsage::Vector3 getPosition(); /** * Get current scale */ const Gsage::Vector3 getScale(); /** * Get current direction vector, uses orientationVector from config to detect front of the object */ const Gsage::Vector3 getDirection(); /** * Get object orientation */ const Gsage::Quaternion getOrientation(); /** * Get object orientation with respect to the direction vector */ const Gsage::Quaternion getFaceOrientation(); /** * Adjusts animation speed for state * @param name Animation state name * @param speed animation speed */ bool adjustAnimationStateSpeed(const std::string& name, double speed); /** * Sets animation state * @param name Animation name * @returns true if state was found */ bool setAnimationState(const std::string& name); /** * Plays animation * * @param name Animation group name * @param times Repeat times, -1 means loop * @param speed Animation speed, 1 -- is normal speed * @param offset Animation start offset * @param reset Starts animation immediately * * @returns true if animation group exists */ bool playAnimation(const std::string& name, int times = -1, double speed = 1, double offset = 0, bool reset = false); /** * Resets animation state to default */ void resetAnimationState(); /** * Reads component root node */ DataProxy getRootNode(); /** * Builds node tree from DataProxy. * \verbatim embed:rst:leading-asterisk * Example: * * .. code-block:: js * * { * "position": "0,0,0", * "scale": "0,0,0", * "children": [ * { * "type": "model", * "mesh": "mesh.mesh" * } * ] * } * * \endverbatim */ void setRootNode(const DataProxy& value); /** * Reads component animations */ DataProxy getAnimations(); /** * Sets animations * \verbatim embed:rst:leading-asterisk * DataProxy should have the following format: * * .. code-block:: js * * { * "states": { * "state1": {"base": {"<model-name>": "<anim-name>"}} * } * } * * \endverbatim */ void setAnimations(const DataProxy& value); /** * Get root SceneNodeWrapper */ SceneNodeWrapper* getRoot(); /** * Read additional resources paths from the DataProxy * @param resources DataProxy with all resources settings */ void setResources(const DataProxy& resources); /** * Get resources */ const DataProxy& getResources() const; private: friend class OgreRenderSystem; bool mAddedToScene; AnimationScheduler mAnimationScheduler; SceneNodeWrapper* mRootNode; DataProxy mResources; Ogre::SceneManager* mSceneManager; ResourceManager* mResourceManager; OgreObjectManager* mObjectManager; }; } #endif
30.989437
155
0.618339
[ "mesh", "geometry", "render", "object", "vector", "model", "transform" ]
a119401ac1d8aaa2fc32abe68cff56f30336cfa6
4,953
h
C
lib/sergut/JsonSerializer.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
5
2018-01-20T10:28:39.000Z
2020-04-28T22:13:24.000Z
lib/sergut/JsonSerializer.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
null
null
null
lib/sergut/JsonSerializer.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
null
null
null
/* Copyright (c) 2016 Tobias Koelsch * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include "sergut/SerializerBase.h" #include "sergut/Util.h" #include "sergut/detail/DummySerializer.h" #include <list> #include <set> #include <sstream> #include <vector> namespace sergut { class JsonSerializer: public SerializerBase { struct Impl; struct LevelStatus; public: enum class Flags { None = 0, BoolAsInt = 1 // set by default for backward-compatibility }; JsonSerializer(const Flags flags = Flags::BoolAsInt); JsonSerializer(const JsonSerializer& ref); ~JsonSerializer(); template<typename DT> JsonSerializer& operator&(const NamedMemberForSerialization<DT>& data) { addCommaIfNeeded(); if(data.name) { out() << "\"" << data.name << "\":"; } serializeValue(data.data); return *this; } void serializeValue(const long long data) { out() << data; } void serializeValue(const long data) { out() << data; } void serializeValue(const int data) { out() << data; } void serializeValue(const short data) { out() << data; } void serializeValue(const signed char data) { out() << static_cast<short>(data); } void serializeValue(const unsigned long long data) { out() << data; } void serializeValue(const unsigned long data) { out() << data; } void serializeValue(const unsigned int data) { out() << data; } void serializeValue(const unsigned short data) { out() << data; } void serializeValue(const unsigned char data) { out() << static_cast<unsigned short>(data); } void serializeValue(const double data) { out() << data; } void serializeValue(const float data) { out() << data; } void serializeValue(const bool data); void serializeValue(const std::string& data) { out() << "\""; writeEscaped(data); out() << "\""; } void serializeValue(const char data[]) { serializeValue(std::string(data)); } void serializeValue(const char*& data) { serializeValue(std::string(data)); } void serializeValue(const char data) { serializeValue(std::string(1, data)); } // Containers as members template<typename DT> void serializeCollection(const DT& data) { out() << "["; bool first=true; for(auto&& value: data) { if(!first) { out() << ","; } else { first=false; } JsonSerializer ser(*this); ser.serializeValue(value); } out() << "]"; } template<typename ValueType> void serializeValue(const std::vector<ValueType>& data) { return serializeCollection(data); } template<typename ValueType> void serializeValue(const std::list<ValueType>& data) { return serializeCollection(data); } template<typename ValueType> void serializeValue(const std::set<ValueType>& data) { return serializeCollection(data); } template<typename DT> auto serializeValue(const DT& data) -> decltype(serialize(detail::DummySerializer::dummyInstance(), data, static_cast<typename std::decay<DT>::type*>(nullptr)), void()) { out() << "{"; JsonSerializer ser(*this); serialize(ser, data, static_cast<typename std::decay<DT>::type*>(nullptr)); out() << "}"; } // Members that can be converted to string template<typename DT> auto serializeValue(const DT& data) -> decltype(serializeToString(data), void()) { serializeValue(serializeToString(data)); } // This is unused for JSON JsonSerializer& operator&(const ChildrenFollow&) { return *this; } // This is unused for JSON JsonSerializer& operator&(const PlainChildFollows&) { return *this; } /// \param name this is not needed for JSON, we just add it here for symmetry to XML. template<typename DT> void serializeData(const DT& data) { serializeValue(data); } std::string str() const; private: void writeEscaped(const std::string& str); void addCommaIfNeeded(); std::ostream& out(); private: Impl* impl; }; } // namespace sergut
32.585526
134
0.692913
[ "vector" ]
a11aea1655e0d00e97825078c3f88ed7634e390e
2,914
h
C
include/partial_sum.h
muellan/statistics
7838fe68250411b0853399985361239563f8af11
[ "MIT" ]
4
2017-11-10T19:30:09.000Z
2022-02-25T05:19:41.000Z
include/partial_sum.h
muellan/statistics
7838fe68250411b0853399985361239563f8af11
[ "MIT" ]
null
null
null
include/partial_sum.h
muellan/statistics
7838fe68250411b0853399985361239563f8af11
[ "MIT" ]
null
null
null
#ifndef AMLIB_STATISTICS_PARTIAL_SUMS_H_ #define AMLIB_STATISTICS_PARTIAL_SUMS_H_ #include <vector> #include <cstdint> #include <limits> #include <type_traits> namespace am { namespace stat { /*************************************************************************//**** * * @brief efficiently query partial sums on a mutable vector of integers * * @details implemented as Fenwick tree * *****************************************************************************/ template<class IntegralT = std::int_least64_t> class partial_sum_counter { static_assert(std::is_integral<IntegralT>::value && std::is_signed<IntegralT>::value, "partial_sum_accumulator<T>: T must be a signed builtin integral type"); public: //--------------------------------------------------------------- using argument_type = IntegralT; using size_type = argument_type; //--------------------------------------------------------------- constexpr partial_sum_counter(): store_{} {} //----------------------------------------------------- explicit constexpr partial_sum_counter(size_type size): store_(size, 0) {} //--------------------------------------------------------------- void reserve(size_type size) { if(size > 0) store_.reserve(size); } void resize(size_type size) { if(size > 0) store_.resize(size, argument_type(0)); } //--------------------------------------------------------------- /// @brief increases the value of k-th element by inc. void increase(size_type idx, argument_type inc = 1) { for(; idx < static_cast<size_type>(store_.size()); idx |= idx + 1) { store_[idx] += inc; } } //--------------------------------------------------------------- size_type size() const noexcept { return store_.size(); } //----------------------------------------------------- /// @brief returns the frequency of one element argument_type operator [] (size_type idx) const noexcept { return total(idx,idx); } //----------------------------------------------------- /// @brief returns the total of elements in index range [0,idx] argument_type total(size_type idx) const noexcept { auto s = argument_type(0); for(; idx >= 0; idx = (idx & (idx + 1)) - 1) { s += store_[idx]; } return s; } //----------------------------------------------------- /// @brief returns the total of elements in index range [a,b] argument_type total(size_type a, size_type b) const { return ((a == 0) ? total(b) : (total(0, b) - total(0, a-1)) ); } private: //store_[i] = total of elements in index range [i&(i+1), i] std::vector<IntegralT> store_; }; } // namespace stat } // namespace am #endif
26.252252
80
0.455731
[ "vector" ]
a11cf4a820488b35c953cf9a6dde03de1b19c82a
9,721
h
C
hardware/chip/smarth_rv64/include/drv_iic.h
ekmixon/AliOS-Things
00334295af8aa474d818724149726ca93da4645d
[ "Apache-2.0" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
hardware/chip/smarth_rv64/include/drv_iic.h
ekmixon/AliOS-Things
00334295af8aa474d818724149726ca93da4645d
[ "Apache-2.0" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
hardware/chip/smarth_rv64/include/drv_iic.h
willianchanlovegithub/AliOS-Things
637c0802cab667b872d3b97a121e18c66f256eab
[ "Apache-2.0" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file drv_iic.h * @brief header file for iic driver * @version V1.0 * @date 02. June 2017 * @model iic ******************************************************************************/ #ifndef _CSI_IIC_H_ #define _CSI_IIC_H_ #include <stdint.h> #include <stdbool.h> #include <drv_common.h> #ifdef __cplusplus extern "C" { #endif /// definition for iic handle. typedef void *iic_handle_t; /*----- IIC Control Codes: Mode -----*/ typedef enum { IIC_MODE_MASTER, ///< IIC Master IIC_MODE_SLAVE ///< IIC Slave } iic_mode_e; /*----- IIC Control Codes: IIC Bus Speed -----*/ typedef enum { IIC_BUS_SPEED_STANDARD = 0, ///< Standard Speed (100kHz) IIC_BUS_SPEED_FAST = 1, ///< Fast Speed (400kHz) IIC_BUS_SPEED_FAST_PLUS = 2, ///< Fast+ Speed ( 1MHz) IIC_BUS_SPEED_HIGH = 3 ///< High Speed (3.4MHz) } iic_speed_e; /*----- IIC Control Codes: IIC Address Mode -----*/ typedef enum { IIC_ADDRESS_7BIT = 0, ///< 7-bit address mode IIC_ADDRESS_10BIT = 1 ///< 10-bit address mode } iic_address_mode_e; /** \brief IIC Status */ typedef struct { uint32_t busy : 1; ///< Transmitter/Receiver busy flag uint32_t mode : 1; ///< Mode: 0=Slave, 1=Master uint32_t direction : 1; ///< Direction: 0=Transmitter, 1=Receiver uint32_t general_call : 1; ///< General Call(address 0) indication (cleared on start of next Slave operation) uint32_t arbitration_lost : 1; ///< Master lost arbitration(in case of multi-masters) (cleared on start of next Master operation) uint32_t bus_error : 1; ///< Bus error detected (cleared on start of next Master/Slave operation) } iic_status_t; /****** IIC Event *****/ typedef enum { IIC_EVENT_TRANSFER_DONE = 0, ///< Master/Slave Transmit/Receive finished IIC_EVENT_TRANSFER_INCOMPLETE = 1, ///< Master/Slave Transmit/Receive incomplete transfer IIC_EVENT_SLAVE_TRANSMIT = 2, ///< Slave Transmit operation requested IIC_EVENT_SLAVE_RECEIVE = 3, ///< Slave Receive operation requested IIC_EVENT_ADDRESS_NACK = 4, ///< Address not acknowledged from Slave IIC_EVENT_GENERAL_CALL = 5, ///< General Call indication IIC_EVENT_ARBITRATION_LOST = 6, ///< Master lost arbitration IIC_EVENT_BUS_ERROR = 7, ///< Bus error detected (START/STOP at illegal position) IIC_EVENT_BUS_CLEAR = 8 ///< Bus clear finished } iic_event_e; typedef void (*iic_event_cb_t)(int32_t idx, iic_event_e event); ///< Pointer to \ref iic_event_cb_t : IIC Event call back. /** \brief IIC Driver Capabilities. */ typedef struct { uint32_t address_10_bit : 1; ///< supports 10-bit addressing } iic_capabilities_t; /** \brief Initialize IIC Interface specified by pins. \n 1. Initializes the resources needed for the IIC interface 2.registers event callback function \param[in] idx iic index \param[in] cb_event event callback function \ref iic_event_cb_t \return 0 for success, negative for error code */ iic_handle_t csi_iic_initialize(int32_t idx, iic_event_cb_t cb_event); /** \brief De-initialize IIC Interface. stops operation and releases the software resources used by the interface \param[in] handle iic handle to operate. \return 0 for success, negative for error code */ int32_t csi_iic_uninitialize(iic_handle_t handle); /** \brief Get driver capabilities. \param[in] idx iic index \return \ref iic_capabilities_t */ iic_capabilities_t csi_iic_get_capabilities(int32_t idx); /** \brief config iic attributes. \param[in] handle iic handle to operate. \param[in] mode iic mode \ref iic_mode_e. if negative, then this attribute not changed. \param[in] speed iic speed \ref iic_speed_e. if negative, then this attribute not changed. \param[in] addr_mode iic address mode \ref iic_address_mode_e. if negative, then this attribute not changed. \param[in] slave_addr iic address of slave. if negative, then this attribute not changed. \return 0 for success, negative for error code */ int32_t csi_iic_config(iic_handle_t handle, iic_mode_e mode, iic_speed_e speed, iic_address_mode_e addr_mode, int32_t slave_addr); /** \brief Start transmitting data as IIC Master. This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens. \ref csi_iic_get_status can get operating status. \param[in] handle iic handle to operate. \param[in] devaddr iic addrress of slave device. |_BIT[7:1]devaddr_|_BIT[0]R/W_| eg: BIT[7:0] = 0xA0, devaddr = 0x50. \param[in] data data to send to IIC Slave \param[in] num Number of data items to send \param[in] xfer_pending Transfer operation is pending - Stop condition will not be generated Master generates STOP condition (if xfer_pending is "false") \return 0 for success, negative for error code */ int32_t csi_iic_master_send(iic_handle_t handle, uint32_t devaddr, const void *data, uint32_t num, bool xfer_pending); /** \brief Start receiving data as IIC Master. This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens. \ref csi_iic_get_status can get operating status. \param[in] handle iic handle to operate. \param[in] devaddr iic addrress of slave device. \param[out] data Pointer to buffer for data to receive from IIC receiver \param[in] num Number of data items to receive \param[in] xfer_pending Transfer operation is pending - Stop condition will not be generated \return 0 for success, negative for error code */ int32_t csi_iic_master_receive(iic_handle_t handle, uint32_t devaddr, void *data, uint32_t num, bool xfer_pending); /** \brief Start transmitting data as IIC Slave. This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens. \ref csi_iic_get_status can get operating status. \param[in] handle iic handle to operate. \param[in] data Pointer to buffer with data to transmit to IIC Master \param[in] num Number of data items to send \return 0 for success, negative for error code */ int32_t csi_iic_slave_send(iic_handle_t handle, const void *data, uint32_t num); /** \brief Start receiving data as IIC Slave. This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens. \ref csi_iic_get_status can get operating status. \param[in] handle iic handle to operate. \param[out] data Pointer to buffer for data to receive from IIC Master \param[in] num Number of data items to receive \return 0 for success, negative for error code */ int32_t csi_iic_slave_receive(iic_handle_t handle, void *data, uint32_t num); /** \brief abort transfer. \param[in] handle iic handle to operate. \return 0 for success, negative for error code */ int32_t csi_iic_abort_transfer(iic_handle_t handle); /** \brief Get IIC status. \param[in] handle iic handle to operate. \return IIC status \ref iic_status_t */ iic_status_t csi_iic_get_status(iic_handle_t handle); /** \brief control IIC power. \param[in] handle iic handle to operate. \param[in] state power state.\ref csi_power_stat_e. \return error code */ int32_t csi_iic_power_control(iic_handle_t handle, csi_power_stat_e state); /** \brief config iic mode. \param[in] handle iic handle to operate. \param[in] mode \ref iic_mode_e \return error code */ int32_t csi_iic_config_mode(iic_handle_t handle, iic_mode_e mode); /** \brief config iic speed. \param[in] handle iic handle to operate. \param[in] speed \ref iic_speed_e \return error code */ int32_t csi_iic_config_speed(iic_handle_t handle, iic_speed_e speed); /** \brief config iic address mode. \param[in] handle iic handle to operate. \param[in] addr_mode \ref iic_address_mode_e \return error code */ int32_t csi_iic_config_addr_mode(iic_handle_t handle, iic_address_mode_e addr_mode); /** \brief config iic slave address. \param[in] handle iic handle to operate. \param[in] slave_addr slave address \return error code */ int32_t csi_iic_config_slave_addr(iic_handle_t handle, int32_t slave_addr); /** \brief Get IIC transferred data count. \param[in] handle iic handle to operate. \return the number of the currently transferred data items */ uint32_t csi_iic_get_data_count(iic_handle_t handle); /** \brief Send START command. \param[in] handle iic handle to operate. \return error code */ int32_t csi_iic_send_start(iic_handle_t handle); /** \brief Send STOP command. \param[in] handle iic handle to operate. \return error code */ int32_t csi_iic_send_stop(iic_handle_t handle); /** \brief Reset IIC peripheral. \param[in] handle iic handle to operate. \return error code */ int32_t csi_iic_reset(iic_handle_t handle); #ifdef __cplusplus } #endif #endif /* _CSI_IIC_H_ */
37.678295
140
0.661557
[ "model" ]
a12089bf17c6631ff07e24330932fe220adc669d
6,328
h
C
aws-cpp-sdk-iot/include/aws/iot/model/MqttContext.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-iot/include/aws/iot/model/MqttContext.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-iot/include/aws/iot/model/MqttContext.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/iot/IoT_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/Array.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace IoT { namespace Model { /** * <p>Specifies the MQTT context to use for the test authorizer * request</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/iot-2015-05-28/MqttContext">AWS API * Reference</a></p> */ class AWS_IOT_API MqttContext { public: MqttContext(); MqttContext(Aws::Utils::Json::JsonView jsonValue); MqttContext& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline const Aws::String& GetUsername() const{ return m_username; } /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline bool UsernameHasBeenSet() const { return m_usernameHasBeenSet; } /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline void SetUsername(const Aws::String& value) { m_usernameHasBeenSet = true; m_username = value; } /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline void SetUsername(Aws::String&& value) { m_usernameHasBeenSet = true; m_username = std::move(value); } /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline void SetUsername(const char* value) { m_usernameHasBeenSet = true; m_username.assign(value); } /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithUsername(const Aws::String& value) { SetUsername(value); return *this;} /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithUsername(Aws::String&& value) { SetUsername(std::move(value)); return *this;} /** * <p>The value of the <code>username</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithUsername(const char* value) { SetUsername(value); return *this;} /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline const Aws::Utils::ByteBuffer& GetPassword() const{ return m_password; } /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline bool PasswordHasBeenSet() const { return m_passwordHasBeenSet; } /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline void SetPassword(const Aws::Utils::ByteBuffer& value) { m_passwordHasBeenSet = true; m_password = value; } /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline void SetPassword(Aws::Utils::ByteBuffer&& value) { m_passwordHasBeenSet = true; m_password = std::move(value); } /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithPassword(const Aws::Utils::ByteBuffer& value) { SetPassword(value); return *this;} /** * <p>The value of the <code>password</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithPassword(Aws::Utils::ByteBuffer&& value) { SetPassword(std::move(value)); return *this;} /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline const Aws::String& GetClientId() const{ return m_clientId; } /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline bool ClientIdHasBeenSet() const { return m_clientIdHasBeenSet; } /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline void SetClientId(const Aws::String& value) { m_clientIdHasBeenSet = true; m_clientId = value; } /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline void SetClientId(Aws::String&& value) { m_clientIdHasBeenSet = true; m_clientId = std::move(value); } /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline void SetClientId(const char* value) { m_clientIdHasBeenSet = true; m_clientId.assign(value); } /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithClientId(const Aws::String& value) { SetClientId(value); return *this;} /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithClientId(Aws::String&& value) { SetClientId(std::move(value)); return *this;} /** * <p>The value of the <code>clientId</code> key in an MQTT authorization * request.</p> */ inline MqttContext& WithClientId(const char* value) { SetClientId(value); return *this;} private: Aws::String m_username; bool m_usernameHasBeenSet; Aws::Utils::ByteBuffer m_password; bool m_passwordHasBeenSet; Aws::String m_clientId; bool m_clientIdHasBeenSet; }; } // namespace Model } // namespace IoT } // namespace Aws
31.482587
123
0.651233
[ "model" ]
a12e9b3ec3ee0d4c989ce54be258aab0d7304dff
16,136
h
C
Assignment/OpenGLEngineA3/OpenGLEngine/OldMain.h
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
3
2019-11-07T04:19:50.000Z
2019-11-07T04:26:40.000Z
Assignment/OpenGLEngineA3/OpenGLEngine/OldMain.h
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
null
null
null
Assignment/OpenGLEngineA3/OpenGLEngine/OldMain.h
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> //#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Shader.h" #include "Camera.h" #include <iostream> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow *window); unsigned int loadTexture(const char *path); // settings const unsigned int SCR_WIDTH = 1920; const unsigned int SCR_HEIGHT = 1080; // camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; bool firstMouse = true; // timing float deltaTime = 0.0f; float lastFrame = 0.0f; // lighting glm::vec3 lightPos(1.2f, 0.0f, 0.0f); int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader lightingShader("Shaders/Lighting_Maps.vs", "Shaders/Lighting_Maps.fs"); Shader lampShader("Shaders/Lamp.vs", "Shaders/Lamp.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { // positions // normals // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; // positions all containers glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; // positions of the point lights glm::vec3 pointLightPositions[] = { glm::vec3(0.7f, 0.2f, 2.0f), glm::vec3(2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f), glm::vec3(0.0f, 0.0f, -3.0f) }; // first, configure the cube's VAO (and VBO) unsigned int VBO, cubeVAO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(cubeVAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) unsigned int lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // note that we update the lamp's position attribute's stride to reflect the updated buffer data glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // load textures (we now use a utility function to keep the code more organized) // ----------------------------------------------------------------------------- unsigned int diffuseMap = loadTexture("Resources/textures/container2.png"); unsigned int specularMap = loadTexture("Resources/Textures/container2_specular.png"); // shader configuration // -------------------- lightingShader.use(); lightingShader.setInt("material.diffuse", 0); lightingShader.setInt("material.specular", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // be sure to activate shader when setting uniforms/drawing objects lightingShader.use(); lightingShader.setVec3("viewPos", camera.Position); lightingShader.setFloat("material.shininess", 32.0f); /* Here we set all the uniforms for the 5/6 types of lights we have. We have to set them manually and index the proper PointLight struct in the array to set each uniform variable. This can be done more code-friendly by defining light types as classes and set their values in there, or by using a more efficient uniform approach by using 'Uniform buffer objects', but that is something we'll discuss in the 'Advanced GLSL' tutorial. */ // directional light lightingShader.setVec3("dirLight.direction", -0.2f, -1.0f, -0.3f); lightingShader.setVec3("dirLight.ambient", 0.05f, 0.05f, 0.05f); lightingShader.setVec3("dirLight.diffuse", 0.4f, 0.4f, 0.4f); lightingShader.setVec3("dirLight.specular", 0.5f, 0.5f, 0.5f); // point light 1 lightingShader.setVec3("pointLights[0].position", pointLightPositions[0]); lightingShader.setVec3("pointLights[0].ambient", 0.05f, 0.05f, 0.05f); lightingShader.setVec3("pointLights[0].diffuse", 0.8f, 0.8f, 0.8f); lightingShader.setVec3("pointLights[0].specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("pointLights[0].constant", 1.0f); lightingShader.setFloat("pointLights[0].linear", 0.09); lightingShader.setFloat("pointLights[0].quadratic", 0.032); // point light 2 lightingShader.setVec3("pointLights[1].position", pointLightPositions[1]); lightingShader.setVec3("pointLights[1].ambient", 0.05f, 0.05f, 0.05f); lightingShader.setVec3("pointLights[1].diffuse", 0.8f, 0.8f, 0.8f); lightingShader.setVec3("pointLights[1].specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("pointLights[1].constant", 1.0f); lightingShader.setFloat("pointLights[1].linear", 0.09); lightingShader.setFloat("pointLights[1].quadratic", 0.032); // point light 3 lightingShader.setVec3("pointLights[2].position", pointLightPositions[2]); lightingShader.setVec3("pointLights[2].ambient", 0.05f, 0.05f, 0.05f); lightingShader.setVec3("pointLights[2].diffuse", 0.8f, 0.8f, 0.8f); lightingShader.setVec3("pointLights[2].specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("pointLights[2].constant", 1.0f); lightingShader.setFloat("pointLights[2].linear", 0.09); lightingShader.setFloat("pointLights[2].quadratic", 0.032); // point light 4 lightingShader.setVec3("pointLights[3].position", pointLightPositions[3]); lightingShader.setVec3("pointLights[3].ambient", 0.05f, 0.05f, 0.05f); lightingShader.setVec3("pointLights[3].diffuse", 0.8f, 0.8f, 0.8f); lightingShader.setVec3("pointLights[3].specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("pointLights[3].constant", 1.0f); lightingShader.setFloat("pointLights[3].linear", 0.09); lightingShader.setFloat("pointLights[3].quadratic", 0.032); // spotLight lightingShader.setVec3("spotLight.position", camera.Position); lightingShader.setVec3("spotLight.direction", camera.Front); lightingShader.setVec3("spotLight.ambient", 0.0f, 0.0f, 0.0f); lightingShader.setVec3("spotLight.diffuse", 1.0f, 1.0f, 1.0f); lightingShader.setVec3("spotLight.specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("spotLight.constant", 1.0f); lightingShader.setFloat("spotLight.linear", 0.09); lightingShader.setFloat("spotLight.quadratic", 0.032); lightingShader.setFloat("spotLight.cutOff", glm::cos(glm::radians(12.5f))); lightingShader.setFloat("spotLight.outerCutOff", glm::cos(glm::radians(15.0f))); // view/projection transformations glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); lightingShader.setMat4("projection", projection); lightingShader.setMat4("view", view); // world transformation glm::mat4 model = glm::mat4(1.0f); lightingShader.setMat4("model", model); // bind diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); // bind specular map glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); lightingShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // also draw the lamp object(s) lampShader.use(); lampShader.setMat4("projection", projection); lampShader.setMat4("view", view); // we now draw as many light bulbs as we have point lights. glBindVertexArray(lightVAO); for (unsigned int i = 0; i < 4; i++) { model = glm::mat4(1.0f); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube lampShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &cubeVAO); glDeleteVertexArrays(1, &lightVAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, deltaTime); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); } // utility function for loading a 2D texture from file // --------------------------------------------------- unsigned int loadTexture(char const * path) { unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; }
37.967059
130
0.639502
[ "render", "object", "model", "3d" ]
a12ee297e9f2aa95287bee5114c83f85f345709d
268
h
C
ENgine/Root/Meshes/IMeshes.h
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
13
2020-12-02T02:13:29.000Z
2022-03-11T06:14:54.000Z
ENgine/Root/Meshes/IMeshes.h
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
ENgine/Root/Meshes/IMeshes.h
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
#pragma once #include "stdio.h" #include <stdlib.h> #include "Support/Support.h" #include "MeshRes.h" namespace Oak { class CLASS_DECLSPEC IMeshes { public: virtual Mesh::Instance* LoadMesh(const char* name, TaskExecutor::SingleTaskPool* taskPool) = 0; }; }
14.888889
97
0.720149
[ "mesh" ]
a1365ce4a9712db323e358d877139ed3f36abe7d
5,822
h
C
Firmware_Common/LoRa.h
Imagimob/AFarCloud
ed37db19ff01c7a922922b61d29d44d71c937007
[ "MIT" ]
null
null
null
Firmware_Common/LoRa.h
Imagimob/AFarCloud
ed37db19ff01c7a922922b61d29d44d71c937007
[ "MIT" ]
null
null
null
Firmware_Common/LoRa.h
Imagimob/AFarCloud
ed37db19ff01c7a922922b61d29d44d71c937007
[ "MIT" ]
1
2021-12-01T14:18:21.000Z
2021-12-01T14:18:21.000Z
/* MIT License Copyright 2021 AFarCloud consortium, Imagimob AB, Nicolas Innocenti, Alex Jonsson */ // Configures LMIC and sets up the LoRa communication #ifndef __afarcloud_lora_h #define __afarcloud_lora_h #include <Arduino.h> #include "definitions.h" #include "config.h" #include <lmic.h> #include "tbeam.h" /**************** * * Definitions for the paylaod buffer and accompanying logic * ************/ //This needs to be set to true before sending operation, and will go back to false when the sending operation is done //It is used to determine when the board is allowed to go into low power mode vs when it needs to stay powered for the LoRa operations to proceed //In some distant future, we may build that into LMIC itself :) extern bool LORA_sendjob_pending; // Payload buffer. // Vanilla LMIC allows max 51 bytes at every SF. // It seems possible to remove that limitation quite easily, but for now we'll stick to it. // https://www.thethingsnetwork.org/forum/t/lmic-fails-to-send-application-payload-larger-than-51-bytes/8923/19 extern byte LORA_payload[MAX_PAYLOAD]; extern int LORA_payload_length; extern int LORA_port; //Effectively, one extra byte to be used for our application ;) extern int LORA_ACK; //0 for simple send, 1 for acknowledged sent. // NB: acknowledged sent also lead to automatic adjustment of SF and power level. // It's good to have them from time to time, but they consume ressources and airtime of the LoRa gateway. extern bool LORA_payload_full; extern int waypoints_in_payload; // Reset the payload buffer inline void reset_LoRa_payload() { LORA_payload_full = false; LORA_payload_length = 0; LORA_ACK = 0; //LORA_port = 1; waypoints_in_payload = 0; } // Call this during initializing to configure everything // NB: this will perform one attempt to connect to the LoRa network and block on failure. // The board needs to be manually reset before another attempt. void setup_LoRa(); // This attemps to trigger a send if a payload is available, while enforcing airtime rules. // Returns True if the send was triggered and False if it needs to be retried later. // It needs to be called regularly in the main loop bool LORA_try_send(); /**************** * * Configuration for LMIC * ************/ void onEvent(ev_t ev); void os_getArtEui(u1_t *buf); void os_getDevEui(u1_t *buf); void os_getDevKey(u1_t *buf); // In the original LMIC code, these config values were defined on the // gcc commandline. Since Arduino does not allow easily modifying the // compiler commandline, use this file instead. //#define CFG_eu868 1 //#define CFG_us915 1 // This is the SX1272/SX1273 radio, which is also used on the HopeRF // RFM92 boards. //#define CFG_sx1272_radio 1 // This is the SX1276/SX1277/SX1278/SX1279 radio, which is also used on // the HopeRF RFM95 boards. #define CFG_sx1276_radio 1 // 16 μs per tick // LMIC requires ticks to be 15.5μs - 100 μs long #define US_PER_OSTICK_EXPONENT 4 #define US_PER_OSTICK (1 << US_PER_OSTICK_EXPONENT) #define OSTICKS_PER_SEC (1000000 / US_PER_OSTICK) // Set this to 1 to enable some basic debug output (using printf) about // RF settings used during transmission and reception. Set to 2 to // enable more verbose output. Make sure that printf is actually // configured (e.g. on AVR it is not by default), otherwise using it can // cause crashing. #define LMIC_DEBUG_LEVEL 0 // Enable this to allow using printf() to print to the given serial port // (or any other Print object). This can be easy for debugging. The // current implementation only works on AVR, though. //#define LMIC_PRINTF_TO Serial // Any runtime assertion failures are printed to this serial port (or // any other Print object). If this is unset, any failures just silently // halt execution. #define LMIC_FAILURE_TO Serial // Uncomment this to disable all code related to joining //#define DISABLE_JOIN // Uncomment this to disable all code related to ping //#define DISABLE_PING // Uncomment this to disable all code related to beacon tracking. // Requires ping to be disabled too //#define DISABLE_BEACONS // Uncomment these to disable the corresponding MAC commands. // Class A //#define DISABLE_MCMD_DCAP_REQ // duty cycle cap //#define DISABLE_MCMD_DN2P_SET // 2nd DN window param //#define DISABLE_MCMD_SNCH_REQ // set new channel // Class B //#define DISABLE_MCMD_PING_SET // set ping freq, automatically disabled by DISABLE_PING //#define DISABLE_MCMD_BCNI_ANS // next beacon start, automatical disabled by DISABLE_BEACON // In LoRaWAN, a gateway applies I/Q inversion on TX, and nodes do the // same on RX. This ensures that gateways can talk to nodes and vice // versa, but gateways will not hear other gateways and nodes will not // hear other nodes. By uncommenting this macro, this inversion is // disabled and this node can hear other nodes. If two nodes both have // this macro set, they can talk to each other (but they can no longer // hear gateways). This should probably only be used when debugging // and/or when talking to the radio directly (e.g. like in the "raw" // example). //#define DISABLE_INVERT_IQ_ON_RX // This allows choosing between multiple included AES implementations. // Make sure exactly one of these is uncommented. // // This selects the original AES implementation included LMIC. This // implementation is optimized for speed on 32-bit processors using // fairly big lookup tables, but it takes up big amounts of flash on the // AVR architecture. // #define USE_ORIGINAL_AES // // This selects the AES implementation written by Ideetroon for their // own LoRaWAN library. It also uses lookup tables, but smaller // byte-oriented ones, making it use a lot less flash space (but it is // also about twice as slow as the original). #define USE_IDEETRON_AES #endif __afarcloud_lora_h
38.052288
145
0.757128
[ "object" ]
a14431d7b36d0bb1ca82b77b938468d609a0d393
5,029
h
C
SRC/common/pixelgroup.h
usnistgov/OOF3D
4fd423a48aea9c5dc207520f02de53ae184be74c
[ "X11" ]
31
2015-04-01T15:59:36.000Z
2022-03-18T20:21:47.000Z
SRC/common/pixelgroup.h
usnistgov/OOF3D
4fd423a48aea9c5dc207520f02de53ae184be74c
[ "X11" ]
3
2015-02-06T19:30:24.000Z
2017-05-25T14:14:31.000Z
SRC/common/pixelgroup.h
usnistgov/OOF3D
4fd423a48aea9c5dc207520f02de53ae184be74c
[ "X11" ]
7
2015-01-23T15:19:22.000Z
2021-06-09T09:03:59.000Z
// -*- C++ -*- /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ #include <oofconfig.h> #ifndef PIXELGROUP_H #define PIXELGROUP_H #include "common/boolarray.h" #include "common/coord.h" #include "common/lock.h" #include "common/pixelattribute.h" #include <string> #include <vector> class BitmapOverlay; class CMicrostructure; class CPixelSelection; // PixelSet is the base class for PixelGroup. It keep track of the // pixels, but doesn't manipulate the Microstructure's lists of pixel // groups or categories. class PixelSet { private: static int ngroups; const int id_; protected: mutable SLock member_lock; void weed() const; mutable ICoordVector members_; mutable bool weeded; ICoord geometry; CMicrostructure *microstructure; public: PixelSet(const ICoord *geometry, CMicrostructure *microstructure); PixelSet(const PixelSet&); virtual ~PixelSet(); int id() const { return id_; } void resize(const ICoord *newgeom); int len() const; bool empty() const; PixelSet *clone() const { return new PixelSet(*this); } CMicrostructure *getMicrostructure() const { return microstructure; } void add(CPixelSelection *sel); void add(PixelSet *set); void addWithoutCheck(CPixelSelection *sel); void addWithoutCheck(PixelSet *set); virtual void add(const ICoordVector*); virtual void addWithoutCheck(const ICoordVector*); // ignore active area virtual void add(const ICoord&); void addWithoutCheck(const ICoord&); void remove(CPixelSelection *sel); void remove(PixelSet *set); void removeWithoutCheck(CPixelSelection *sel); void removeWithoutCheck(PixelSet *set); virtual void remove(const ICoordVector*); virtual void removeWithoutCheck(const ICoordVector*); // ICoord pop(); // remove and return one pixel virtual void clear(); virtual void setFromBitmap(const BitmapOverlay&); const ICoordVector *members() const; void getBounds(ICoord &min, ICoord &max) const; void despeckle(int threshold, BoolArray &selected) const; void elkcepsed(int threshold, BoolArray &selected) const; void expand(double range, BoolArray &selected) const; void shrink(double range, BoolArray &selected) const; }; class GroupList; class PixelGroup; //typedef void (GroupList::*ManipulateGroupList)(PixelGroup*); class PixelGroup : public PixelSet, public SubAttribute { private: bool meshable_; public: PixelGroup(const std::string &name, const ICoord *geometry, CMicrostructure *microstructure); PixelGroup(const std::string &name, const PixelGroup &othergroup); virtual ~PixelGroup(); virtual bool is_meshable() const { return meshable_; } void set_meshable(bool); virtual void add(const ICoordVector *pixels); virtual void addWithoutCheck(const ICoordVector*); virtual void add(const ICoord&); virtual void remove(const ICoordVector *pixels); virtual void clear(); bool pixelInGroup(const ICoord*); virtual void print(std::ostream&) const; }; //=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=//=\\=// class GroupList : public ListAttribute { private: static const std::string displayname_; public: GroupList() : ListAttribute() {}; GroupList(const GroupList &g) : ListAttribute(g) {}; virtual GroupList *clone() const {return new GroupList(*this);}; virtual bool operator<(const PixelAttribute&) const; virtual const std::string &displayname() const {return displayname_;}; // static void buildAttributeChangeMap(AttributeVectorMap &avm, ManipulateListAttribute manip, // PixelGroup *group, CMicrostructure *microstructure); }; class GroupListGlobalData : public PixelAttributeGlobalData { public: GroupListGlobalData() : PixelAttributeGlobalData() {}; virtual ~GroupListGlobalData() {}; void removeGroup(const std::string &name); }; std::vector<std::string> *pixelGroupNames(const CMicrostructure*, int cat); bool pixelGroupQueryPixel(const CMicrostructure&, const ICoord&, const PixelGroup*); bool pixelGroupQueryCategory(const CMicrostructure&, int, const PixelGroup*); class PixelGroupAttributeRegistration : public PxlAttributeRegistration { private: static const std::string classname_; static const std::string modulename_; public: PixelGroupAttributeRegistration(); virtual ~PixelGroupAttributeRegistration() {} virtual PixelAttribute *createAttribute(const CMicrostructure*) const; virtual PixelAttributeGlobalData *createAttributeGlobalData( const CMicrostructure *ms) const; virtual const std::string &classname() const { return classname_;} virtual const std::string &modulename() const { return modulename_; } }; #endif // PIXELGROUP_H
33.085526
97
0.744482
[ "geometry", "vector" ]
a14691c9c10008c5e69b977e58dc5c2be548a294
57,724
c
C
deps/hts_engine_API-1.09/lib/HTS_model.c
TanUkkii007/node-openjtalk
5344d3b4c8f5e3464286604f33f581cda4474a31
[ "MIT" ]
25
2015-07-06T04:24:56.000Z
2021-01-19T10:51:23.000Z
src/lib/HTS_model.c
mivoq/hts_engine_api
59df073f16d6e37feef4eb85b255a6ac453fb39b
[ "BSD-2-Clause", "Unlicense" ]
1
2015-07-10T07:41:11.000Z
2015-07-10T08:49:36.000Z
src/lib/HTS_model.c
mivoq/hts_engine_api
59df073f16d6e37feef4eb85b255a6ac453fb39b
[ "BSD-2-Clause", "Unlicense" ]
5
2015-07-06T08:13:17.000Z
2022-02-15T16:33:53.000Z
/* ----------------------------------------------------------------- */ /* The HMM-Based Speech Synthesis Engine "hts_engine API" */ /* developed by HTS Working Group */ /* http://hts-engine.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2001-2014 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 2001-2008 Tokyo Institute of Technology */ /* Interdisciplinary Graduate School of */ /* Science and Engineering */ /* */ /* 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 HTS working group nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */ /* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */ /* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */ /* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */ /* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */ /* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */ /* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */ /* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */ /* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* ----------------------------------------------------------------- */ #ifndef HTS_MODEL_C #define HTS_MODEL_C #ifdef __cplusplus #define HTS_MODEL_C_START extern "C" { #define HTS_MODEL_C_END } #else #define HTS_MODEL_C_START #define HTS_MODEL_C_END #endif /* __CPLUSPLUS */ HTS_MODEL_C_START; #include <stdlib.h> /* for atoi(),abs() */ #include <string.h> /* for strlen(),strstr(),strrchr(),strcmp() */ #include <ctype.h> /* for isdigit() */ /* hts_engine libraries */ #include "HTS_hidden.h" #ifdef WIN32 typedef unsigned __int32 uint32_t; #else #include <stdint.h> #endif /* WIN32 */ /* HTS_dp_match: recursive matching */ static HTS_Boolean HTS_dp_match(const char *string, const char *pattern, size_t pos, size_t max) { if (pos > max) return FALSE; if (string[0] == '\0' && pattern[0] == '\0') return TRUE; if (pattern[0] == '*') { if (HTS_dp_match(string + 1, pattern, pos + 1, max) == 1) return TRUE; else return HTS_dp_match(string, pattern + 1, pos, max); } if (string[0] == pattern[0] || pattern[0] == '?') { if (HTS_dp_match(string + 1, pattern + 1, pos + 1, max + 1) == 1) return TRUE; } return FALSE; } /* HTS_pattern_match: pattern matching function */ static HTS_Boolean HTS_pattern_match(const char *string, const char *pattern) { size_t i, j; size_t buff_length, max = 0, nstar = 0, nquestion = 0; char buff[HTS_MAXBUFLEN]; size_t pattern_length = strlen(pattern); for (i = 0; i < pattern_length; i++) { switch (pattern[i]) { case '*': nstar++; break; case '?': nquestion++; max++; break; default: max++; } } if (nstar == 2 && nquestion == 0 && pattern[0] == '*' && pattern[i - 1] == '*') { /* only string matching is required */ buff_length = i - 2; for (i = 0, j = 1; i < buff_length; i++, j++) buff[i] = pattern[j]; buff[buff_length] = '\0'; if (strstr(string, buff) != NULL) return TRUE; else return FALSE; } else return HTS_dp_match(string, pattern, 0, strlen(string) - max); } /* HTS_is_num: check given buffer is number or not */ static HTS_Boolean HTS_is_num(const char *buff) { size_t i; size_t length = strlen(buff); for (i = 0; i < length; i++) if (!(isdigit((int) buff[i]) || (buff[i] == '-'))) return FALSE; return TRUE; } /* HTS_name2num: convert name of node to number */ static size_t HTS_name2num(const char *buff) { size_t i; for (i = strlen(buff) - 1; '0' <= buff[i] && buff[i] <= '9'; i--); i++; return (size_t) atoi(&buff[i]); } /* HTS_get_state_num: return the number of state */ static size_t HTS_get_state_num(const char *string) { const char *left, *right; left = strchr(string, '['); if (left == NULL) return 0; left++; right = strchr(left, ']'); if (right == NULL) return 0; return (size_t) atoi(left); } /* HTS_Question_initialize: initialize question */ static void HTS_Question_initialize(HTS_Question * question) { question->string = NULL; question->head = NULL; question->next = NULL; } /* HTS_Question_clear: clear loaded question */ static void HTS_Question_clear(HTS_Question * question) { HTS_Pattern *pattern, *next_pattern; if (question->string != NULL) HTS_free(question->string); for (pattern = question->head; pattern; pattern = next_pattern) { next_pattern = pattern->next; HTS_free(pattern->string); HTS_free(pattern); } HTS_Question_initialize(question); } /* HTS_Question_load: Load questions from file */ static HTS_Boolean HTS_Question_load(HTS_Question * question, HTS_File * fp) { char buff[HTS_MAXBUFLEN]; HTS_Pattern *pattern, *last_pattern; if (question == NULL || fp == NULL) return FALSE; HTS_Question_clear(question); /* get question name */ if (HTS_get_pattern_token(fp, buff) == FALSE) return FALSE; question->string = HTS_strdup(buff); /* get pattern list */ if (HTS_get_pattern_token(fp, buff) == FALSE) { HTS_Question_clear(question); return FALSE; } last_pattern = NULL; if (strcmp(buff, "{") == 0) { while (1) { if (HTS_get_pattern_token(fp, buff) == FALSE) { HTS_Question_clear(question); return FALSE; } pattern = (HTS_Pattern *) HTS_calloc(1, sizeof(HTS_Pattern)); if (question->head != NULL) last_pattern->next = pattern; else /* first time */ question->head = pattern; pattern->string = HTS_strdup(buff); pattern->next = NULL; if (HTS_get_pattern_token(fp, buff) == FALSE) { HTS_Question_clear(question); return FALSE; } if (!strcmp(buff, "}")) break; last_pattern = pattern; } } return TRUE; } /* HTS_Question_match: check given string match given question */ static HTS_Boolean HTS_Question_match(HTS_Question * question, const char *string) { HTS_Pattern *pattern; for (pattern = question->head; pattern; pattern = pattern->next) if (HTS_pattern_match(string, pattern->string)) return TRUE; return FALSE; } /* HTS_Question_find: find question from question list */ static HTS_Question *HTS_Question_find(HTS_Question * question, const char *string) { for (; question; question = question->next) if (strcmp(string, question->string) == 0) return question; return NULL; } /* HTS_Node_initialzie: initialize node */ static void HTS_Node_initialize(HTS_Node * node) { node->index = 0; node->pdf = 0; node->yes = NULL; node->no = NULL; node->next = NULL; node->quest = NULL; } /* HTS_Node_clear: recursive function to free node */ static void HTS_Node_clear(HTS_Node * node) { if (node->yes != NULL) { HTS_Node_clear(node->yes); HTS_free(node->yes); } if (node->no != NULL) { HTS_Node_clear(node->no); HTS_free(node->no); } HTS_Node_initialize(node); } /* HTS_Node_find: find node for given number */ static HTS_Node *HTS_Node_find(HTS_Node * node, int num) { for (; node; node = node->next) if (node->index == num) return node; return NULL; } /* HTS_Tree_initialize: initialize tree */ static void HTS_Tree_initialize(HTS_Tree * tree) { tree->head = NULL; tree->next = NULL; tree->root = NULL; tree->state = 0; } /* HTS_Tree_clear: clear given tree */ static void HTS_Tree_clear(HTS_Tree * tree) { HTS_Pattern *pattern, *next_pattern; for (pattern = tree->head; pattern; pattern = next_pattern) { next_pattern = pattern->next; HTS_free(pattern->string); HTS_free(pattern); } if (tree->root != NULL) { HTS_Node_clear(tree->root); HTS_free(tree->root); } HTS_Tree_initialize(tree); } /* HTS_Tree_parse_pattern: parse pattern specified for each tree */ static void HTS_Tree_parse_pattern(HTS_Tree * tree, char *string) { char *left, *right; HTS_Pattern *pattern, *last_pattern; tree->head = NULL; last_pattern = NULL; /* parse tree pattern */ if ((left = strchr(string, '{')) != NULL) { /* pattern is specified */ string = left + 1; if (*string == '(') ++string; right = strrchr(string, '}'); if (string < right && *(right - 1) == ')') --right; *right = ','; /* parse pattern */ while ((left = strchr(string, ',')) != NULL) { pattern = (HTS_Pattern *) HTS_calloc(1, sizeof(HTS_Pattern)); if (tree->head) { last_pattern->next = pattern; } else { tree->head = pattern; } *left = '\0'; pattern->string = HTS_strdup(string); string = left + 1; pattern->next = NULL; last_pattern = pattern; } } } /* HTS_Tree_load: load trees */ static HTS_Boolean HTS_Tree_load(HTS_Tree * tree, HTS_File * fp, HTS_Question * question) { char buff[HTS_MAXBUFLEN]; HTS_Node *node, *last_node; if (tree == NULL || fp == NULL) return FALSE; if (HTS_get_pattern_token(fp, buff) == FALSE) { HTS_Tree_clear(tree); return FALSE; } node = (HTS_Node *) HTS_calloc(1, sizeof(HTS_Node)); HTS_Node_initialize(node); tree->root = last_node = node; if (strcmp(buff, "{") == 0) { while (HTS_get_pattern_token(fp, buff) == TRUE && strcmp(buff, "}") != 0) { node = HTS_Node_find(last_node, atoi(buff)); if (node == NULL) { HTS_error(0, "HTS_Tree_load: Cannot find node %d.\n", atoi(buff)); HTS_Tree_clear(tree); return FALSE; } if (HTS_get_pattern_token(fp, buff) == FALSE) { HTS_Tree_clear(tree); return FALSE; } node->quest = HTS_Question_find(question, buff); if (node->quest == NULL) { HTS_error(0, "HTS_Tree_load: Cannot find question %s.\n", buff); HTS_Tree_clear(tree); return FALSE; } node->yes = (HTS_Node *) HTS_calloc(1, sizeof(HTS_Node)); node->no = (HTS_Node *) HTS_calloc(1, sizeof(HTS_Node)); HTS_Node_initialize(node->yes); HTS_Node_initialize(node->no); if (HTS_get_pattern_token(fp, buff) == FALSE) { node->quest = NULL; free(node->yes); free(node->no); HTS_Tree_clear(tree); return FALSE; } if (HTS_is_num(buff)) node->no->index = atoi(buff); else node->no->pdf = HTS_name2num(buff); node->no->next = last_node; last_node = node->no; if (HTS_get_pattern_token(fp, buff) == FALSE) { node->quest = NULL; free(node->yes); free(node->no); HTS_Tree_clear(tree); return FALSE; } if (HTS_is_num(buff)) node->yes->index = atoi(buff); else node->yes->pdf = HTS_name2num(buff); node->yes->next = last_node; last_node = node->yes; } } else { node->pdf = HTS_name2num(buff); } return TRUE; } /* HTS_Node_search: tree search */ static size_t HTS_Tree_search_node(HTS_Tree * tree, const char *string) { HTS_Node *node = tree->root; while (node != NULL) { if (node->quest == NULL) return node->pdf; if (HTS_Question_match(node->quest, string)) { if (node->yes->pdf > 0) return node->yes->pdf; node = node->yes; } else { if (node->no->pdf > 0) return node->no->pdf; node = node->no; } } HTS_error(0, "HTS_Tree_search_node: Cannot find node.\n"); return 1; } /* HTS_Window_initialize: initialize dynamic window */ static void HTS_Window_initialize(HTS_Window * win) { win->size = 0; win->l_width = NULL; win->r_width = NULL; win->coefficient = NULL; win->max_width = 0; } /* HTS_Window_clear: free dynamic window */ static void HTS_Window_clear(HTS_Window * win) { size_t i; if (win->coefficient != NULL) { for (i = 0; i < win->size; i++) { win->coefficient[i] += win->l_width[i]; HTS_free(win->coefficient[i]); } HTS_free(win->coefficient); } if (win->l_width) HTS_free(win->l_width); if (win->r_width) HTS_free(win->r_width); HTS_Window_initialize(win); } /* HTS_Window_load: load dynamic windows */ static HTS_Boolean HTS_Window_load(HTS_Window * win, HTS_File ** fp, size_t size) { size_t i, j; size_t fsize, length; char buff[HTS_MAXBUFLEN]; HTS_Boolean result = TRUE; /* check */ if (win == NULL || fp == NULL || size == 0) return FALSE; win->size = size; win->l_width = (int *) HTS_calloc(win->size, sizeof(int)); win->r_width = (int *) HTS_calloc(win->size, sizeof(int)); win->coefficient = (double **) HTS_calloc(win->size, sizeof(double *)); /* set delta coefficents */ for (i = 0; i < win->size; i++) { if (HTS_get_token_from_fp(fp[i], buff) == FALSE) { result = FALSE; fsize = 1; } else { fsize = atoi(buff); if (fsize == 0) { result = FALSE; fsize = 1; } } /* read coefficients */ win->coefficient[i] = (double *) HTS_calloc(fsize, sizeof(double)); for (j = 0; j < fsize; j++) { if (HTS_get_token_from_fp(fp[i], buff) == FALSE) { result = FALSE; win->coefficient[i][j] = 0.0; } else { win->coefficient[i][j] = (double) atof(buff); } } /* set pointer */ length = fsize / 2; win->coefficient[i] += length; win->l_width[i] = -1 * (int) length; win->r_width[i] = (int) length; if (fsize % 2 == 0) win->r_width[i]--; } /* calcurate max_width to determine size of band matrix */ win->max_width = 0; for (i = 0; i < win->size; i++) { if (win->max_width < (size_t) abs(win->l_width[i])) win->max_width = abs(win->l_width[i]); if (win->max_width < (size_t) abs(win->r_width[i])) win->max_width = abs(win->r_width[i]); } if (result == FALSE) { HTS_Window_clear(win); return FALSE; } return TRUE; } /* HTS_Model_initialize: initialize model */ static void HTS_Model_initialize(HTS_Model * model) { model->vector_length = 0; model->num_windows = 0; model->is_msd = FALSE; model->ntree = 0; model->npdf = NULL; model->pdf = NULL; model->tree = NULL; model->question = NULL; } /* HTS_Model_clear: free pdfs and trees */ static void HTS_Model_clear(HTS_Model * model) { size_t i, j; HTS_Question *question, *next_question; HTS_Tree *tree, *next_tree; for (question = model->question; question; question = next_question) { next_question = question->next; HTS_Question_clear(question); HTS_free(question); } for (tree = model->tree; tree; tree = next_tree) { next_tree = tree->next; HTS_Tree_clear(tree); HTS_free(tree); } if (model->pdf) { for (i = 2; i <= model->ntree + 1; i++) { for (j = 1; j <= model->npdf[i]; j++) { HTS_free(model->pdf[i][j]); } model->pdf[i]++; HTS_free(model->pdf[i]); } model->pdf += 2; HTS_free(model->pdf); } if (model->npdf) { model->npdf += 2; HTS_free(model->npdf); } HTS_Model_initialize(model); } /* HTS_Model_load_tree: load trees */ static HTS_Boolean HTS_Model_load_tree(HTS_Model * model, HTS_File * fp) { char buff[HTS_MAXBUFLEN]; HTS_Question *question, *last_question; HTS_Tree *tree, *last_tree; size_t state; /* check */ if (model == NULL) { HTS_error(0, "HTS_Model_load_tree: File for trees is not specified.\n"); return FALSE; } if (fp == NULL) { model->ntree = 1; return TRUE; } model->ntree = 0; last_question = NULL; last_tree = NULL; while (!HTS_feof(fp)) { HTS_get_pattern_token(fp, buff); /* parse questions */ if (strcmp(buff, "QS") == 0) { question = (HTS_Question *) HTS_calloc(1, sizeof(HTS_Question)); HTS_Question_initialize(question); if (HTS_Question_load(question, fp) == FALSE) { free(question); HTS_Model_clear(model); return FALSE; } if (model->question) last_question->next = question; else model->question = question; question->next = NULL; last_question = question; } /* parse trees */ state = HTS_get_state_num(buff); if (state != 0) { tree = (HTS_Tree *) HTS_calloc(1, sizeof(HTS_Tree)); HTS_Tree_initialize(tree); tree->state = state; HTS_Tree_parse_pattern(tree, buff); if (HTS_Tree_load(tree, fp, model->question) == FALSE) { free(tree); HTS_Model_clear(model); return FALSE; } if (model->tree) last_tree->next = tree; else model->tree = tree; tree->next = NULL; last_tree = tree; model->ntree++; } } /* No Tree information in tree file */ if (model->tree == NULL) model->ntree = 1; return TRUE; } /* HTS_Model_load_pdf: load pdfs */ static HTS_Boolean HTS_Model_load_pdf(HTS_Model * model, HTS_File * fp, size_t vector_length, size_t num_windows, HTS_Boolean is_msd) { uint32_t i; size_t j, k; HTS_Boolean result = TRUE; size_t len; /* check */ if (model == NULL || fp == NULL || model->ntree <= 0) { HTS_error(1, "HTS_Model_load_pdf: File for pdfs is not specified.\n"); return FALSE; } /* read MSD flag */ model->vector_length = vector_length; model->num_windows = num_windows; model->is_msd = is_msd; model->npdf = (size_t *) HTS_calloc(model->ntree, sizeof(size_t)); model->npdf -= 2; /* read the number of pdfs */ for (j = 2; j <= model->ntree + 1; j++) { if (HTS_fread_little_endian(&i, sizeof(i), 1, fp) != 1) { result = FALSE; break; } model->npdf[j] = (size_t) i; } for (j = 2; j <= model->ntree + 1; j++) { if (model->npdf[j] <= 0) { HTS_error(1, "HTS_Model_load_pdf: # of pdfs at %d-th state should be positive.\n", j); result = FALSE; break; } } if (result == FALSE) { model->npdf += 2; free(model->npdf); HTS_Model_initialize(model); return FALSE; } model->pdf = (float ***) HTS_calloc(model->ntree, sizeof(float **)); model->pdf -= 2; /* read means and variances */ if (is_msd) /* for MSD */ len = model->vector_length * model->num_windows * 2 + 1; else len = model->vector_length * model->num_windows * 2; for (j = 2; j <= model->ntree + 1; j++) { model->pdf[j] = (float **) HTS_calloc(model->npdf[j], sizeof(float *)); model->pdf[j]--; for (k = 1; k <= model->npdf[j]; k++) { model->pdf[j][k] = (float *) HTS_calloc(len, sizeof(float)); if (HTS_fread_little_endian(model->pdf[j][k], sizeof(float), len, fp) != len) result = FALSE; } } if (result == FALSE) { HTS_Model_clear(model); return FALSE; } return TRUE; } /* HTS_Model_load: load pdf and tree */ static HTS_Boolean HTS_Model_load(HTS_Model * model, HTS_File * pdf, HTS_File * tree, size_t vector_length, size_t num_windows, HTS_Boolean is_msd) { /* check */ if (model == NULL || pdf == NULL || vector_length == 0 || num_windows == 0) return FALSE; /* reset */ HTS_Model_clear(model); /* load tree */ if (HTS_Model_load_tree(model, tree) != TRUE) { HTS_Model_clear(model); return FALSE; } /* load pdf */ if (HTS_Model_load_pdf(model, pdf, vector_length, num_windows, is_msd) != TRUE) { HTS_Model_clear(model); return FALSE; } return TRUE; } /* HTS_Model_get_index: get index of tree and PDF */ static void HTS_Model_get_index(HTS_Model * model, size_t state_index, const char *string, size_t * tree_index, size_t * pdf_index) { HTS_Tree *tree; HTS_Pattern *pattern; HTS_Boolean find; (*tree_index) = 2; (*pdf_index) = 1; if (model->tree == NULL) return; find = FALSE; for (tree = model->tree; tree; tree = tree->next) { if (tree->state == state_index) { pattern = tree->head; if (!pattern) find = TRUE; for (; pattern; pattern = pattern->next) if (HTS_pattern_match(string, pattern->string)) { find = TRUE; break; } if (find) break; } (*tree_index)++; } if (tree != NULL) { (*pdf_index) = HTS_Tree_search_node(tree, string); } else { (*pdf_index) = HTS_Tree_search_node(model->tree, string); } } /* HTS_ModelSet_initialize: initialize model set */ void HTS_ModelSet_initialize(HTS_ModelSet * ms) { ms->hts_voice_version = NULL; ms->sampling_frequency = 0; ms->frame_period = 0; ms->num_voices = 0; ms->num_states = 0; ms->num_streams = 0; ms->stream_type = NULL; ms->fullcontext_format = NULL; ms->fullcontext_version = NULL; ms->gv_off_context = NULL; ms->option = NULL; ms->duration = NULL; ms->window = NULL; ms->stream = NULL; ms->gv = NULL; } /* HTS_ModelSet_clear: free model set */ void HTS_ModelSet_clear(HTS_ModelSet * ms) { size_t i, j; if (ms->hts_voice_version != NULL) free(ms->hts_voice_version); if (ms->stream_type != NULL) free(ms->stream_type); if (ms->fullcontext_format != NULL) free(ms->fullcontext_format); if (ms->fullcontext_version != NULL) free(ms->fullcontext_version); if (ms->gv_off_context != NULL) { HTS_Question_clear(ms->gv_off_context); free(ms->gv_off_context); } if (ms->option != NULL) { for (i = 0; i < ms->num_streams; i++) if (ms->option[i] != NULL) free(ms->option[i]); free(ms->option); } if (ms->duration != NULL) { for (i = 0; i < ms->num_voices; i++) HTS_Model_clear(&ms->duration[i]); free(ms->duration); } if (ms->window != NULL) { for (i = 0; i < ms->num_streams; i++) HTS_Window_clear(&ms->window[i]); free(ms->window); } if (ms->stream != NULL) { for (i = 0; i < ms->num_voices; i++) { for (j = 0; j < ms->num_streams; j++) HTS_Model_clear(&ms->stream[i][j]); free(ms->stream[i]); } HTS_free(ms->stream); } if (ms->gv != NULL) { for (i = 0; i < ms->num_voices; i++) { for (j = 0; j < ms->num_streams; j++) HTS_Model_clear(&ms->gv[i][j]); free(ms->gv[i]); } free(ms->gv); } HTS_ModelSet_initialize(ms); } /* HTS_match_head_string: return true if head of str is equal to pattern */ static HTS_Boolean HTS_match_head_string(const char *str, const char *pattern, size_t * matched_size) { (*matched_size) = 0; while (1) { if (pattern[(*matched_size)] == '\0') return TRUE; if (str[(*matched_size)] == '\0') return FALSE; if (str[(*matched_size)] != pattern[(*matched_size)]) return FALSE; (*matched_size)++; } } /* HTS_strequal: strcmp wrapper */ static HTS_Boolean HTS_strequal(const char *s1, const char *s2) { if (s1 == NULL && s2 == NULL) return TRUE; else if (s1 == NULL || s2 == NULL) return FALSE; else return strcmp(s1, s2) == 0 ? TRUE : FALSE; } /* HTS_ModelSet_load: load model set */ HTS_Boolean HTS_ModelSet_load(HTS_ModelSet * ms, char **voices, size_t num_voices) { size_t i, j, k, s, e; HTS_Boolean error = FALSE; HTS_File *fp; char buff1[HTS_MAXBUFLEN]; char buff2[HTS_MAXBUFLEN]; size_t matched_size; char **stream_type_list = NULL; size_t *vector_length = NULL; HTS_Boolean *is_msd = NULL; size_t *num_windows = NULL; HTS_Boolean *use_gv = NULL; char *gv_off_context = NULL; /* temporary values */ char *temp_hts_voice_version; size_t temp_sampling_frequency; size_t temp_frame_period; size_t temp_num_states; size_t temp_num_streams; char *temp_stream_type; char *temp_fullcontext_format; char *temp_fullcontext_version; char *temp_gv_off_context; size_t *temp_vector_length; HTS_Boolean *temp_is_msd; size_t *temp_num_windows; HTS_Boolean *temp_use_gv; char **temp_option; char *temp_duration_pdf; char *temp_duration_tree; char ***temp_stream_win; char **temp_stream_pdf; char **temp_stream_tree; char **temp_gv_pdf; char **temp_gv_tree; long start_of_data; HTS_File *pdf_fp = NULL; HTS_File *tree_fp = NULL; HTS_File **win_fp = NULL; HTS_File *gv_off_context_fp = NULL; HTS_ModelSet_clear(ms); if (ms == NULL || voices == NULL || num_voices < 1) return FALSE; ms->num_voices = num_voices; for (i = 0; i < num_voices && error == FALSE; i++) { /* open file */ fp = HTS_fopen_from_fn(voices[i], "rb"); if (fp == NULL) { error = TRUE; break; } /* reset GLOBAL options */ temp_hts_voice_version = NULL; temp_sampling_frequency = 0; temp_frame_period = 0; temp_num_states = 0; temp_num_streams = 0; temp_stream_type = NULL; temp_fullcontext_format = NULL; temp_fullcontext_version = NULL; temp_gv_off_context = NULL; if (HTS_get_token_from_fp_with_separator(fp, buff1, '\n') != TRUE) { error = TRUE; break; } /* load GLOBAL options */ if (HTS_strequal(buff1, "[GLOBAL]") != TRUE) { error = TRUE; break; } while (1) { if (HTS_get_token_from_fp_with_separator(fp, buff1, '\n') != TRUE) { error = TRUE; break; } if (HTS_strequal(buff1, "[STREAM]") == TRUE) { break; } else if (HTS_match_head_string(buff1, "HTS_VOICE_VERSION:", &matched_size) == TRUE) { if (temp_hts_voice_version != NULL) free(temp_hts_voice_version); temp_hts_voice_version = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "SAMPLING_FREQUENCY:", &matched_size) == TRUE) { temp_sampling_frequency = (size_t) atoi(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "FRAME_PERIOD:", &matched_size) == TRUE) { temp_frame_period = (size_t) atoi(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "NUM_STATES:", &matched_size) == TRUE) { temp_num_states = (size_t) atoi(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "NUM_STREAMS:", &matched_size) == TRUE) { temp_num_streams = (size_t) atoi(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "STREAM_TYPE:", &matched_size) == TRUE) { if (temp_stream_type != NULL) free(temp_stream_type); temp_stream_type = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "FULLCONTEXT_FORMAT:", &matched_size) == TRUE) { if (temp_fullcontext_format != NULL) free(temp_fullcontext_format); temp_fullcontext_format = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "FULLCONTEXT_VERSION:", &matched_size) == TRUE) { if (temp_fullcontext_version != NULL) free(temp_fullcontext_version); temp_fullcontext_version = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "GV_OFF_CONTEXT:", &matched_size) == TRUE) { if (temp_gv_off_context != NULL) free(temp_gv_off_context); temp_gv_off_context = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "COMMENT:", &matched_size) == TRUE) { } else { HTS_error(0, "HTS_ModelSet_load: Unknown option %s.\n", buff1); } } /* check GLOBAL options */ if (i == 0) { ms->hts_voice_version = temp_hts_voice_version; ms->sampling_frequency = temp_sampling_frequency; ms->frame_period = temp_frame_period; ms->num_states = temp_num_states; ms->num_streams = temp_num_streams; ms->stream_type = temp_stream_type; ms->fullcontext_format = temp_fullcontext_format; ms->fullcontext_version = temp_fullcontext_version; gv_off_context = temp_gv_off_context; } else { if (HTS_strequal(ms->hts_voice_version, temp_hts_voice_version) != TRUE) error = TRUE; if (ms->sampling_frequency != temp_sampling_frequency) error = TRUE; if (ms->frame_period != temp_frame_period) error = TRUE; if (ms->num_states != temp_num_states) error = TRUE; if (ms->num_streams != temp_num_streams) error = TRUE; if (HTS_strequal(ms->stream_type, temp_stream_type) != TRUE) error = TRUE; if (HTS_strequal(ms->fullcontext_format, temp_fullcontext_format) != TRUE) error = TRUE; if (HTS_strequal(ms->fullcontext_version, temp_fullcontext_version) != TRUE) error = TRUE; if (HTS_strequal(gv_off_context, temp_gv_off_context) != TRUE) error = TRUE; if (temp_hts_voice_version != NULL) free(temp_hts_voice_version); if (temp_stream_type != NULL) free(temp_stream_type); if (temp_fullcontext_format != NULL) free(temp_fullcontext_format); if (temp_fullcontext_version != NULL) free(temp_fullcontext_version); if (temp_gv_off_context != NULL) free(temp_gv_off_context); } /* find stream names */ if (i == 0) { stream_type_list = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0, matched_size = 0; j < ms->num_streams; j++) { if (HTS_get_token_from_string_with_separator(ms->stream_type, &matched_size, buff2, ',') == TRUE) { stream_type_list[j] = HTS_strdup(buff2); } else { stream_type_list[j] = NULL; error = TRUE; } } } if (error != FALSE) { HTS_fclose(fp); break; } /* reset STREAM options */ temp_vector_length = (size_t *) HTS_calloc(ms->num_streams, sizeof(size_t)); for (j = 0; j < ms->num_streams; j++) temp_vector_length[j] = 0; temp_is_msd = (HTS_Boolean *) HTS_calloc(ms->num_streams, sizeof(HTS_Boolean)); for (j = 0; j < ms->num_streams; j++) temp_is_msd[j] = FALSE; temp_num_windows = (size_t *) HTS_calloc(ms->num_streams, sizeof(size_t)); for (j = 0; j < ms->num_streams; j++) temp_num_windows[j] = 0; temp_use_gv = (HTS_Boolean *) HTS_calloc(ms->num_streams, sizeof(HTS_Boolean)); for (j = 0; j < ms->num_streams; j++) temp_use_gv[j] = FALSE; temp_option = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0; j < ms->num_streams; j++) temp_option[j] = NULL; /* load STREAM options */ while (1) { if (HTS_get_token_from_fp_with_separator(fp, buff1, '\n') != TRUE) { error = TRUE; break; } if (strcmp(buff1, "[POSITION]") == 0) { break; } else if (HTS_match_head_string(buff1, "VECTOR_LENGTH[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) if (strcmp(stream_type_list[j], buff2) == 0) { temp_vector_length[j] = (size_t) atoi(&buff1[matched_size]); break; } } } } else if (HTS_match_head_string(buff1, "IS_MSD[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) if (strcmp(stream_type_list[j], buff2) == 0) { temp_is_msd[j] = (buff1[matched_size] == '1') ? TRUE : FALSE; break; } } } } else if (HTS_match_head_string(buff1, "NUM_WINDOWS[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) if (strcmp(stream_type_list[j], buff2) == 0) { temp_num_windows[j] = (size_t) atoi(&buff1[matched_size]); break; } } } } else if (HTS_match_head_string(buff1, "USE_GV[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) if (strcmp(stream_type_list[j], buff2) == 0) { temp_use_gv[j] = (buff1[matched_size] == '1') ? TRUE : FALSE; break; } } } } else if (HTS_match_head_string(buff1, "OPTION[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) if (strcmp(stream_type_list[j], buff2) == 0) { if (temp_option[j] != NULL) free(temp_option[j]); temp_option[j] = HTS_strdup(&buff1[matched_size]); break; } } } } else { HTS_error(0, "HTS_ModelSet_load: Unknown option %s.\n", buff1); } } /* check STREAM options */ if (i == 0) { vector_length = temp_vector_length; is_msd = temp_is_msd; num_windows = temp_num_windows; use_gv = temp_use_gv; ms->option = temp_option; } else { for (j = 0; j < ms->num_streams; j++) if (vector_length[j] != temp_vector_length[j]) error = TRUE; for (j = 0; j < ms->num_streams; j++) if (is_msd[j] != is_msd[j]) error = TRUE; for (j = 0; j < ms->num_streams; j++) if (num_windows[j] != temp_num_windows[j]) error = TRUE; for (j = 0; j < ms->num_streams; j++) if (use_gv[j] != temp_use_gv[j]) error = TRUE; for (j = 0; j < ms->num_streams; j++) if (HTS_strequal(ms->option[j], temp_option[j]) != TRUE) error = TRUE; free(temp_vector_length); free(temp_is_msd); free(temp_num_windows); free(temp_use_gv); for (j = 0; j < ms->num_streams; j++) if (temp_option[j] != NULL) free(temp_option[j]); free(temp_option); } if (error != FALSE) { HTS_fclose(fp); break; } /* reset POSITION */ temp_duration_pdf = NULL; temp_duration_tree = NULL; temp_stream_win = (char ***) HTS_calloc(ms->num_streams, sizeof(char **)); for (j = 0; j < ms->num_streams; j++) { temp_stream_win[j] = (char **) HTS_calloc(num_windows[j], sizeof(char *)); for (k = 0; k < num_windows[j]; k++) temp_stream_win[j][k] = NULL; } temp_stream_pdf = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0; j < ms->num_streams; j++) temp_stream_pdf[j] = NULL; temp_stream_tree = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0; j < ms->num_streams; j++) temp_stream_tree[j] = NULL; temp_gv_pdf = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0; j < ms->num_streams; j++) temp_gv_pdf[j] = NULL; temp_gv_tree = (char **) HTS_calloc(ms->num_streams, sizeof(char *)); for (j = 0; j < ms->num_streams; j++) temp_gv_tree[j] = NULL; /* load POSITION */ while (1) { if (HTS_get_token_from_fp_with_separator(fp, buff1, '\n') != TRUE) { error = TRUE; break; } if (strcmp(buff1, "[DATA]") == 0) { break; } else if (HTS_match_head_string(buff1, "DURATION_PDF:", &matched_size) == TRUE) { if (temp_duration_pdf != NULL) free(temp_duration_pdf); temp_duration_pdf = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "DURATION_TREE:", &matched_size) == TRUE) { if (temp_duration_tree != NULL) free(temp_duration_tree); temp_duration_tree = HTS_strdup(&buff1[matched_size]); } else if (HTS_match_head_string(buff1, "STREAM_WIN[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) { if (strcmp(stream_type_list[j], buff2) == 0) { for (k = 0; k < num_windows[j]; k++) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ',') == TRUE) temp_stream_win[j][k] = HTS_strdup(buff2); else error = TRUE; } break; } } } } } else if (HTS_match_head_string(buff1, "STREAM_PDF[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) { if (strcmp(stream_type_list[j], buff2) == 0) { if (temp_stream_pdf[j] != NULL) free(temp_stream_pdf[j]); temp_stream_pdf[j] = HTS_strdup(&buff1[matched_size]); break; } } } } } else if (HTS_match_head_string(buff1, "STREAM_TREE[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) { if (strcmp(stream_type_list[j], buff2) == 0) { if (temp_stream_tree[j] != NULL) free(temp_stream_tree[j]); temp_stream_tree[j] = HTS_strdup(&buff1[matched_size]); break; } } } } } else if (HTS_match_head_string(buff1, "GV_PDF[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) { if (strcmp(stream_type_list[j], buff2) == 0) { if (temp_gv_pdf[j] != NULL) free(temp_gv_pdf[j]); temp_gv_pdf[j] = HTS_strdup(&buff1[matched_size]); break; } } } } } else if (HTS_match_head_string(buff1, "GV_TREE[", &matched_size) == TRUE) { if (HTS_get_token_from_string_with_separator(buff1, &matched_size, buff2, ']') == TRUE) { if (buff1[matched_size++] == ':') { for (j = 0; j < ms->num_streams; j++) { if (strcmp(stream_type_list[j], buff2) == 0) { if (temp_gv_tree[j] != NULL) free(temp_gv_tree[j]); temp_gv_tree[j] = HTS_strdup(&buff1[matched_size]); break; } } } } } else { HTS_error(0, "HTS_ModelSet_load: Unknown option %s.\n", buff1); } } /* check POSITION */ if (temp_duration_pdf == NULL) error = TRUE; for (j = 0; j < ms->num_streams; j++) for (k = 0; k < num_windows[j]; k++) if (temp_stream_win[j][k] == NULL) error = TRUE; for (j = 0; j < ms->num_streams; j++) if (temp_stream_pdf[j] == NULL) error = TRUE; /* prepare memory */ if (i == 0) { ms->duration = (HTS_Model *) HTS_calloc(num_voices, sizeof(HTS_Model)); for (j = 0; j < num_voices; j++) HTS_Model_initialize(&ms->duration[j]); ms->window = (HTS_Window *) HTS_calloc(ms->num_streams, sizeof(HTS_Window)); for (j = 0; j < ms->num_streams; j++) HTS_Window_initialize(&ms->window[j]); ms->stream = (HTS_Model **) HTS_calloc(num_voices, sizeof(HTS_Model *)); for (j = 0; j < num_voices; j++) { ms->stream[j] = (HTS_Model *) HTS_calloc(ms->num_streams, sizeof(HTS_Model)); for (k = 0; k < ms->num_streams; k++) HTS_Model_initialize(&ms->stream[j][k]); } ms->gv = (HTS_Model **) HTS_calloc(num_voices, sizeof(HTS_Model *)); for (j = 0; j < num_voices; j++) { ms->gv[j] = (HTS_Model *) HTS_calloc(ms->num_streams, sizeof(HTS_Model)); for (k = 0; k < ms->num_streams; k++) HTS_Model_initialize(&ms->gv[j][k]); } } start_of_data = HTS_ftell(fp); /* load duration */ pdf_fp = NULL; tree_fp = NULL; matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_duration_pdf, &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_duration_pdf[matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); pdf_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_duration_tree, &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_duration_tree[matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); tree_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } if (HTS_Model_load(&ms->duration[i], pdf_fp, tree_fp, ms->num_states, 1, FALSE) != TRUE) error = TRUE; HTS_fclose(pdf_fp); HTS_fclose(tree_fp); /* load windows */ for (j = 0; j < ms->num_streams; j++) { win_fp = (HTS_File **) HTS_calloc(num_windows[j], sizeof(HTS_File *)); for (k = 0; k < num_windows[j]; k++) win_fp[k] = NULL; for (k = 0; k < num_windows[j]; k++) { matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_stream_win[j][k], &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_stream_win[j][k][matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); win_fp[k] = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } } if (HTS_Window_load(&ms->window[j], win_fp, num_windows[j]) != TRUE) error = TRUE; for (k = 0; k < num_windows[j]; k++) HTS_fclose(win_fp[k]); free(win_fp); } /* load streams */ for (j = 0; j < ms->num_streams; j++) { pdf_fp = NULL; tree_fp = NULL; matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_stream_pdf[j], &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_stream_pdf[j][matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); pdf_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_stream_tree[j], &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_stream_tree[j][matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); tree_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } if (HTS_Model_load(&ms->stream[i][j], pdf_fp, tree_fp, vector_length[j], num_windows[j], is_msd[j]) != TRUE) error = TRUE; HTS_fclose(pdf_fp); HTS_fclose(tree_fp); } /* load GVs */ for (j = 0; j < ms->num_streams; j++) { pdf_fp = NULL; tree_fp = NULL; matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_gv_pdf[j], &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_gv_pdf[j][matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); pdf_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } matched_size = 0; if (HTS_get_token_from_string_with_separator(temp_gv_tree[j], &matched_size, buff2, '-') == TRUE) { s = (size_t) atoi(buff2); e = (size_t) atoi(&temp_gv_tree[j][matched_size]); HTS_fseek(fp, (long) s, SEEK_CUR); tree_fp = HTS_fopen_from_fp(fp, e - s + 1); HTS_fseek(fp, start_of_data, SEEK_SET); } if (use_gv[j] == TRUE) { if (HTS_Model_load(&ms->gv[i][j], pdf_fp, tree_fp, vector_length[j], 1, FALSE) != TRUE) error = TRUE; } HTS_fclose(pdf_fp); HTS_fclose(tree_fp); } /* free */ if (temp_duration_pdf != NULL) free(temp_duration_pdf); if (temp_duration_tree != NULL) free(temp_duration_tree); for (j = 0; j < ms->num_streams; j++) { for (k = 0; k < num_windows[j]; k++) if (temp_stream_win[j][k] != NULL) free(temp_stream_win[j][k]); free(temp_stream_win[j]); } free(temp_stream_win); for (j = 0; j < ms->num_streams; j++) if (temp_stream_pdf[j] != NULL) free(temp_stream_pdf[j]); free(temp_stream_pdf); for (j = 0; j < ms->num_streams; j++) if (temp_stream_tree[j] != NULL) free(temp_stream_tree[j]); free(temp_stream_tree); for (j = 0; j < ms->num_streams; j++) if (temp_gv_pdf[j] != NULL) free(temp_gv_pdf[j]); free(temp_gv_pdf); for (j = 0; j < ms->num_streams; j++) if (temp_gv_tree[j] != NULL) free(temp_gv_tree[j]); free(temp_gv_tree); /* fclose */ HTS_fclose(fp); if (error != FALSE) break; } if (gv_off_context != NULL) { sprintf(buff1, "GV-Off { %s }", gv_off_context); gv_off_context_fp = HTS_fopen_from_data((void *) buff1, strlen(buff1) + 1); ms->gv_off_context = (HTS_Question *) HTS_calloc(1, sizeof(HTS_Question)); HTS_Question_initialize(ms->gv_off_context); HTS_Question_load(ms->gv_off_context, gv_off_context_fp); HTS_fclose(gv_off_context_fp); free(gv_off_context); } if (stream_type_list != NULL) { for (i = 0; i < ms->num_streams; i++) if (stream_type_list[i] != NULL) free(stream_type_list[i]); free(stream_type_list); } if (vector_length != NULL) free(vector_length); if (is_msd != NULL) free(is_msd); if (num_windows != NULL) free(num_windows); if (use_gv != NULL) free(use_gv); return !error; } /* HTS_ModelSet_get_sampling_frequency: get sampling frequency of HTS voices */ size_t HTS_ModelSet_get_sampling_frequency(HTS_ModelSet * ms) { return ms->sampling_frequency; } /* HTS_ModelSet_get_fperiod: get frame period of HTS voices */ size_t HTS_ModelSet_get_fperiod(HTS_ModelSet * ms) { return ms->frame_period; } /* HTS_ModelSet_get_fperiod: get stream option */ const char *HTS_ModelSet_get_option(HTS_ModelSet * ms, size_t stream_index) { return ms->option[stream_index]; } /* HTS_ModelSet_get_gv_flag: get GV flag */ HTS_Boolean HTS_ModelSet_get_gv_flag(HTS_ModelSet * ms, const char *string) { if (ms->gv_off_context == NULL) return TRUE; else if (HTS_Question_match(ms->gv_off_context, string) == TRUE) return FALSE; else return TRUE; } /* HTS_ModelSet_get_nstate: get number of state */ size_t HTS_ModelSet_get_nstate(HTS_ModelSet * ms) { return ms->num_states; } /* HTS_Engine_get_fullcontext_label_format: get full-context label format */ const char *HTS_ModelSet_get_fullcontext_label_format(HTS_ModelSet * ms) { return ms->fullcontext_format; } /* HTS_Engine_get_fullcontext_label_version: get full-context label version */ const char *HTS_ModelSet_get_fullcontext_label_version(HTS_ModelSet * ms) { return ms->fullcontext_version; } /* HTS_ModelSet_get_nstream: get number of stream */ size_t HTS_ModelSet_get_nstream(HTS_ModelSet * ms) { return ms->num_streams; } /* HTS_ModelSet_get_nvoices: get number of stream */ size_t HTS_ModelSet_get_nvoices(HTS_ModelSet * ms) { return ms->num_voices; } /* HTS_ModelSet_get_vector_length: get vector length */ size_t HTS_ModelSet_get_vector_length(HTS_ModelSet * ms, size_t stream_index) { return ms->stream[0][stream_index].vector_length; } /* HTS_ModelSet_is_msd: get MSD flag */ HTS_Boolean HTS_ModelSet_is_msd(HTS_ModelSet * ms, size_t stream_index) { return ms->stream[0][stream_index].is_msd; } /* HTS_ModelSet_get_window_size: get dynamic window size */ size_t HTS_ModelSet_get_window_size(HTS_ModelSet * ms, size_t stream_index) { return ms->window[stream_index].size; } /* HTS_ModelSet_get_window_left_width: get left width of dynamic window */ int HTS_ModelSet_get_window_left_width(HTS_ModelSet * ms, size_t stream_index, size_t window_index) { return ms->window[stream_index].l_width[window_index]; } /* HTS_ModelSet_get_window_right_width: get right width of dynamic window */ int HTS_ModelSet_get_window_right_width(HTS_ModelSet * ms, size_t stream_index, size_t window_index) { return ms->window[stream_index].r_width[window_index]; } /* HTS_ModelSet_get_window_coefficient: get coefficient of dynamic window */ double HTS_ModelSet_get_window_coefficient(HTS_ModelSet * ms, size_t stream_index, size_t window_index, size_t coefficient_index) { return ms->window[stream_index].coefficient[window_index][coefficient_index]; } /* HTS_ModelSet_get_window_max_width: get max width of dynamic window */ size_t HTS_ModelSet_get_window_max_width(HTS_ModelSet * ms, size_t stream_index) { return ms->window[stream_index].max_width; } /* HTS_ModelSet_use_gv: get GV flag */ HTS_Boolean HTS_ModelSet_use_gv(HTS_ModelSet * ms, size_t stream_index) { if (ms->gv[0][stream_index].vector_length != 0) return TRUE; else return FALSE; } /* HTS_Model_add_parameter: get parameter using interpolation weight */ static void HTS_Model_add_parameter(HTS_Model * model, size_t state_index, const char *string, double *mean, double *vari, double *msd, double weight) { size_t i; size_t tree_index, pdf_index; size_t len = model->vector_length * model->num_windows; HTS_Model_get_index(model, state_index, string, &tree_index, &pdf_index); for (i = 0; i < len; i++) { mean[i] += weight * model->pdf[tree_index][pdf_index][i]; vari[i] += weight * model->pdf[tree_index][pdf_index][i + len]; } if (msd != NULL && model->is_msd == TRUE) *msd += weight * model->pdf[tree_index][pdf_index][len + len]; } /* HTS_ModelSet_get_duration_index: get duration PDF & tree index */ void HTS_ModelSet_get_duration_index(HTS_ModelSet * ms, size_t voice_index, const char *string, size_t * tree_index, size_t * pdf_index) { HTS_Model_get_index(&ms->duration[voice_index], 2, string, tree_index, pdf_index); } /* HTS_ModelSet_get_duration: get duration using interpolation weight */ void HTS_ModelSet_get_duration(HTS_ModelSet * ms, const char *string, const double *iw, double *mean, double *vari) { size_t i; size_t len = ms->num_states; for (i = 0; i < len; i++) { mean[i] = 0.0; vari[i] = 0.0; } for (i = 0; i < ms->num_voices; i++) if (iw[i] != 0.0) HTS_Model_add_parameter(&ms->duration[i], 2, string, mean, vari, NULL, iw[i]); } /* HTS_ModelSet_get_parameter_index: get paramter PDF & tree index */ void HTS_ModelSet_get_parameter_index(HTS_ModelSet * ms, size_t voice_index, size_t stream_index, size_t state_index, const char *string, size_t * tree_index, size_t * pdf_index) { HTS_Model_get_index(&ms->stream[voice_index][stream_index], state_index, string, tree_index, pdf_index); } /* HTS_ModelSet_get_parameter: get parameter using interpolation weight */ void HTS_ModelSet_get_parameter(HTS_ModelSet * ms, size_t stream_index, size_t state_index, const char *string, const double *iw, double *mean, double *vari, double *msd) { size_t i; size_t len = ms->stream[0][stream_index].vector_length * ms->stream[0][stream_index].num_windows; for (i = 0; i < len; i++) { mean[i] = 0.0; vari[i] = 0.0; } if (msd != NULL) *msd = 0.0; for (i = 0; i < ms->num_voices; i++) if (iw[i] != 0.0) HTS_Model_add_parameter(&ms->stream[i][stream_index], state_index, string, mean, vari, msd, iw[i]); } /* HTS_ModelSet_get_gv_index: get gv PDF & tree index */ void HTS_ModelSet_get_gv_index(HTS_ModelSet * ms, size_t voice_index, size_t stream_index, const char *string, size_t * tree_index, size_t * pdf_index) { HTS_Model_get_index(&ms->gv[voice_index][stream_index], 2, string, tree_index, pdf_index); } /* HTS_ModelSet_get_gv: get GV using interpolation weight */ void HTS_ModelSet_get_gv(HTS_ModelSet * ms, size_t stream_index, const char *string, const double *iw, double *mean, double *vari) { size_t i; size_t len = ms->stream[0][stream_index].vector_length; for (i = 0; i < len; i++) { mean[i] = 0.0; vari[i] = 0.0; } for (i = 0; i < ms->num_voices; i++) if (iw[i] != 0.0) HTS_Model_add_parameter(&ms->gv[i][stream_index], 2, string, mean, vari, NULL, iw[i]); } HTS_MODEL_C_END; #endif /* !HTS_MODEL_C */
34.27791
178
0.566853
[ "vector", "model" ]
a149a09f7b43844b30b7f0155cf094c3f34adc4b
19,318
h
C
stira/common/common/MathUtils.h
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2016-03-23T08:12:33.000Z
2022-01-25T14:07:03.000Z
stira/common/common/MathUtils.h
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
null
null
null
stira/common/common/MathUtils.h
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2015-06-29T12:00:06.000Z
2019-09-03T12:40:47.000Z
/*********************************************************************************** * Copyright (C) 2008 by Filip Rooms * * * * Terms and conditions for using this software in any form are provided in the * * file COPYING, which can be found in the root directory of this project. * * * * Contact data: filip.rooms@gmail.com * * http://www.filiprooms.be/ * * * ***********************************************************************************/ #ifndef STIRA_COMMON_MATHUTILS_H #define STIRA_COMMON_MATHUTILS_H #include <stdint.h> #include <complex> #include <vector> #include "Point.h" namespace stira { namespace common { /** \brief A class with some handy mathematical functions. * <OL><LI> SWITCH TWO VALUES * <LI> ORDER / COMPARE STUFF / CLIP RANGE / CHECK IF IS RANGE * <LI> COMBINE / SPLIT BITS * <LI> STUFF RELATED TO ANGLES * <LI> SOLVE LINEAR / QUADRATIC EQUATIONS * <LI> COMPUTE MATHEMATICAL FUNCTION VALUE * <LI> COMPUTE VALUES OF GAUSSIAN FUNCTION / DERIVATIVES * <LI> COMPUTE STATISTICS * </OL> */ class MathUtils{ public: /** \brief Constructor.*/ MathUtils(); /** \brief Destructor. */ ~MathUtils(); // 1. SWITCH TWO VALUES /////////////////////// /** \brief switches the values for the variables a and b * \param a the first value; gets the value of b after switch * \param b the second value; gets the value of a after switch*/ static void SwitchValues(double& a, double& b); /** \brief switches the values for the variables a and b * \param a the first value; gets the value of b after switch * \param b the second value; gets the value of a after switch*/ static void SwitchValues(int& a, int& b); // 2. ORDER / COMPARE STUFF / CLIP RANGE / CHECK IF IS RANGE //////////////////////////////////////////////////////////// /** \brief returns the smallest of both input values * \param value1 first input value * \param value2 second input value*/ static double GetMin(double value1, double value2); /** \brief returns the largest of both input values * \param value1 first input value * \param value2 second input value*/ static double GetMax(double value1, double value2); /** \brief compare method for two doubles, as needed by qsort * \param a first number to compare * \param b second number to compare * \return -1 if the first number is the smallest, 1 if it is bigger and 0 if both numbers are equal*/ static int CompareDoubles(const void *a, const void *b); /** \brief compare method for two floats, as needed by qsort * \param a first number to compare * \param b second number to compare * \return -1 if the first number is the smallest, 1 if it is bigger and 0 if both numbers are equal*/ static int CompareFloats(const void *a, const void *b); /** \brief compare method for two doubles, as needed by qsort * \param a first number to compare * \param b second number to compare * \return -1 if the first number is the smallest, 1 if it is bigger and 0 if both numbers are equal*/ static int CompareIntegers(const void *a, const void *b); /** \brief Clips value to be in the range [min, max] * if the user by accident switches the maximum and minimum values, this method corrects this * \param min the minimum value allowed value after clipping * \param value the value to be clipped * \param max the maximum value allowed after clipping*/ static int ClipValue( int value, int min=0, int max=255 ); /** \brief Clips value to be in the range [min, max] * if the user by accident switches the maximum and minimum values, this method corrects this * \param min the minimum value allowed value after clipping * \param value the value to be clipped * \param max the maximum value allowed after clipping*/ static double ClipValue(double value, double min=0.0 , double max=255.0); /** \brief Checks if a value is between a lower and an upper value * \param testValue the value to be checked * \param underLimit the lower limit for the value * \param upperLimit the upper limit for the value */ static bool IsBetween(double testValue, double underLimit, double upperLimit); /** \brief applies modulo to number * While number is larger than number, subtract modulo; While number is smaller than 0, add modulo * \param input input number * \param modulo modulo*/ static double ApplyModulo( double input, double modulo ); // 3. COMBINE / SPLIT BITS ///////////////////////////// /** \brief prints to stdout the bits in a 32bit unsigned integer * \param i input unigned integer */ static void PrintBitsInInt(unsigned int i); /** \brief prints to stdout the bits in an unsigned char * \param c input unigned char */ static void PrintBitsInChar(unsigned char c); /** \brief combine 4 unsigned in one 32 bit unsigned integer * [ 1 1 1 1 1 1 1 1 ] [ 1 1 1 1 1 1 1 1 ] [ 1 1 1 1 1 1 1 1 ] [ 1 1 1 1 1 1 1 1 ] * unsigned char c0 unsigned char c1 unsigned char c2 unsigned char c3 * * \param c0 first input unsigned char, will be placed at the most significant bits of the integer * \param c1 second input unsigned char, will be placed at the next 8 less significant bits of the integer * \param c2 third input unsigned char, will be placed at the next 8 less significant bits of the integer * \param c3 fourth input unsigned char, will be placed at the least significant bits of the integer */ static unsigned int CombineCharsInInt(unsigned char i0, unsigned char i1, unsigned char i2, unsigned char i3); /** \brief splits a 32bit unsigned integer in a vector of 4 unsigned chars * \param value input unsigned integer */ static std::vector<unsigned char> SplitIntInChars( int value ); // 4. STUFF RELATED TO ANGLES ///////////////////////////// /** \brief computes the angle of the line from the origin to the point (x,y) * \param x x coordinate * \param y y coordinate */ static double ComputeArgument(double x, double y); /** \brief converts degrees to radians * \param degrees value in degrees to convert to radians*/ static double ToRadians( double degrees ); /** \brief converts radians to degrees * \param radians value in radians to convert to degrees*/ static double ToDegrees( double radians ); // 5. SOLVE LINEAR / QUADRATIC EQUATIONS //////////////////////////////////////// /** \brief solves a linear equation ax + b = 0 * \param a slope coefficient * \param b offset * \param solution the solution of the equation * \return false if there is no solution (a==0); true otherwise*/ static bool SolveLinearEquation (double a, double b, double& solution); /** \brief solves a quadratic equation a * x * x + b * x + c = 0 (real-valued case) * \param a quadratic coefficient * \param b linear coefficient * \param c constant * \param outSolution1 the first solution of the equation * \param outSolution2 the second solution of the equation * \return true if solutions are real-valued; false otherwise*/ bool SolveQuadraticEquation( double a, double b, double c, double& outSolution1, double& outSolution2); /** \brief solves a quadratic equation a * x * x + b * x + c = 0 (complex-valued case) * \param a quadratic coefficient * \param b linear coefficient * \param c constant * \param outSolution1 the first solution of the equation * \param outSolution2 the second solution of the equation * \return true if solutions are real-valued; false otherwise*/ static bool SolveQuadraticEquation ( std::complex<double> a, std::complex<double> b, std::complex<double> c, std::complex<double>& outSolution1, std::complex<double>& outSolution2); // 6. COMPUTE MATHEMATICAL FUNCTION VALUE ///////////////////////////////////////// /** \brief Computes y value according to linear interpolation */ static double LinearInterpolate( double x0, double y0, double x1, double y1, double x ); /** \brief Computes PSNR (Peak Signal to Noise Ratio) given the MSE (Mean Square Error) * Ref: http://en.wikipedia.org/wiki/PSNR * \param MSE the MSE (Mean Square Error) * \param peakValue maximum possible value of the data range */ static double ComputePSNR( double MSE, double peakValue=255.0 ); /** \brief applies gamma correction to input value * Data is for gamma correction first normalized between 0 and 1 * \param inValue incoming value * \param gamma value of gamma * \param rangeMin minimum of data range of incoming value * \param rangeMax maximum of data range of incoming value*/ static double GammaCorrect( double inValue, double gamma, double rangeMin=0.0, double rangeMax=255.0); /** \brief computes steerable interpolation coefficient for angle theta * Suppose B_theta(x,y) = k1(theta) * B1(x,y)) + k2(theta) * B2(x,y)) + k3(theta) * B1(x,y), * with B_theta the interpolated band, ki(theta) the interpolation coefficients (i=1,2,3) * and Bi(x,y) the basis bands (i=1,2,3). * then this function computes ki(theta) * This formulation is a generalization of the expression of Freeman and Adelson by Bart Goossens * for an arbitrary number of orientations * \param i the number of the band with which the interpolation coefficient corresponds (see above) * \param K the total number of oriented bands (in our example above, K=3) * \param theta the angle under which to interpolate*/ static double GetSteerableInterPolationCoefficient(int i, int K, double theta); /** \brief help function to have an exact factorial in case the input number is a casted integer * \param inputNumber number of which to compute the factorial*/ static double Factorial(const double& inputNumber); /** \brief computes myNumber to the power myExponent, to prevent all that messy casting that pow() otherwise requires * \param myNumber the number to be raised to the power myExponent * \param myExponent the exponent to be used*/ static int ComputeIntegerPower(int myNumber, int myExponent); // 7. COMPUTE VALUES OF GAUSSIAN FUNCTION / DERIVATIVES /////////////////////////////////////////////////////// /** \brief computes a set of points sampled regularly from the Gauss function (NOT random variables with Gaussian distribution!!) * \param sigma sigma of the function */ static std::vector<double> GenerateGaussianSamples( double sigma ); /** \brief computes a set of Gaussian sample points * The Gaussian has the peak at gaussCenterX, unity sample distance and half width 2 times sigma * \param gaussCenterX x coordinate cooresponding with the center (i.e., the peak) * \param sigma sigma of the gaussian profile * \param scaleAmplitude flag whether or not the values are rescaled so the peak has a predefined value * \param amplitude predefined value for the peak */ static std::vector< Point<double> > GenerateGaussianPoints( int gaussCenterX, double sigma, bool scaleAmplitude=false, double amplitude=1 ); /** \brief computes a set of Gaussian sample points * It uses the x coordinates of inPoints to compute the function value with the peak at gaussCenterX * \param gaussCenterX x coordinate cooresponding with the center (i.e., the peak) * \param sigma sigma of the gaussian profile * \param scaleAmplitude flag whether or not the values are rescaled so the peak has a predefined value * \param amplitude predefined value for the peak */ static std::vector< Point<double> > GenerateGaussianPoints( std::vector< Point<double> > inPoints, int gaussCenterX, double sigma, bool scaleAmplitude, double amplitude ); /** \brief computes for a value x the value G(x) with G the Gaussian function (as used in probabilities) * Reference: http://mathworld.wolfram.com/GaussianFunction.html * G(x) = 1/sqrt(2*sigma*pi) * exp( (x - mu) / 2 sigma^2 ) * \param x value for which to compute the function value * \param mu mu of the function (related to the position of the peak of the function ) * \param sigma sigma of the function (related to the width)*/ static double Gaussian( double x, double mu, double sigma ); /** \brief computes for a point (x,y) the value G(x,y) with G the 2D Gaussian function (as used in probabilities) * Reference: http://mathworld.wolfram.com/GaussianFunction.html * G(x) = 1/(2*pi*sigmaX*sigmaY) * exp( (x - muX) / (2 sigmaX^2) + (y - muY) / (2 sigmaY^2) ) * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double Gaussian( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); /** \brief computes for a value x the value G'(x) with G' the first derivative of the Gaussian function * \param x value for which to compute the function value * \param mu mu of the function * \param sigma sigma of the function */ static double GaussianFirstDerivativeX1D( double x, double mu, double sigma ); /** \brief computes for a value x the value G''(x) with G'' the second derivative of the Gaussian function * \param x value for which to compute the function value * \param mu mu of the function * \param sigma sigma of the function*/ static double GaussianSecondDerivateX1D( double x, double mu, double sigma ); /** \brief computes for a point (x,y) the value of the first derivative to x of the 2D Gaussian function * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double GaussianDx( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); /** \brief computes for a point (x,y) the value of the first derivative to y of the 2D Gaussian function * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double GaussianDy( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); /** \brief computes for a point (x,y) the value of the second derivative to x of the 2D Gaussian function * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double GaussianSecondDerivateX1D( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); /** \brief computes for a point (x,y) the value of the second derivative to y of the 2D Gaussian function * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double GaussianD2y( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); /** \brief computes for a point (x,y) the value of the mixed first derivatives to x and y of the 2D Gaussian function * \param x x coordinate of point for which to compute the function value * \param y y coordinate of point for which to compute the function value * \param muX muX of the function (related to the x coordinate of the position of the peak of the function ) * \param muY muY of the function (related to the y coordinate of the position of the peak of the function ) * \param sigmaX sigmaX of the function (related to the width in the x-direction) * \param sigmaY sigmaY of the function (related to the width in the y-direction)*/ static double GaussianDxDy( double x, double y, double muX, double muY, double sigmaX, double sigmaY ); // 8. COMPUTE STATISTICS //////////////////////// /** \brief Computes cross-correlation between two signals x and y * Reference: code + explanation: http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/correlate/ * general: http://en.wikipedia.org/wiki/Cross-correlation * \param x array of values of first function * \param y array of values of second function * \param nrSamples number of elements in x and y * \param maxDelay maximum delay to compute cross-correlation for * \return array of (2*maxDelay) cross-correlation values */ static double* ComputeCrossCorrelation( double* x, double* y, int nrSamples, int maxDelay ); /** \brief normalizes all elements of the vector passed as argument, overwriting the original values * \param inVector vector to normalize */ static void NormalizeVector( std::vector<double>& inVector ); }; } } #endif
55.511494
174
0.670515
[ "vector" ]
a14a39d62dd5184d13c33199239a60f48cc817b0
2,732
h
C
WasatchVCPPLib/WasatchVCPPLib/ParseData.h
WasatchPhotonics/WasatchVCPP
a1ce59d4a1eb659c52ea3b6233cdefd674bc24f3
[ "MIT" ]
null
null
null
WasatchVCPPLib/WasatchVCPPLib/ParseData.h
WasatchPhotonics/WasatchVCPP
a1ce59d4a1eb659c52ea3b6233cdefd674bc24f3
[ "MIT" ]
null
null
null
WasatchVCPPLib/WasatchVCPPLib/ParseData.h
WasatchPhotonics/WasatchVCPP
a1ce59d4a1eb659c52ea3b6233cdefd674bc24f3
[ "MIT" ]
1
2022-01-01T01:51:40.000Z
2022-01-01T01:51:40.000Z
/** @file ParseData.h @author Mark Zieg <mzieg@wasatchphotonics.com> @brief interface of WasatchVCPP::ParseData @note customers normally wouldn't access this file; use WasatchVCPP.h instead */ #pragma once #include <cstdint> #include <string> #include <vector> namespace WasatchVCPP { //! Internal class providing methods for reading and writing individual fields //! within the EEPROM. //! //! It is used by EEPROM.parse() and EEPROM.write() (generally with non-zero values //! for index). However, this class is also used to demarsharl little-endian gettors //! from WasatchVCPP::Spectrometer. //! //! @note all serialized data is presumed little-endian unless specified otherwise class ParseData { public: static bool toBool (const std::vector<uint8_t>& buf, int index = 0); static uint8_t toUInt8 (const std::vector<uint8_t>& buf, int index = 0); static int16_t toInt16 (const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static uint16_t toUInt16(const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static uint32_t toUInt24(const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static int32_t toInt32 (const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static uint32_t toUInt32(const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static uint64_t toUInt40(const std::vector<uint8_t>& buf, int index = 0, bool bigEndian = false); static float toFloat (const std::vector<uint8_t>& buf, int index = 0); static std::string toString(const std::vector<uint8_t>& buf, int index = 0, int len = 0); static bool writeBool (bool value, std::vector<uint8_t>& buf, int index); static bool writeUInt8 (uint8_t value, std::vector<uint8_t>& buf, int index); static bool writeUInt16 (uint16_t value, std::vector<uint8_t>& buf, int index); static bool writeInt16 (int16_t value, std::vector<uint8_t>& buf, int index); static bool writeUInt32 (uint32_t value, std::vector<uint8_t>& buf, int index); static bool writeInt32 (int32_t value, std::vector<uint8_t>& buf, int index); static bool writeFloat (float value, std::vector<uint8_t>& buf, int index); static bool writeString (const std::string& value, std::vector<uint8_t>& buf, int index, int maxLen); }; }
55.755102
114
0.614568
[ "vector" ]
a14aac0a4483fa26c54270c656305fb458d2c3c0
1,971
h
C
include/treelite/compiler.h
ziyu-guo/treelite
5909c99a14387f84bc6ac1e6e697f969d39a1e92
[ "Apache-2.0" ]
1
2020-12-28T06:19:45.000Z
2020-12-28T06:19:45.000Z
include/treelite/compiler.h
ziyu-guo/treelite
5909c99a14387f84bc6ac1e6e697f969d39a1e92
[ "Apache-2.0" ]
1
2022-02-04T20:14:45.000Z
2022-02-04T20:14:45.000Z
include/treelite/compiler.h
hcho3/treelite
d73bed79a7fff7cc870881f59ebc45b13798d6fb
[ "Apache-2.0" ]
null
null
null
/*! * Copyright 2017 by Contributors * \file compiler.h * \brief Interface of compiler that compiles a tree ensemble model * \author Philip Cho */ #ifndef TREELITE_COMPILER_H_ #define TREELITE_COMPILER_H_ #include <dmlc/registry.h> #include <treelite/common.h> #include <functional> #include <memory> #include <string> namespace treelite { struct Model; // forward declaration namespace compiler { struct CompilerParam; // forward declaration struct CompiledModel { std::string backend; std::unordered_map<std::string, std::string> files; std::string file_prefix; }; } // namespace compiler /*! \brief interface of compiler */ class Compiler { public: /*! \brief virtual destructor */ virtual ~Compiler() = default; /*! * \brief convert tree ensemble model * \return compiled model */ virtual compiler::CompiledModel Compile(const Model& model) = 0; /*! * \brief create a compiler from given name * \param name name of compiler * \return The created compiler */ static Compiler* Create(const std::string& name, const compiler::CompilerParam& param); }; /*! * \brief Registry entry for compiler */ struct CompilerReg : public dmlc::FunctionRegEntryBase<CompilerReg, std::function<Compiler* (const compiler::CompilerParam&)> > { }; /*! * \brief Macro to register compiler. * * \code * // example of registering the simple compiler * TREELITE_REGISTER_COMPILER(SimpleCompiler, "simple") * .describe("Bare-bones simple compiler") * .set_body([]() { * return new SimpleCompiler(); * }); * \endcode */ #define TREELITE_REGISTER_COMPILER(UniqueId, Name) \ static DMLC_ATTRIBUTE_UNUSED ::treelite::CompilerReg & \ __make_ ## CompilerReg ## _ ## UniqueId ## __ = \ ::dmlc::Registry< ::treelite::CompilerReg>::Get()->__REGISTER__(Name) } // namespace treelite #endif // TREELITE_COMPILER_H_
24.949367
79
0.669203
[ "model" ]
a150e8494c1bc0a583185a00aa7089eb5ce486f4
1,057
h
C
Code/CoreData/RKObjectPropertyInspector+CoreData.h
SinnerSchraderMobileMirrors/RestKit
076382103698254dab7db832f350a21d3301e45c
[ "Apache-2.0" ]
2
2015-04-18T09:10:49.000Z
2016-05-30T08:08:14.000Z
Code/CoreData/RKObjectPropertyInspector+CoreData.h
grgcombs/RestKit
1a4b7c216db3e12a51cfa49ac83e2105e97879ac
[ "Apache-2.0" ]
null
null
null
Code/CoreData/RKObjectPropertyInspector+CoreData.h
grgcombs/RestKit
1a4b7c216db3e12a51cfa49ac83e2105e97879ac
[ "Apache-2.0" ]
null
null
null
// // RKObjectPropertyInspector+CoreData.h // RestKit // // Created by Blake Watters on 8/14/11. // Copyright 2011 RestKit // // 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. // #import "../ObjectMapping/RKObjectPropertyInspector.h" @interface RKObjectPropertyInspector (CoreData) - (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity; /** Returns the Class type of the specified property on the object class */ - (Class)typeForProperty:(NSString*)propertyName ofEntity:(NSEntityDescription*)entity; @end
32.030303
87
0.74929
[ "object" ]
a155d1c695903fa1db4f694eac930a2e2bb6790e
4,981
h
C
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/gpu_utils/ocl_compiler.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
1
2020-04-20T04:33:11.000Z
2020-04-20T04:33:11.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/gpu_utils/ocl_compiler.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
8
2019-07-10T15:18:21.000Z
2019-07-31T13:38:09.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/gpu_utils/ocl_compiler.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
3
2019-07-10T10:50:25.000Z
2020-12-08T13:42:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2012,2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \libinternal \file * \brief Declare infrastructure for OpenCL JIT compilation * * \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com> * \author Anca Hamuraru <anca@streamcomputing.eu> * \author Teemu Virolainen <teemu@streamcomputing.eu> * \author Mark Abraham <mark.j.abraham@gmail.com> * \inlibraryapi */ #ifndef GMX_GPU_UTILS_OCL_COMPILER_H #define GMX_GPU_UTILS_OCL_COMPILER_H #include <string> #include "gromacs/gpu_utils/oclutils.h" namespace gmx { namespace ocl { /*! \brief Get the device-specific warp size * * This is platform implementation dependent and seems to only work on the Nvidia and AMD platforms! * Nvidia reports 32, AMD for GPU 64. Intel seems to report 16, but that is not correct, * as it execution width can be between 8-32 and it's picked per-kernel at compile-time. * Therefore, for Intel it should actually be queried separately for each kernel (Redmine #2520). * * \param context Current OpenCL context * \param deviceId OpenCL device with the context * \return cl_int value of the warp size * * \throws InternalError if an OpenCL error was encountered */ size_t getDeviceWarpSize(cl_context context, cl_device_id deviceId); /*! \brief Get the kernel-specific warp size * * \param kernel THe OpenCL kernel object * \param deviceId OpenCL device for which the kernel warp size is queried * \return cl_int value of the warp size * * \throws InternalError if an OpenCL error was encountered */ size_t getKernelWarpSize(cl_kernel kernel, cl_device_id deviceId); /*! \brief Compile the specified kernel for the context and device. * * \param[out] fplog Open file pointer for log output * \param[in] kernelRelativePath Relative path to the kernel in the source tree, * e.g. "src/gromacs/mdlib/nbnxn_ocl" for NB kernels. * \param[in] kernelBaseFilename The name of the kernel source file to compile, e.g. "nbnxn_ocl_kernels.cl" * \param[in] extraDefines Preprocessor defines required by the calling code, e.g. for configuring the kernels * \param[in] context OpenCL context on the device to compile for * \param[in] deviceId OpenCL device id of the device to compile for * \param[in] deviceVendorId Enumerator of the device vendor to compile for * * \returns The compiled OpenCL program * * \todo Consider whether we can parallelize the compilation of all * the kernels by compiling them in separate programs - but since the * resulting programs can't refer to each other, that might lead to * bloat of util code? * * \throws std::bad_alloc if out of memory. * FileIOError if a file I/O error prevents returning a valid compiled program. * InternalError if an OpenCL API error prevents returning a valid compiled program. */ cl_program compileProgram(FILE *fplog, const std::string &kernelRelativePath, const std::string &kernelBaseFilename, const std::string &extraDefines, cl_context context, cl_device_id deviceId, ocl_vendor_id_t deviceVendorId); } // namespace ocl } // namespace gmx #endif
42.939655
120
0.717125
[ "object" ]
a1574b13d5106ad839a9db89f7dcf70e00d57e1b
7,806
h
C
dlib/threads/threads_kernel_1.h
ckproc/dlib-19.7
0ca40f5e85de2436e557bee9a805d3987d2d9507
[ "BSL-1.0" ]
null
null
null
dlib/threads/threads_kernel_1.h
ckproc/dlib-19.7
0ca40f5e85de2436e557bee9a805d3987d2d9507
[ "BSL-1.0" ]
null
null
null
dlib/threads/threads_kernel_1.h
ckproc/dlib-19.7
0ca40f5e85de2436e557bee9a805d3987d2d9507
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2003 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_THREADS_KERNEl_1_ #define DLIB_THREADS_KERNEl_1_ #ifdef DLIB_ISO_CPP_ONLY #error "DLIB_ISO_CPP_ONLY is defined so you can't use this OS dependent code. Turn DLIB_ISO_CPP_ONLY off if you want to use it." #endif #include "threads_kernel_abstract.h" #include "../windows_magic.h" #include <windows.h> #include "../algs.h" namespace dlib { // ---------------------------------------------------------------------------------------- typedef DWORD thread_id_type; inline thread_id_type get_thread_id ( ) { return GetCurrentThreadId(); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // mutex object // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // forward declaration of signaler class signaler; class mutex { public: mutex ( ) { InitializeCriticalSection(&cs); } ~mutex ( ) { DeleteCriticalSection(&cs); } void lock ( ) const { EnterCriticalSection(&cs); } void unlock ( ) const { LeaveCriticalSection(&cs); } private: mutable CRITICAL_SECTION cs; // restricted functions mutex(mutex&); // copy constructor mutex& operator=(mutex&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // signaler object // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class signaler { public: signaler ( const mutex& associated_mutex ) : hSemaphore(CreateSemaphore (NULL, 0, 100000000, NULL)), waiters(0), hCountSema(CreateSemaphore (NULL,0,100000000,NULL)), m(associated_mutex) { if (hSemaphore == NULL || hCountSema == NULL) { if (hSemaphore != NULL) { CloseHandle(hSemaphore); } if (hCountSema != NULL) { CloseHandle(hCountSema); } throw dlib::thread_error(ECREATE_SIGNALER, "in function signaler::signaler() an error occurred making the signaler" ); } } ~signaler ( ) { CloseHandle(hSemaphore); CloseHandle(hCountSema);} void wait ( ) const { // get a lock on the mutex for the waiters variable waiters_mutex.lock(); // mark that one more thread will be waiting on this signaler ++waiters; // release the mutex for waiters waiters_mutex.unlock(); // release the associated mutex m.unlock(); // wait for the semaphore to be signaled WaitForSingleObject (hSemaphore,INFINITE); // signal that we are awake ReleaseSemaphore(hCountSema,(LONG)1,NULL); // relock the associated mutex m.lock(); } bool wait_or_timeout ( unsigned long milliseconds ) const { // get a lock on the mutex for the waiters variable waiters_mutex.lock(); // mark that one more thread will be waiting on this signaler ++waiters; // release the mutex for waiters waiters_mutex.unlock(); // release the associated mutex m.unlock(); bool value; // wait for the semaphore to be signaled if ( WaitForSingleObject (hSemaphore, milliseconds ) == WAIT_TIMEOUT ) { // in this case we should decrement waiters because we are returning // due to a timeout rather than because someone called signal() or // broadcast(). value = false; // signal that we are awake ReleaseSemaphore(hCountSema,(LONG)1,NULL); // get a lock on the mutex for the waiters variable waiters_mutex.lock(); // mark that one less thread will be waiting on this signaler. if (waiters != 0) --waiters; // release the mutex for waiters waiters_mutex.unlock(); } else { value = true; // signal that we are awake ReleaseSemaphore(hCountSema,(LONG)1,NULL); } // relock the associated mutex m.lock(); return value; } void signal ( ) const { // get a lock on the mutex for the waiters variable waiters_mutex.lock(); if (waiters > 0) { --waiters; // make the semaphore release one waiting thread ReleaseSemaphore(hSemaphore,1,NULL); // wait for signaled thread to wake up WaitForSingleObject(hCountSema,INFINITE); } // release the mutex for waiters waiters_mutex.unlock(); } void broadcast ( ) const { // get a lock on the mutex for the waiters variable waiters_mutex.lock(); if (waiters > 0) { // make the semaphore release all the waiting threads ReleaseSemaphore(hSemaphore,(LONG)waiters,NULL); // wait for count to be zero for (unsigned long i = 0; i < waiters; ++i) { WaitForSingleObject(hCountSema,INFINITE); } waiters = 0; } // release the mutex for waiters waiters_mutex.unlock(); } const mutex& get_mutex ( ) const { return m; } private: mutable HANDLE hSemaphore; mutable unsigned long waiters; mutex waiters_mutex; mutable HANDLE hCountSema; const mutex& m; // restricted functions signaler(signaler&); // copy constructor signaler& operator=(signaler&); // assignment operator }; // ---------------------------------------------------------------------------------------- namespace threads_kernel_shared_helpers { bool spawn_thread ( void (*funct)(void*), void* param ); /*! is identical to create_new_thread() but just doesn't use any thread pooling. !*/ } // ---------------------------------------------------------------------------------------- } #include "threads_kernel_shared.h" #ifdef NO_MAKEFILE #include "threads_kernel_1.cpp" #endif #endif // DLIB_THREADS_KERNEl_1_
29.126866
130
0.431719
[ "object" ]
a1581f3d457fd168d05bf94c344d1e9f6386ffee
17,926
c
C
apps/logisticregression/lr.opencl.c
tcarneirop/chapel-gpu
7073702708d72b3f16447f1465ed68c92927907c
[ "Apache-2.0" ]
1
2021-02-18T16:51:34.000Z
2021-02-18T16:51:34.000Z
apps/logisticregression/lr.opencl.c
tcarneirop/chapel-gpu
7073702708d72b3f16447f1465ed68c92927907c
[ "Apache-2.0" ]
null
null
null
apps/logisticregression/lr.opencl.c
tcarneirop/chapel-gpu
7073702708d72b3f16447f1465ed68c92927907c
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <assert.h> #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif #define VERBOSE #define MAX_SOURCE_SIZE (0x100000) const char *getErrorString(cl_int error) { switch(error){ // run-time and JIT compiler errors case 0: return "CL_SUCCESS"; case -1: return "CL_DEVICE_NOT_FOUND"; case -2: return "CL_DEVICE_NOT_AVAILABLE"; case -3: return "CL_COMPILER_NOT_AVAILABLE"; case -4: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case -5: return "CL_OUT_OF_RESOURCES"; case -6: return "CL_OUT_OF_HOST_MEMORY"; case -7: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case -8: return "CL_MEM_COPY_OVERLAP"; case -9: return "CL_IMAGE_FORMAT_MISMATCH"; case -10: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case -11: return "CL_BUILD_PROGRAM_FAILURE"; case -12: return "CL_MAP_FAILURE"; case -13: return "CL_MISALIGNED_SUB_BUFFER_OFFSET"; case -14: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST"; case -15: return "CL_COMPILE_PROGRAM_FAILURE"; case -16: return "CL_LINKER_NOT_AVAILABLE"; case -17: return "CL_LINK_PROGRAM_FAILURE"; case -18: return "CL_DEVICE_PARTITION_FAILED"; case -19: return "CL_KERNEL_ARG_INFO_NOT_AVAILABLE"; // compile-time errors case -30: return "CL_INVALID_VALUE"; case -31: return "CL_INVALID_DEVICE_TYPE"; case -32: return "CL_INVALID_PLATFORM"; case -33: return "CL_INVALID_DEVICE"; case -34: return "CL_INVALID_CONTEXT"; case -35: return "CL_INVALID_QUEUE_PROPERTIES"; case -36: return "CL_INVALID_COMMAND_QUEUE"; case -37: return "CL_INVALID_HOST_PTR"; case -38: return "CL_INVALID_MEM_OBJECT"; case -39: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case -40: return "CL_INVALID_IMAGE_SIZE"; case -41: return "CL_INVALID_SAMPLER"; case -42: return "CL_INVALID_BINARY"; case -43: return "CL_INVALID_BUILD_OPTIONS"; case -44: return "CL_INVALID_PROGRAM"; case -45: return "CL_INVALID_PROGRAM_EXECUTABLE"; case -46: return "CL_INVALID_KERNEL_NAME"; case -47: return "CL_INVALID_KERNEL_DEFINITION"; case -48: return "CL_INVALID_KERNEL"; case -49: return "CL_INVALID_ARG_INDEX"; case -50: return "CL_INVALID_ARG_VALUE"; case -51: return "CL_INVALID_ARG_SIZE"; case -52: return "CL_INVALID_KERNEL_ARGS"; case -53: return "CL_INVALID_WORK_DIMENSION"; case -54: return "CL_INVALID_WORK_GROUP_SIZE"; case -55: return "CL_INVALID_WORK_ITEM_SIZE"; case -56: return "CL_INVALID_GLOBAL_OFFSET"; case -57: return "CL_INVALID_EVENT_WAIT_LIST"; case -58: return "CL_INVALID_EVENT"; case -59: return "CL_INVALID_OPERATION"; case -60: return "CL_INVALID_GL_OBJECT"; case -61: return "CL_INVALID_BUFFER_SIZE"; case -62: return "CL_INVALID_MIP_LEVEL"; case -63: return "CL_INVALID_GLOBAL_WORK_SIZE"; case -64: return "CL_INVALID_PROPERTY"; case -65: return "CL_INVALID_IMAGE_DESCRIPTOR"; case -66: return "CL_INVALID_COMPILER_OPTIONS"; case -67: return "CL_INVALID_LINKER_OPTIONS"; case -68: return "CL_INVALID_DEVICE_PARTITION_COUNT"; // extension errors case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR"; case -1001: return "CL_PLATFORM_NOT_FOUND_KHR"; case -1002: return "CL_INVALID_D3D10_DEVICE_KHR"; case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR"; case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR"; case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR"; default: return "Unknown OpenCL error"; } } #ifdef __cplusplus extern "C" { #endif void lrCUDA1(float* W, float *Wcurr, int start, int end, int GPUN) { if (GPUN > 0) { assert(end - start + 1 == GPUN); #ifdef VERBOSE printf("In vcOCL\n"); printf("\t GPUN: %d\n", GPUN); printf("\t range: %d..%d\n", start, end); #endif FILE *fp; char *source_str; size_t source_size; char str[1024]; fp = fopen("lr.cl", "r"); if (!fp) { fprintf(stderr, "Failed to load kernel.\n"); exit(1); } source_str = (char*)malloc(MAX_SOURCE_SIZE); source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp); fclose( fp ); //printf("source: %s\n", source_str); // Get platform and device information cl_platform_id platform_id = NULL; cl_device_id device_ids[2]; cl_uint ret_num_devices; cl_uint ret_num_platforms; cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms); if (ret != CL_SUCCESS) { printf("clGetPlatformIDs %s\n", getErrorString(ret)); } ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 2, device_ids, &ret_num_devices); //printf("device ID: %d, # of devices: %d\n", ret, ret_num_devices); int did = 0; char *env = getenv("OCL_DEVICE_NO"); if (env) { did = atoi(env); } cl_device_id device_id = device_ids[did]; clGetDeviceInfo(device_id, CL_DEVICE_NAME, sizeof(str), str, &ret); printf("GPU %s\n", str); // Create an OpenCL context cl_context context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create a command queue cl_command_queue command_queue = clCreateCommandQueue(context, device_id, CL_QUEUE_PROFILING_ENABLE, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create memory buffers on the device for each vector cl_mem w_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY, GPUN * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_mem wcurr_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, GPUN * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_event h2d_event; ret = clEnqueueWriteBuffer(command_queue, w_mem_obj, CL_TRUE, 0, GPUN * sizeof(float), W + start, 0, NULL, &h2d_event); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } else { clWaitForEvents(1, &h2d_event); } // Create a program from the kernel source cl_program program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Build the program ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create the OpenCL kernel cl_kernel kernel = clCreateKernel(program, "lr1", &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Set the arguments of the kernel ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&wcurr_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&w_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&GPUN); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Execute the OpenCL kernel on the list size_t local_item_size = 64; // Divide work items into groups of 64 size_t global_item_size = local_item_size * ((GPUN + local_item_size -1) / local_item_size); // Process the entire lists cl_event k_event; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, &k_event); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } else { clWaitForEvents(1, &k_event); } cl_event d2h_event; ret = clEnqueueReadBuffer(command_queue, wcurr_mem_obj, CL_TRUE, 0, GPUN * sizeof(float), Wcurr + start, 0, NULL, &d2h_event); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clFinish(command_queue); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_ulong time_start; cl_ulong time_end; // H2D clGetEventProfilingInfo(h2d_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(h2d_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("H2D time: %lf seconds \n", (time_end-time_start) / 1000000000.0); // Kernel clGetEventProfilingInfo(k_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(k_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("Kernel time: %lf seconds \n", (time_end-time_start) / 1000000000.0); // D2H clGetEventProfilingInfo(d2h_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(d2h_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("D2H time: %lf seconds \n", (time_end-time_start) / 1000000000.0); } } void lrCUDA2(float* X, float *Y, float *W, float *Wcurr, float alpha, int nSamples, int nFeatures, int start, int end, int GPUN) { if (GPUN > 0) { assert(end - start + 1 == GPUN); #ifdef VERBOSE printf("In vcOCL\n"); printf("\t GPUN: %d\n", GPUN); printf("\t range: %d..%d\n", start, end); alpha = 0.1; #endif FILE *fp; char *source_str; size_t source_size; char str[1024]; fp = fopen("lr.cl", "r"); if (!fp) { fprintf(stderr, "Failed to load kernel.\n"); exit(1); } source_str = (char*)malloc(MAX_SOURCE_SIZE); source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp); fclose( fp ); //printf("source: %s\n", source_str); // Get platform and device information cl_platform_id platform_id = NULL; cl_device_id device_ids[2]; cl_uint ret_num_devices; cl_uint ret_num_platforms; cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms); if (ret != CL_SUCCESS) { printf("clGetPlatformIDs %s\n", getErrorString(ret)); } ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 2, device_ids, &ret_num_devices); //printf("device ID: %d, # of devices: %d\n", ret, ret_num_devices); int did = 0; char *env = getenv("OCL_DEVICE_NO"); if (env) { did = atoi(env); } cl_device_id device_id = device_ids[did]; clGetDeviceInfo(device_id, CL_DEVICE_NAME, sizeof(str), str, &ret); printf("GPU %s\n", str); // Create an OpenCL context cl_context context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create a command queue cl_command_queue command_queue = clCreateCommandQueue(context, device_id, CL_QUEUE_PROFILING_ENABLE, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create memory buffers on the device for each vector cl_mem x_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, nSamples * nFeatures * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_mem y_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, nSamples * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_mem wcurr_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, nFeatures * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_mem w_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY, GPUN * sizeof(float), NULL, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_event h2d_event[3]; ret = clEnqueueWriteBuffer(command_queue, x_mem_obj, CL_TRUE, 0, nSamples * nFeatures * sizeof(float), X, 0, NULL, &h2d_event[0]); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clEnqueueWriteBuffer(command_queue, y_mem_obj, CL_TRUE, 0, nSamples * sizeof(float), Y, 0, NULL, &h2d_event[1]); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clEnqueueWriteBuffer(command_queue, wcurr_mem_obj, CL_TRUE, 0, nFeatures * sizeof(float), Wcurr, 0, NULL, &h2d_event[2]); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } clWaitForEvents(3, h2d_event); // Create a program from the kernel source cl_program program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Build the program ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Create the OpenCL kernel cl_kernel kernel = clCreateKernel(program, "lr2", &ret); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Set the arguments of the kernel ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&w_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&wcurr_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&x_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *)&y_mem_obj); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 4, sizeof(cl_float), (void *)&alpha); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 5, sizeof(cl_int), (void *)&nSamples); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 6, sizeof(cl_int), (void *)&nFeatures); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clSetKernelArg(kernel, 7, sizeof(cl_int), (void *)&GPUN); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } // Execute the OpenCL kernel on the list size_t local_item_size = 64; // Divide work items into groups of 64 size_t global_item_size = local_item_size * ((GPUN + local_item_size -1) / local_item_size); // Process the entire lists cl_event k_event; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, &k_event); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } else { clWaitForEvents(1, &k_event); } cl_event d2h_event; ret = clEnqueueReadBuffer(command_queue, w_mem_obj, CL_TRUE, 0, GPUN * sizeof(float), W + start, 0, NULL, &d2h_event); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } ret = clFinish(command_queue); if (ret != CL_SUCCESS) { printf("%s\n", getErrorString(ret)); } cl_ulong time_start; cl_ulong time_end; // H2D clGetEventProfilingInfo(h2d_event[0], CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(h2d_event[0], CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("H2D1 time: %lf seconds \n", (time_end-time_start) / 1000000000.0); clGetEventProfilingInfo(h2d_event[1], CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(h2d_event[1], CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("H2D2 time: %lf seconds \n", (time_end-time_start) / 1000000000.0); clGetEventProfilingInfo(h2d_event[2], CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(h2d_event[2], CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("H2D3 time: %lf seconds \n", (time_end-time_start) / 1000000000.0); // Kernel clGetEventProfilingInfo(k_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(k_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("Kernel time: %lf seconds \n", (time_end-time_start) / 1000000000.0); // D2H clGetEventProfilingInfo(d2h_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(d2h_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); printf("D2H time: %lf seconds \n", (time_end-time_start) / 1000000000.0); } } #ifdef __cplusplus } #endif
39.747228
138
0.624512
[ "vector" ]
a15bb8b2e160044fe13bf9b44168c43c3715720a
2,148
h
C
export/windows/cpp/obj/include/flixel/ui/_FlxButton/FlxButtonEvent.h
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/include/flixel/ui/_FlxButton/FlxButtonEvent.h
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/include/flixel/ui/_FlxButton/FlxButtonEvent.h
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
// Generated by Haxe 3.3.0 #ifndef INCLUDED_flixel_ui__FlxButton_FlxButtonEvent #define INCLUDED_flixel_ui__FlxButton_FlxButtonEvent #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DECLARE_CLASS1(flixel,FlxBasic) HX_DECLARE_CLASS2(flixel,_hx_system,FlxSound) HX_DECLARE_CLASS3(flixel,ui,_FlxButton,FlxButtonEvent) HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable) namespace flixel{ namespace ui{ namespace _FlxButton{ class HXCPP_CLASS_ATTRIBUTES FlxButtonEvent_obj : public hx::Object { public: typedef hx::Object super; typedef FlxButtonEvent_obj OBJ_; FlxButtonEvent_obj(); public: void __construct( ::Dynamic Callback, ::flixel::_hx_system::FlxSound sound); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="flixel.ui._FlxButton.FlxButtonEvent") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,true,"flixel.ui._FlxButton.FlxButtonEvent"); } static hx::ObjectPtr< FlxButtonEvent_obj > __new( ::Dynamic Callback, ::flixel::_hx_system::FlxSound sound); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~FlxButtonEvent_obj(); HX_DO_RTTI_ALL; hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp); hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); void *_hx_getInterface(int inHash); ::String __ToString() const { return HX_HCSTRING("FlxButtonEvent","\x96","\x41","\xf7","\x21"); } ::Dynamic callback; ::Dynamic &callback_dyn() { return callback;} ::flixel::_hx_system::FlxSound sound; void destroy(); ::Dynamic destroy_dyn(); void fire(); ::Dynamic fire_dyn(); }; } // end namespace flixel } // end namespace ui } // end namespace _FlxButton #endif /* INCLUDED_flixel_ui__FlxButton_FlxButtonEvent */
32.545455
122
0.763966
[ "object" ]
a15c54974fd1139be3ac253f5deb9341bca5c4cf
10,982
h
C
plugins/jml/jml/stump_accum.h
kstepanmpmg/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
665
2015-12-09T17:00:14.000Z
2022-03-25T07:46:46.000Z
plugins/jml/jml/stump_accum.h
tomzhang/mldb
a09cf2d9ca454d1966b9e49ae69f2fe6bf571494
[ "Apache-2.0" ]
797
2015-12-09T19:48:19.000Z
2022-03-07T02:19:47.000Z
plugins/jml/jml/stump_accum.h
matebestek/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
103
2015-12-25T04:39:29.000Z
2022-02-03T02:55:22.000Z
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /* stump_accum.h -*- C++ -*- Jeremy Barnes, 28 April 2004 Copyright (c) 2004 Jeremy Barnes. All rights reserved. $Source$ The stump_accum object. Internal to the stump, but split off here to allow the testing programs to work. */ #include "mldb/arch/threads.h" namespace ML { namespace { /* Sort stumps by their Z values. */ struct Sort_Z { bool operator () (const Stump & s1, const Stump & s2) const { return s1.Z > s2.Z; } }; } // file scope struct No_Locks { typedef int Lock; typedef int Guard; }; typedef Lock Lock_; typedef Guard Guard_; struct Locked { typedef Lock_ Lock; typedef Guard_ Guard; }; /*****************************************************************************/ /* STUMP_ACCUM */ /*****************************************************************************/ /* An internal class to the stumps. This is passed to the stump training core to accumulate the results into. It keeps track of which is the best stump. */ template<class W, class Z, class C, class Tracer = No_Trace, class Locks = No_Locks> struct Stump_Accum { Stump_Accum(const Feature_Space & fs, bool fair, int num_results = 0, const C & c = C(), const Tracer & tracer = Tracer()) : calc_c(c), z_best(Z::worst), z_needed(Z::worst), fair(fair), num_results(num_results), fs(fs), tracer(tracer) { next_check = num_results * 2; } Z calc_z; C calc_c; typedef typename Locks::Lock Lock; typedef typename Locks::Guard Guard; Lock lock; /* Holds an entry that we are accumulating. */ struct Entry { Entry(const W & w, float arg, float z, const Feature & feature) : w(w), arg(arg), z(z), feature(feature) { //if (!isfinite(z)) // throw Exception("Attempt to put non-finite Z " // + ostream_format(z) + " into accum"); } W w; float arg; float z; Feature feature; bool operator < (const Entry & other) const { return z < other.z; } }; float z_best; float z_needed; int next_check; std::vector<Entry> best; bool fair; int num_results; const Feature_Space & fs; Tracer tracer; /** Method that gets called when we start a new feature. We use it to pre-cache part of the work from the Z calculation, as we are assured that the MISSING buckets of W will never change after this method is called. Return value is used to allow an early exit from the training process, due to it being impossible for this feature to have a high enough value to be included. */ bool start(const Feature & feature, const W & w, double & missing) { bool optional = fs.info(feature).optional(); missing = calc_z.missing(w, optional); bool keep_going = num_results > 1 || calc_z.can_beat(w, missing, z_best); //cerr << "start: missing = " << missing << " z_best = " // << z_best << " keep_going = " << keep_going << endl; //cerr << "non-missing = " << calc_z.non_missing(w, missing) // << endl; return keep_going; } void cleanup_best() { Guard MLDB_UNUSED guard(lock); //cerr << "cleanup_best: best.size() = " << best.size() // << " num_results = " << num_results << endl; //cerr << "fair = " << fair << endl; //for (unsigned i = 0; i < best.size(); ++i) // cerr << " " << best[i].z; //cerr << endl; #if 0 for (unsigned i = 0; i < best.size(); ++i) { if (!finite(best[i].z)) throw Exception("non-finite Z value"); } #endif if (fair) std::sort(best.begin(), best.end()); else { size_t num_to_get = std::min<size_t>(num_results, best.size()); std::partial_sort(best.begin(), best.begin() + num_to_get, best.end()); } //cerr << "finished sort." << endl; if (num_results > best.size()) return; // not enough yet... typename std::vector<Entry>::iterator it = best.begin() + num_results; if (fair) { --it; // get the last included one z_needed = it->z; while (it != best.end() && z_equal(it->z, z_needed)) ++it; } //cerr << "before erase" << endl; best.erase(it, best.end()); //cerr << "finished erase" << endl; } /** Method that gets called when we have found a potential split point. */ float add(const Feature & feature, const W & w, float arg, float z) { Guard MLDB_UNUSED guard(lock); if (tracer) tracer("stump accum", 3) << " accum: feature " << feature << " arg " << arg << " z " << z << " " << fs.print(feature) << std::endl; //if (tracer) // tracer("stump accum", 4) // << " accum: w = " << endl << w.print() << endl; if ((fair && z_equal(z, z_best)) || num_results > 1 || best.empty()) { /* Check if we can short circuit it. This happens when the z is lower than the lowest necessary value. */ if (!z_equal(z, z_needed) && z_needed < z) return z; // Another split with the same Z value best.push_back(Entry(w, arg, z, feature)); z_best = std::min(z, z_best); if (num_results > 1 && best.size() == next_check) { /* Time to clean up the list, to stop it getting too long. */ cleanup_best(); next_check = std::min(std::max(512, num_results * 2), next_check * 2); } } else if (z < z_best) { // A better one. This replaces whatever we had accumulated so // far. z_best = z; best[0].w = w; best[0].arg = arg; best[0].z = z; best[0].feature = feature; if (fair) { // Erase the rest of the ones with the old (inferior) Z value best.erase(best.begin() + 1, best.end()); } } return z; } /** Method that gets called when we have found a potential split point. */ float add(const Feature & feature, const W & w, float arg, double missing) { float z = calc_z.non_missing(w, missing); return add(feature, w, arg, z); } /** Method that gets called when we have found a potential split point. */ float add_presence(const Feature & feature, const W & w, float arg, double missing) { float z = calc_z.non_missing_presence(w, missing); return add(feature, w, arg, z); } void finish(const Feature & feature) { // nothing to do here, at the moment } /* Extract a list of stumps from the results. */ std::vector<Stump> results(const Training_Data & data, const Feature & predicted) { Guard MLDB_UNUSED guard(lock); cleanup_best(); unsigned nx = data.example_count(); unsigned nc = data.label_count(predicted); float epsilon = 1.0 / (nx * nc); std::vector<Stump> result; for (unsigned i = 0; i < best.size(); ++i) { std::vector<distribution<float> > c = calc_c(best[i].w, epsilon, fs.info(best[i].feature).optional()); Stump added(predicted, best[i].feature, best[i].arg, c[true], c[false], c[MISSING], calc_c.update_alg(), data.feature_space(), best[i].z); result.push_back(added); //cerr << "added " << added.print() << endl; } return result; } }; /*****************************************************************************/ /* BIAS_ACCUM */ /*****************************************************************************/ /* Class that accumulates to keep track of the bias. */ template<class W, class Z, class C, class Tracer = No_Trace> struct Bias_Accum { Bias_Accum(const Feature_Space & fs, int nl, const C & c = C(), const Tracer & tracer = Tracer()) : calc_c(c), saved_w(nl), fs(fs), tracer(tracer) { } Z calc_z; C calc_c; double z; W saved_w; const Feature_Space & fs; Tracer tracer; /** Method that gets called when we start a new feature. We use it to pre-cache part of the work from the Z calculation, as we are assured that the MISSING buckets of W will never change after this method is called. Return value is used to allow an early exit from the training process, due to it being impossible for this feature to have a high enough value to be included. */ bool start(const Feature & feature, const W & w, double & missing) { saved_w = w; missing = calc_z.missing(w, false); bool keep_going = true; return keep_going; } /** Method that gets called when we have found a potential split point. */ float add(const Feature & feature, const W & w, float arg, double missing) { return z = calc_z.non_missing(w, missing); } /** Method that gets called when we have found a potential split point. */ float add_presence(const Feature & feature, const W & w, float arg, double missing) { return z = calc_z.non_missing_presence(w, missing); } void finish(const Feature & feature) { // nothing to do here, at the moment } /* Extract a list of stumps from the results. */ Stump result(const Training_Data & data, const Feature & predicted) { unsigned nx = data.example_count(); unsigned nc = data.label_count(predicted); float epsilon = 1.0 / (nx * nc); std::vector<distribution<float> > c = calc_c(saved_w, epsilon, false); //cerr << "c[true] = " << c[true] << endl; //cerr << "c[false] = " << c[false] << endl; //cerr << "c[MISSING] = " << c[MISSING] << endl; //cerr << "bias z = " << z << endl; Stump result(predicted, MISSING_FEATURE, -INFINITY, c[true], c[false], c[MISSING], calc_c.update_alg(), data.feature_space(), 1.0); return result; } }; } // namespace ML
31.739884
79
0.515025
[ "object", "vector" ]
a15f5e82b377be8fdb9bee55f77b56f451a87432
3,524
h
C
src/torelease.h
kfrolov/netcoredbg
84f51b95d0eb4a087ce2a068d4474895e44e3f97
[ "MIT" ]
null
null
null
src/torelease.h
kfrolov/netcoredbg
84f51b95d0eb4a087ce2a068d4474895e44e3f97
[ "MIT" ]
null
null
null
src/torelease.h
kfrolov/netcoredbg
84f51b95d0eb4a087ce2a068d4474895e44e3f97
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Copyright (c) 2017 Samsung Electronics Co., LTD #pragma once #include <assert.h> #include "utils/logger.h" namespace netcoredbg { // This class acts a smart pointer which calls the Release method on any object // you place in it when the ToRelease class falls out of scope. You may use it // just like you would a standard pointer to a COM object (including if (foo), // if (!foo), if (foo == 0), etc) except for two caveats: // 1. This class never calls AddRef and it always calls Release when it // goes out of scope. // 2. You should never use & to try to get a pointer to a pointer unless // you call Release first, or you will leak whatever this object contains // prior to updating its internal pointer. template<class T> class ToRelease { public: ToRelease() : m_ptr(nullptr) {} ToRelease(T* ptr) : m_ptr(ptr) {} ~ToRelease() { Free(); } void operator=(T *ptr) { Free(); m_ptr = ptr; } T* operator->() const { assert(m_ptr != 0); // accessing NULL pointer return m_ptr; } operator T*() const { return m_ptr; } T** operator&() { assert(m_ptr == 0); // make sure, that previously stored value of type `T' isn't lost return &m_ptr; } // Special case for EvalFunction() arguments in order to avoid temporary array pointers creation code. // DO NOT use it, unless you know what you are doing. Operator & must be used instead. T** GetRef() { return &m_ptr; } T* GetPtr() const { return m_ptr; } T* Detach() { T* pT = m_ptr; m_ptr = nullptr; return pT; } void Free() { if (m_ptr != nullptr) { m_ptr->Release(); m_ptr = nullptr; } } ToRelease(ToRelease&& that) noexcept : m_ptr(that.m_ptr) { that.m_ptr = nullptr; } private: ToRelease(const ToRelease& that) = delete; T* m_ptr; }; #ifndef IfFailRet #define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { LOGE("%s : 0x%08x", #EXPR, Status); return (Status); } } while (0) #endif #ifndef _countof #define _countof(x) (sizeof(x)/sizeof(x[0])) #endif #ifdef PAL_STDCPP_COMPAT #define _iswprint PAL_iswprint #define _wcslen PAL_wcslen #define _wcsncmp PAL_wcsncmp #define _wcsrchr PAL_wcsrchr #define _wcscmp PAL_wcscmp #define _wcschr PAL_wcschr #define _wcscspn PAL_wcscspn #define _wcscat PAL_wcscat #define _wcsstr PAL_wcsstr #else // PAL_STDCPP_COMPAT #define _iswprint iswprint #define _wcslen wcslen #define _wcsncmp wcsncmp #define _wcsrchr wcsrchr #define _wcscmp wcscmp #define _wcschr wcschr #define _wcscspn wcscspn #define _wcscat wcscat #define _wcsstr wcsstr #endif // !PAL_STDCPP_COMPAT typedef uintptr_t TADDR; typedef ULONG64 CLRDATA_ADDRESS; // Convert between CLRDATA_ADDRESS and TADDR. #define TO_TADDR(cdaddr) ((TADDR)(cdaddr)) #define TO_CDADDR(taddr) ((CLRDATA_ADDRESS)(LONG_PTR)(taddr)) const int mdNameLen = 2048; #ifdef _MSC_VER #define PACK_BEGIN __pragma( pack(push, 1) ) #define PACK_END __pragma( pack(pop) ) #else #define PACK_BEGIN #define PACK_END __attribute__((packed)) #endif } // namespace netcoredbg
24.136986
133
0.648978
[ "object" ]
a1652bc11d53295454e83f47bc9110c055c5856a
523
h
C
dbms/include/DB/Dictionaries/ExternalResultDescription.h
btmc/ClickHouse
6b5f15ec62a434dc9204194f70c1c68b46533866
[ "Apache-2.0" ]
1
2017-01-17T17:29:05.000Z
2017-01-17T17:29:05.000Z
dbms/include/DB/Dictionaries/ExternalResultDescription.h
btmc/ClickHouse
6b5f15ec62a434dc9204194f70c1c68b46533866
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
dbms/include/DB/Dictionaries/ExternalResultDescription.h
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <DB/Core/Block.h> namespace DB { /** Common part for implementation of MySQLBlockInputStream, MongoDBBlockInputStream and others. */ struct ExternalResultDescription { enum struct ValueType { UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64, String, Date, DateTime }; Block sample_block; std::vector<ValueType> types; std::vector<std::string> names; ConstColumnPlainPtrs sample_columns; void init(const Block & sample_block_); }; }
13.410256
96
0.715105
[ "vector" ]
a24832d4bd02f6ccb233596f441b9e8b498d8ce6
7,207
c
C
src/StyleLexers/styleLexR.c
RaffaeleBianc0/Notepad3
42bf5a948707d3fc38e6de4ffa224c4f4948e21b
[ "BSD-2-Clause" ]
null
null
null
src/StyleLexers/styleLexR.c
RaffaeleBianc0/Notepad3
42bf5a948707d3fc38e6de4ffa224c4f4948e21b
[ "BSD-2-Clause" ]
null
null
null
src/StyleLexers/styleLexR.c
RaffaeleBianc0/Notepad3
42bf5a948707d3fc38e6de4ffa224c4f4948e21b
[ "BSD-2-Clause" ]
null
null
null
#include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_R = { // Language Keywords "if else repeat while function for in next break " "true false NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_", // Base / Default package function "abbreviate abline abs acf acos acosh addmargins aggregate agrep alarm alias alist " "all anova any aov aperm append apply approx approxfun apropos ar args arima array " "arrows asin asinh assign assocplot atan atanh attach attr attributes autoload autoloader ave axis " "backsolve barplot basename beta bindtextdomain binomial biplot bitmap bmp body " "box boxplot bquote break browser builtins bxp by bzfile c call cancor capabilities " "casefold cat category cbind ccf ceiling character charmatch chartr chol choose " "chull citation class close cm cmdscale codes coef coefficients col colnames colors " "colorspaces colours comment complex confint conflicts contour contrasts contributors " "convolve cophenetic coplot cor cos cosh cov covratio cpgram crossprod cummax cummin " "cumprod cumsum curve cut cutree cycle data dataentry date dbeta dbinom dcauchy dchisq de " "debug debugger decompose delay deltat demo dendrapply density deparse deriv det detach " "determinant deviance dexp df dfbeta dfbetas dffits dgamma dgeom dget dhyper diag diff " "diffinv difftime digamma dim dimnames dir dirname dist dlnorm dlogis dmultinom dnbinom " "dnorm dotchart double dpois dput drop dsignrank dt dump dunif duplicated dweibull " "dwilcox eapply ecdf edit effects eigen emacs embed end environment eval evalq " "example exists exp expression factanal factor factorial family fft fifo file filter " "find fitted fivenum fix floor flush for force formals format formula forwardsolve " "fourfoldplot frame frequency ftable function gamma gaussian gc gcinfo gctorture get " "getenv geterrmessage gettext gettextf getwd gl glm globalenv gray grep grey grid gsub " "gzcon gzfile hat hatvalues hcl hclust head heatmap help hist history hsv httpclient " "iconv iconvlist identical identify if ifelse image influence inherits integer integrate " "interaction interactive intersect invisible isoreg jitter jpeg julian kappa kernapply " "kernel kmeans knots kronecker ksmooth labels lag lapply layout lbeta lchoose lcm legend " "length letters levels lfactorial lgamma library licence license line lines list lm load " "loadhistory loadings local locator loess log logb logical loglin lowess ls lsfit machine mad " "mahalanobis makepredictcall manova mapply match matlines matplot matpoints matrix max mean " "median medpolish menu merge message methods mget min missing mode monthplot months " "mosaicplot mtext mvfft names napredict naprint naresid nargs nchar ncol next nextn ngettext " "nlevels nlm nls noquote nrow numeric objects offset open optim optimise optimize options " "order ordered outer pacf page pairlist pairs palette par parse paste pbeta pbinom pbirthday " "pcauchy pchisq pdf pentagamma person persp pexp pf pgamma pgeom phyper pi pico pictex pie " "piechart pipe plclust plnorm plogis plot pmatch pmax pmin pnbinom png pnorm points poisson " "poly polygon polym polyroot postscript power ppoints ppois ppr prcomp predict preplot " "pretty princomp print prmatrix prod profile profiler proj promax prompt provide psigamma " "psignrank pt ptukey punif pweibull pwilcox q qbeta qbinom qbirthday qcauchy qchisq qexp qf " "qgamma qgeom qhyper qlnorm qlogis qnbinom qnorm qpois qqline qqnorm qqplot qr qsignrank qt " "qtukey quantile quarters quasi quasibinomial quasipoisson quit qunif quote qweibull qwilcox " "rainbow range rank raw rbeta rbind rbinom rcauchy rchisq readline real recover rect " "reformulate regexpr relevel remove reorder rep repeat replace replicate replications require " "reshape resid residuals restart return rev rexp rf rgamma rgb rgeom rhyper rle rlnorm rlogis rm " "rmultinom rnbinom rnorm round row rownames rowsum rpois rsignrank rstandard rstudent rt " "rug runif runmed rweibull rwilcox sample sapply save savehistory scale scan screen screeplot sd " "search searchpaths seek segments seq sequence serialize setdiff setequal setwd shell sign " "signif sin single sinh sink smooth solve sort source spectrum spline splinefun split sprintf " "sqrt stack stars start stderr stdin stdout stem step stepfun stl stop stopifnot str strftime " "strheight stripchart strptime strsplit strtrim structure strwidth strwrap sub subset " "substitute substr substring sum summary sunflowerplot supsmu svd sweep switch symbols symnum " "system t table tabulate tail tan tanh tapply tempdir tempfile termplot terms tetragamma " "text time title toeplitz tolower topenv toupper trace traceback transform trigamma trunc " "truncate try ts tsdiag tsp typeof unclass undebug union unique uniroot unix unlink unlist " "unname unserialize unsplit unstack untrace unz update upgrade url var varimax vcov vector " "version vi vignette warning warnings weekdays weights which while window windows " "with write wsbrowser xedit xemacs xfig xinch xor xtabs xyinch yinch zapsmall", // "Other Package Functions "acme aids aircondit amis aml banking barchart barley beaver bigcity boot brambles " "breslow bs bwplot calcium cane capability cav censboot channing city claridge cloth " "cloud coal condense contourplot control corr darwin densityplot dogs dotplot ducks " "empinf envelope environmental ethanol fir frets gpar grav gravity grob hirose histogram " "islay knn larrows levelplot llines logit lpoints lsegments lset ltext lvqinit lvqtest manaus " "melanoma melanoma motor multiedit neuro nitrofen nodal ns nuclear oneway parallel " "paulsen poisons polar qq qqmath remission rfs saddle salinity shingle simplex singer " "somgrid splom stripplot survival tau tmd tsboot tuna unit urine viewport wireframe wool xyplot", // Unused "", // Unused "", // --- "", "", "", "" }; EDITLEXER lexR = { SCLEX_R, IDS_LEX_R_STAT, L"R-S-SPlus Statistics Code", L"R", L"", &KeyWords_R,{ { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_R_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_R_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_R_KWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#0A246A", L"" }, { {SCE_R_BASEKWORD}, IDS_LEX_STR_63271, L"Base Package Functions", L"bold; fore:#7f0000", L"" }, { {SCE_R_OTHERKWORD}, IDS_LEX_STR_63272, L"Other Package Functions", L"bold; fore:#7f007F", L"" }, { {SCE_R_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#0000FF", L"" }, { {MULTI_STYLE(SCE_R_STRING,SCE_R_STRING2,0,0)}, IDS_LEX_STR_63131, L"String", L"italic; fore:#3C6CDD", L"" }, { {SCE_R_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"bold; fore:#B000B0", L"" }, { {SCE_R_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {SCE_R_INFIX}, IDS_LEX_STR_63269, L"Infix", L"fore:#660066", L"" }, { {SCE_R_INFIXEOL}, IDS_LEX_STR_63270, L"Infix EOL", L"fore:#FF4000; back:#E0C0E0; eolfilled", L"" }, EDITLEXER_SENTINEL } };
74.298969
114
0.768142
[ "vector", "transform" ]
a24f965ef40a69decf5f3bd1e4776bd8d1a45892
18,987
c
C
components/hal/esp32s2/usbh_hal.c
hasiflo/esp-idf
1ca2afd982230e4cbf021c58137f3141c1870572
[ "Apache-2.0" ]
1
2021-05-24T07:39:12.000Z
2021-05-24T07:39:12.000Z
components/hal/esp32s2/usbh_hal.c
ziggy1010/esp-idf
639e7ad494d93fc82159f9fe854041bc43a96d5f
[ "Apache-2.0" ]
null
null
null
components/hal/esp32s2/usbh_hal.c
ziggy1010/esp-idf
639e7ad494d93fc82159f9fe854041bc43a96d5f
[ "Apache-2.0" ]
1
2021-05-29T06:35:09.000Z
2021-05-29T06:35:09.000Z
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stddef.h> #include <stdint.h> #include <assert.h> #include <string.h> #include "hal/usbh_hal.h" #include "hal/usbh_ll.h" /* ----------------------------------------------------------------------------- ------------------------------- Macros and Types ------------------------------- ----------------------------------------------------------------------------- */ // -------------------------------- Constants ---------------------------------- #define BENDPOINTADDRESS_NUM_MSK 0x0F //Endpoint number mask of the bEndpointAddress field of an endpoint descriptor #define BENDPOINTADDRESS_DIR_MSK 0x80 //Endpoint direction mask of the bEndpointAddress field of an endpoint descriptor #define CORE_REG_GSNPSID 0x4F54400A #define CORE_REG_GHWCFG1 0x00000000 #define CORE_REG_GHWCFG2 0x224DD930 #define CORE_REG_GHWCFG3 0x00C804B5 #define CORE_REG_GHWCFG4 0xD3F0A030 // ------------------------------ Configurable --------------------------------- #define CHAN_MAX_SLOTS 16 /* FIFO lengths configured as follows: RXFIFO (Receive FIFO) - Recommended: (((LPS/4) + 2) * NUM_PACKETS) + (NUM_CHAN * 2) + (NUM_BULK_CTRL * 1) - Actual: Assume (LPS = 64), (NUM_CHAN = 8), (NUM_BULK_CTRL = 8): NPTXFIFO (Non-periodic TX FIFO) - Recommended: (((LPS/4) + 2) * 2) Fit two largest packet sizes (and each packets overhead info) - Actual: Assume LPS is 64 (is the MPS for CTRL/BULK/INTR in FS) PTXFIFO (Periodic TX FIFO) - Recommended: ((LPS/4) + 2) * NUM_PACKETS - Actual: Assume a single LPS of 64 (quarter of ISO MPS), then 2 packets worth of overhead REGFIFO (Register storage) - Recommended: 4 * NUM_CHAN - Actual: Assume NUM_CHAN is 8 */ #define HW_FIFO_LEN 256 #define RX_FIFO_LEN 92 #define NPTX_FIFO_LEN 36 #define PTX_FIFO_LEN 72 #define REG_FIFO_LEN 32 _Static_assert((RX_FIFO_LEN + NPTX_FIFO_LEN + PTX_FIFO_LEN + REG_FIFO_LEN) <= HW_FIFO_LEN, "Sum of FIFO lengths not equal to HW_FIFO_LEN"); /** * The following core interrupts will be enabled (listed LSB to MSB). Some of these * interrupts are enabled later than others. * - USB_LL_INTR_CORE_PRTINT * - USB_LL_INTR_CORE_HCHINT * - USB_LL_INTR_CORE_DISCONNINT * The following PORT interrupts cannot be masked, listed LSB to MSB * - USBH_LL_INTR_HPRT_PRTCONNDET * - USBH_LL_INTR_HPRT_PRTENCHNG * - USBH_LL_INTR_HPRT_PRTOVRCURRCHNG */ #define CORE_INTRS_EN_MSK (USB_LL_INTR_CORE_DISCONNINT) //Interrupts that pertain to core events #define CORE_EVENTS_INTRS_MSK (USB_LL_INTR_CORE_DISCONNINT | \ USB_LL_INTR_CORE_HCHINT) //Interrupt that pertain to host port events #define PORT_EVENTS_INTRS_MSK (USBH_LL_INTR_HPRT_PRTCONNDET | \ USBH_LL_INTR_HPRT_PRTENCHNG | \ USBH_LL_INTR_HPRT_PRTOVRCURRCHNG) /** * The following channel interrupt bits are currently checked (in order LSB to MSB) * - USBH_LL_INTR_CHAN_XFERCOMPL * - USBH_LL_INTR_CHAN_CHHLTD * - USBH_LL_INTR_CHAN_STALL * - USBH_LL_INTR_CHAN_BBLEER * - USBH_LL_INTR_CHAN_BNAINTR * - USBH_LL_INTR_CHAN_XCS_XACT_ERR * * Note the following points about channel interrupts: * - Not all bits are unmaskable under scatter/gather * - Those bits proxy their interrupt through the USBH_LL_INTR_CHAN_CHHLTD bit * - USBH_LL_INTR_CHAN_XCS_XACT_ERR is always unmasked * - When USBH_LL_INTR_CHAN_BNAINTR occurs, USBH_LL_INTR_CHAN_CHHLTD will NOT. * - USBH_LL_INTR_CHAN_AHBERR doesn't actually ever happen on our system )i.e., ESP32S2 and later): * - If the QTD list's starting address is an invalid address (e.g., NULL), the core will attempt to fetch that * address for a transfer descriptor and probably gets all zeroes. It will interpret the zero as a bad QTD and * return a USBH_LL_INTR_CHAN_BNAINTR instead. * - If the QTD's buffer pointer is an invalid address, the core will attempt to read/write data to/from that * invalid buffer address with NO INDICATION OF ERROR. The transfer will be acknowledged and treated as * successful. Bad buffer pointers MUST BE CHECKED FROM HIGHER LAYERS INSTEAD. */ #define CHAN_INTRS_EN_MSK (USBH_LL_INTR_CHAN_XFERCOMPL | \ USBH_LL_INTR_CHAN_CHHLTD | \ USBH_LL_INTR_CHAN_BNAINTR) #define CHAN_INTRS_ERROR_MSK (USBH_LL_INTR_CHAN_STALL | \ USBH_LL_INTR_CHAN_BBLEER | \ USBH_LL_INTR_CHAN_BNAINTR | \ USBH_LL_INTR_CHAN_XCS_XACT_ERR) /* ----------------------------------------------------------------------------- --------------------------------- Core (Global) -------------------------------- ----------------------------------------------------------------------------- */ // ---------------------------- Private Functions ------------------------------ static void set_defaults(usbh_hal_context_t *hal) { usbh_ll_internal_phy_conf(hal->wrap_dev); //Enable and configure internal PHY //GAHBCFG register usb_ll_en_dma_mode(hal->dev); usb_ll_set_hbstlen(hal->dev, 0); //INCR16 AHB burst length //GUSBCFG register usb_ll_dis_hnp_cap(hal->dev); //Disable HNP usb_ll_dis_srp_cap(hal->dev); //Disable SRP //Enable interruts usb_ll_dis_intrs(hal->dev, 0xFFFFFFFF); //Mask all interrupts first usb_ll_en_intrs(hal->dev, CORE_INTRS_EN_MSK); //Unmask global interrupts usb_ll_intr_read_and_clear(hal->dev); //Clear interrupts usb_ll_en_global_intr(hal->dev); //Enable interrupt signal //Enable host mode usb_ll_set_host_mode(hal->dev); } // ---------------------------- Public Functions ------------------------------- void usbh_hal_init(usbh_hal_context_t *hal) { //Check if a peripheral is alive by reading the core ID registers usbh_dev_t *dev = &USBH; #ifndef NDEBUG uint32_t core_id = usb_ll_get_controller_core_id(dev); assert(core_id == CORE_REG_GSNPSID); #endif //Initialize HAL context memset(hal, 0, sizeof(usbh_hal_context_t)); hal->dev = dev; hal->wrap_dev = &USB_WRAP; set_defaults(hal); } void usbh_hal_deinit(usbh_hal_context_t *hal) { //Disable and clear global interrupt usb_ll_dis_intrs(hal->dev, 0xFFFFFFFF); //Disable all interrupts usb_ll_intr_read_and_clear(hal->dev); //Clear interrupts usb_ll_dis_global_intr(hal->dev); //Disable interrupt signal hal->dev = NULL; hal->wrap_dev = NULL; } void usbh_hal_core_soft_reset(usbh_hal_context_t *hal) { usb_ll_core_soft_reset(hal->dev); while (usb_ll_check_core_soft_reset(hal->dev)) { ; //Wait until core reset is done } while (!usb_ll_check_ahb_idle(hal->dev)) { ; //Wait until AHB Master bus is idle before doing any other operations } //Set the default bits set_defaults(hal); //Clear all the flags and channels hal->flags.val = 0; hal->channels.num_allocd = 0; hal->channels.chan_pend_intrs_msk = 0; memset(hal->channels.hdls, 0, sizeof(usbh_hal_chan_t *) * USBH_HAL_NUM_CHAN); } /* ----------------------------------------------------------------------------- ---------------------------------- Host Port ---------------------------------- ----------------------------------------------------------------------------- */ static inline void debounce_lock_enable(usbh_hal_context_t *hal) { //Disable the hprt (connection) and disconnection interrupts to prevent repeated triggerings usb_ll_dis_intrs(hal->dev, USB_LL_INTR_CORE_PRTINT | USB_LL_INTR_CORE_DISCONNINT); hal->flags.dbnc_lock_enabled = 1; } void usbh_hal_port_enable(usbh_hal_context_t *hal) { usb_priv_speed_t speed = usbh_ll_hprt_get_speed(hal->dev); //Host Configuration usbh_ll_hcfg_set_defaults(hal->dev, speed); //Todo: Set frame list entries and ena per sched //Configure HFIR usbh_ll_hfir_set_defaults(hal->dev, speed); //Config FIFO sizes usb_ll_set_rx_fifo_size(hal->dev, RX_FIFO_LEN); usb_ll_set_nptx_fifo_size(hal->dev, RX_FIFO_LEN, NPTX_FIFO_LEN); usbh_ll_set_ptx_fifo_size(hal->dev, RX_FIFO_LEN + NPTX_FIFO_LEN, PTX_FIFO_LEN); } /* ----------------------------------------------------------------------------- ----------------------------------- Channel ------------------------------------ ------------------------------------------------------------------------------*/ // --------------------------- Channel Allocation ------------------------------ //Allocate a channel bool usbh_hal_chan_alloc(usbh_hal_context_t *hal, usbh_hal_chan_t *chan_obj, void *chan_ctx) { //Attempt to allocate channel if (hal->channels.num_allocd == USBH_HAL_NUM_CHAN) { return false; //Out of free channels } int chan_idx = -1; for (int i = 0; i < USBH_HAL_NUM_CHAN; i++) { if (hal->channels.hdls[i] == NULL) { hal->channels.hdls[i] = chan_obj; chan_idx = i; hal->channels.num_allocd++; break; } } assert(chan_idx != -1); //Initialize channel object memset(chan_obj, 0, sizeof(usbh_hal_chan_t)); chan_obj->flags.chan_idx = chan_idx; chan_obj->regs = usbh_ll_get_chan_regs(hal->dev, chan_idx); chan_obj->chan_ctx = chan_ctx; //Note: EP characteristics configured separately //Clean and unmask the channel's interrupt usbh_ll_chan_intr_read_and_clear(chan_obj->regs); //Clear the interrupt bits for that channel usbh_ll_haintmsk_en_chan_intr(hal->dev, 1 << chan_obj->flags.chan_idx); usbh_ll_chan_set_intr_mask(chan_obj->regs, CHAN_INTRS_EN_MSK); //Unmask interrupts for this channel usbh_ll_chan_set_pid(chan_obj->regs, 0); //Set the initial PID to zero usbh_ll_chan_hctsiz_init(chan_obj->regs); //Set the non changing parts of the HCTSIZ registers (e.g., do_ping and sched info) return true; } //Returns object memory void usbh_hal_chan_free(usbh_hal_context_t *hal, usbh_hal_chan_t *chan_obj) { //Can only free a channel when in the disabled state and descriptor list released assert(!chan_obj->slot.flags.slot_acquired && !chan_obj->flags.active && !chan_obj->flags.error_pending); //Deallocate channel hal->channels.hdls[chan_obj->flags.chan_idx] = NULL; hal->channels.num_allocd--; assert(hal->channels.num_allocd >= 0); } // ---------------------------- Channel Control -------------------------------- void usbh_hal_chan_set_ep_char(usbh_hal_chan_t *chan_obj, usbh_hal_ep_char_t *ep_char) { //Cannot change ep_char whilst channel is still active or in error assert(!chan_obj->flags.active && !chan_obj->flags.error_pending); //Set the endpoint characteristics of the pipe usbh_ll_chan_hcchar_init(chan_obj->regs, ep_char->dev_addr, ep_char->bEndpointAddress & BENDPOINTADDRESS_NUM_MSK, ep_char->mps, ep_char->type, ep_char->bEndpointAddress & BENDPOINTADDRESS_DIR_MSK, ep_char->ls_via_fs_hub); } /* ----------------------------------------------------------------------------- ------------------------------- Transfers Slots -------------------------------- ------------------------------------------------------------------------------*/ void usbh_hal_chan_activate(usbh_hal_chan_t *chan_obj, int num_to_skip) { //Cannot enable a channel that has already been enabled or is pending error handling assert(!chan_obj->flags.active && !chan_obj->flags.error_pending); assert(chan_obj->slot.flags.slot_acquired); //Update the descriptor list index and check if it's within bounds chan_obj->slot.flags.cur_qtd_idx += num_to_skip; assert(chan_obj->slot.flags.cur_qtd_idx < chan_obj->slot.flags.qtd_list_len); chan_obj->flags.active = 1; //Set start address of the QTD list and starting QTD index usbh_ll_chan_set_dma_addr_non_iso(chan_obj->regs, chan_obj->slot.xfer_desc_list, chan_obj->slot.flags.cur_qtd_idx); //Start the channel usbh_ll_chan_start(chan_obj->regs); } bool usbh_hal_chan_slot_request_halt(usbh_hal_chan_t *chan_obj) { //Cannot request halt on a channel that is pending error handling assert(!chan_obj->flags.error_pending); if (usbh_ll_chan_is_active(chan_obj->regs) || chan_obj->flags.active) { usbh_ll_chan_halt(chan_obj->regs); chan_obj->flags.halt_requested = 1; return false; } return true; } /* ----------------------------------------------------------------------------- -------------------------------- Event Handling -------------------------------- ----------------------------------------------------------------------------- */ //When a device on the port is no longer valid (e.g., disconnect, port error). All channels are no longer valid static void chan_all_halt(usbh_hal_context_t *hal) { for (int i = 0; i < USBH_HAL_NUM_CHAN; i++) { if (hal->channels.hdls[i] != NULL) { hal->channels.hdls[i]->flags.active = 0; } } } usbh_hal_port_event_t usbh_hal_decode_intr(usbh_hal_context_t *hal) { uint32_t intrs_core = usb_ll_intr_read_and_clear(hal->dev); //Read and clear core interrupts uint32_t intrs_port = 0; if (intrs_core & USB_LL_INTR_CORE_PRTINT) { //There are host port interrupts. Read and clear those as well. intrs_port = usbh_ll_hprt_intr_read_and_clear(hal->dev); } //Note: Do not change order of checks. Regressing events (e.g. enable -> disabled, connected -> connected) //always take precendance. ENABLED < DISABLED < CONN < DISCONN < OVRCUR usbh_hal_port_event_t event = USBH_HAL_PORT_EVENT_NONE; //Check if this is a core or port event if ((intrs_core & CORE_EVENTS_INTRS_MSK) || (intrs_port & PORT_EVENTS_INTRS_MSK)) { //Do not change the order of the following checks. Some events/interrupts take precedence over others if (intrs_core & USB_LL_INTR_CORE_DISCONNINT) { event = USBH_HAL_PORT_EVENT_DISCONN; debounce_lock_enable(hal); chan_all_halt(hal); //All channels are halted on a disconnect //Mask the port connection and disconnection interrupts to prevent repeated triggering } else if (intrs_port & USBH_LL_INTR_HPRT_PRTOVRCURRCHNG) { //Check if this is an overcurrent or an overcurrent cleared if (usbh_ll_hprt_get_port_overcur(hal->dev)) { event = USBH_HAL_PORT_EVENT_OVRCUR; chan_all_halt(hal); //All channels are halted on an overcurrent } else { event = USBH_HAL_PORT_EVENT_OVRCUR_CLR; } } else if (intrs_port & USBH_LL_INTR_HPRT_PRTENCHNG) { if (usbh_ll_hprt_get_port_en(hal->dev)) { //Host port was enabled event = USBH_HAL_PORT_EVENT_ENABLED; } else { //Host port has been disabled event = USBH_HAL_PORT_EVENT_DISABLED; chan_all_halt(hal); //All channels are halted when the port is disabled } } else if (intrs_port & USBH_LL_INTR_HPRT_PRTCONNDET && !hal->flags.dbnc_lock_enabled) { event = USBH_HAL_PORT_EVENT_CONN; debounce_lock_enable(hal); } } //Port events always take precendance over channel events if (event == USBH_HAL_PORT_EVENT_NONE && (intrs_core & USB_LL_INTR_CORE_HCHINT)) { //One or more channels have pending interrupts. Store the mask of those channels hal->channels.chan_pend_intrs_msk = usbh_ll_get_chan_intrs_msk(hal->dev); event = USBH_HAL_PORT_EVENT_CHAN; } return event; } usbh_hal_chan_t *usbh_hal_get_chan_pending_intr(usbh_hal_context_t *hal) { int chan_num = __builtin_ffs(hal->channels.chan_pend_intrs_msk); if (chan_num) { hal->channels.chan_pend_intrs_msk &= ~(1 << (chan_num - 1)); //Clear the pending bit for that channel return hal->channels.hdls[chan_num - 1]; } else { return NULL; } } usbh_hal_chan_event_t usbh_hal_chan_decode_intr(usbh_hal_chan_t *chan_obj) { uint32_t chan_intrs = usbh_ll_chan_intr_read_and_clear(chan_obj->regs); usbh_hal_chan_event_t chan_event; //Currently, all cases where channel interrupts occur will also halt the channel, except for BNA assert(chan_intrs & (USBH_LL_INTR_CHAN_CHHLTD | USBH_LL_INTR_CHAN_BNAINTR)); chan_obj->flags.active = 0; //Note: Do not change the current checking order of checks. Certain interrupts (e.g., errors) have precedence over others if (chan_intrs & CHAN_INTRS_ERROR_MSK) { //One of the error interrupts has occurred. //Note: Errors are uncommon, so we check against the entire interrupt mask to reduce frequency of entering this call path //Store the error in hal context usbh_hal_chan_error_t error; if (chan_intrs & USBH_LL_INTR_CHAN_STALL) { error = USBH_HAL_CHAN_ERROR_STALL; } else if (chan_intrs & USBH_LL_INTR_CHAN_BBLEER) { error = USBH_HAL_CHAN_ERROR_PKT_BBL; } else if (chan_intrs & USBH_LL_INTR_CHAN_BNAINTR) { error = USBH_HAL_CHAN_ERROR_BNA; } else { //USBH_LL_INTR_CHAN_XCS_XACT_ERR error = USBH_HAL_CHAN_ERROR_XCS_XACT; } //Update flags chan_obj->error = error; chan_obj->flags.error_pending = 1; //Save the error to be handled later chan_event = USBH_HAL_CHAN_EVENT_ERROR; } else if (chan_obj->flags.halt_requested) { //A halt was previously requested and has not been fulfilled chan_obj->flags.halt_requested = 0; chan_event = USBH_HAL_CHAN_EVENT_HALT_REQ; } else if (chan_intrs & USBH_LL_INTR_CHAN_XFERCOMPL) { int cur_qtd_idx = usbh_ll_chan_get_ctd(chan_obj->regs); //Store current qtd index chan_obj->slot.flags.cur_qtd_idx = cur_qtd_idx; if (cur_qtd_idx == 0) { //If the transfer descriptor list has completed, the CTD index should be 0 (wrapped around) chan_event = USBH_HAL_CHAN_EVENT_SLOT_DONE; } else { chan_event = USBH_HAL_CHAN_EVENT_SLOT_HALT; } } else { //Should never reach this point abort(); } return chan_event; }
44.155814
139
0.633381
[ "object" ]
a252cb9a04d4ce7c02033a28c931c8d097106545
4,452
h
C
br-ext-chip-hisilicon/package/hisilicon-osdrv-hi3516ev300/files/include/hi_comm_vgs.h
carnei-ro/openipc-2.1
f624268e27976a6ad642fa3c70c57b7cdcb1b666
[ "MIT" ]
8
2021-08-02T09:55:36.000Z
2022-01-24T09:38:50.000Z
br-ext-chip-hisilicon/package/hisilicon-osdrv-hi3516ev300/files/include/hi_comm_vgs.h
ZigFisher/openipc-2.1
ac6b21949bdc9dcb2aaf96dd69a0641cba7fda3f
[ "MIT" ]
2
2021-07-19T09:28:36.000Z
2021-08-31T07:46:14.000Z
br-ext-chip-hisilicon/package/hisilicon-osdrv-hi3516ev300/files/include/hi_comm_vgs.h
ZigFisher/openipc-2.1
ac6b21949bdc9dcb2aaf96dd69a0641cba7fda3f
[ "MIT" ]
3
2021-03-11T07:53:31.000Z
2021-03-29T05:16:11.000Z
/* * Copyright (C) Hisilicon Technologies Co., Ltd. 2013-2019. All rights reserved. * Description: Common struct definition for VGS * Author: Hisilicon multimedia software group * Create: 2013-07-24 */ #ifndef __HI_COMM_VGS_H__ #define __HI_COMM_VGS_H__ #include "hi_type.h" #include "hi_common.h" #include "hi_errno.h" #include "hi_comm_video.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /* __cplusplus */ /* failure caused by malloc buffer */ #define HI_ERR_VGS_NOBUF HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_NOBUF) #define HI_ERR_VGS_BUF_EMPTY HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_BUF_EMPTY) #define HI_ERR_VGS_NULL_PTR HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_NULL_PTR) #define HI_ERR_VGS_ILLEGAL_PARAM HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_ILLEGAL_PARAM) #define HI_ERR_VGS_BUF_FULL HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_BUF_FULL) #define HI_ERR_VGS_SYS_NOTREADY HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_SYS_NOTREADY) #define HI_ERR_VGS_NOT_SUPPORT HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_NOT_SUPPORT) #define HI_ERR_VGS_NOT_PERMITTED HI_DEF_ERR(HI_ID_VGS, EN_ERR_LEVEL_ERROR, EN_ERR_NOT_PERM) #define VGS_PRIVATE_DATA_LEN 6 typedef HI_S32 VGS_HANDLE; typedef enum hiVGS_COLOR_REVERT_MODE_E { VGS_COLOR_REVERT_NONE = 0, /* Not revert */ VGS_COLOR_REVERT_RGB, /* Revert RGB */ VGS_COLOR_REVERT_ALPHA, /* Revert alpha */ VGS_COLOR_REVERT_BOTH, /* Revert RGB and alpha */ VGS_COLOR_REVERT_BUTT } VGS_COLOR_REVERT_MODE_E; typedef struct hiVGS_OSD_REVERT_S { RECT_S stSrcRect; /* OSD color revert area */ VGS_COLOR_REVERT_MODE_E enColorRevertMode; /* OSD color revert mode */ } VGS_OSD_REVERT_S; typedef struct hiVGS_TASK_ATTR_S { VIDEO_FRAME_INFO_S stImgIn; /* Input picture */ VIDEO_FRAME_INFO_S stImgOut; /* Output picture */ HI_U64 au64PrivateData[4]; /* RW; Private data of task */ HI_U32 reserved; /* RW; Debug information,state of current picture */ } VGS_TASK_ATTR_S; typedef struct hiVGS_DRAW_LINE_S { POINT_S stStartPoint; /* Line start point */ POINT_S stEndPoint; /* Line end point */ HI_U32 u32Thick; /* RW; Width of line */ HI_U32 u32Color; /* RW; Range: [0,0xFFFFFF]; Color of line */ } VGS_DRAW_LINE_S; typedef enum hiVGS_COVER_TYPE_E { COVER_RECT = 0, /* Retangle cover */ COVER_QUAD_RANGLE, /* Quadrangle cover */ COVER_BUTT } VGS_COVER_TYPE_E; typedef struct hiVGS_QUADRANGLE_COVER_S { HI_BOOL bSolid; /* Solid or hollow cover */ HI_U32 u32Thick; /* RW; Range: [2,8]; Thick of the hollow quadrangle */ POINT_S stPoint[4]; /* Four points of the quadrangle */ } VGS_QUADRANGLE_COVER_S; typedef struct hiVGS_ADD_COVER_S { VGS_COVER_TYPE_E enCoverType; /* Cover type */ union { RECT_S stDstRect; /* The rectangle area */ VGS_QUADRANGLE_COVER_S stQuadRangle; /* The quadrangle area */ }; HI_U32 u32Color; /* RW; Range: [0,0xFFFFFF]; Color of cover */ } VGS_ADD_COVER_S; typedef struct hiVGS_ADD_OSD_S { RECT_S stRect; /* Osd area */ HI_U32 u32BgColor; /* RW; Background color of osd, depends on pixel format of osd, ARGB8888:[0,0xFFFFFFFF], ARGB4444:[0,0xFFFF], ARGB1555:[0,0x1FFF] */ PIXEL_FORMAT_E enPixelFmt; /* Pixel format of osd */ HI_U64 u64PhyAddr; /* RW; Physical address of osd */ HI_U32 u32Stride; /* RW; Range: [32,8192]; Stride of osd */ HI_U32 u32BgAlpha; /* RW; Range: [0,255]; Background alpha of osd */ HI_U32 u32FgAlpha; /* RW; Range: [0,255]; Foreground alpha of osd */ HI_BOOL bOsdRevert; /* RW; Enable osd color revert */ VGS_OSD_REVERT_S stOsdRevert; /* Osd color revert information */ HI_U16 u16ColorLUT[2]; } VGS_ADD_OSD_S; typedef enum hiVGS_SCLCOEF_MODE_E { VGS_SCLCOEF_NORMAL = 0, /* normal scale coefficient */ VGS_SCLCOEF_TAP2 = 1, /* scale coefficient of 2 tap */ VGS_SCLCOEF_TAP4 = 2, /* scale coefficient of 4 tap */ VGS_SCLCOEF_TAP6 = 3, /* scale coefficient of 6 tap */ VGS_SCLCOEF_TAP8 = 4, /* scale coefficient of 8 tap */ VGS_SCLCOEF_BUTT } VGS_SCLCOEF_MODE_E; #ifdef __cplusplus #if __cplusplus } #endif #endif /* __cplusplus */ #endif /* __HI_COMM_VGS_H__ */
38.713043
108
0.697889
[ "solid" ]
a253fc8cf4505f8d9a5e1811e2156019b5c99e0a
17,572
c
C
PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/cli/model/client/cli_light_lc_client.c
sentervip/phy62xBleSDk2.0.1
edbb43c98d3f27a584a0026a5aac8197d7a219d0
[ "Apache-2.0" ]
1
2020-12-14T19:47:20.000Z
2020-12-14T19:47:20.000Z
PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/cli/model/client/cli_light_lc_client.c
sentervip/phy62xBleSDk2.0.1
edbb43c98d3f27a584a0026a5aac8197d7a219d0
[ "Apache-2.0" ]
null
null
null
PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/cli/model/client/cli_light_lc_client.c
sentervip/phy62xBleSDk2.0.1
edbb43c98d3f27a584a0026a5aac8197d7a219d0
[ "Apache-2.0" ]
null
null
null
/** * \file cli_light_lc_client.c * * \brief This file defines the Mesh Light Lc Model Application Interface * - includes Data Structures and Methods for Client. */ /* * Copyright (C) 2018. Mindtree Ltd. * All rights reserved. */ /* --------------------------------------------- Header File Inclusion */ #include "cli_light_lc_client.h" #ifdef CLI_LIGHTINGS_LC_CLIENT_MODEL /* --------------------------------------------- Global Definitions */ /* --------------------------------------------- Static Global Variables */ DECL_CONST CLI_COMMAND cli_modelc_light_lc_cmd_list[] = { /* Help */ { "help", "Help", cli_help }, /* Back */ { "back", "One Level Up", cli_back }, /* Root */ { "root", "Back to Root", cli_root }, /* Setup */ { "setup", "Model Light_Lc Setup", cli_modelc_light_lc_setup }, /* Get Model Handle */ { "gethandle", "Get Model Handle", cli_modelc_light_lc_get_model_handle }, /* Set Publish Address */ { "publishaddr", "Set Publish Address <Peer Server Address (HEX 16-bit)> <Appkey Index (HEX 16-bit)>", cli_modelc_light_lc_set_publish_address }, /* Send Light Lc Light Onoff Get */ { "lightonoffget", "Send Light Lc Light Onoff Get", cli_modelc_light_lc_light_onoff_get}, /* Send Light Lc Light Onoff Set */ { "lightonoffset", "Send Light Lc Light Onoff Set", cli_modelc_light_lc_light_onoff_set}, /* Send Light Lc Light Onoff Set Unacknowledged */ { "lightonoffsetun", "Send Light Lc Light Onoff Set Unacknowledged", cli_modelc_light_lc_light_onoff_set_unacknowledged}, /* Send Light Lc Mode Get */ { "modeget", "Send Light Lc Mode Get", cli_modelc_light_lc_mode_get}, /* Send Light Lc Mode Set */ { "modeset", "Send Light Lc Mode Set", cli_modelc_light_lc_mode_set}, /* Send Light Lc Mode Set Unacknowledged */ { "modesetun", "Send Light Lc Mode Set Unacknowledged", cli_modelc_light_lc_mode_set_unacknowledged}, /* Send Light Lc Om Get */ { "omget", "Send Light Lc Om Get", cli_modelc_light_lc_om_get}, /* Send Light Lc Om Set */ { "omset", "Send Light Lc Om Set", cli_modelc_light_lc_om_set}, /* Send Light Lc Om Set Unacknowledged */ { "omsetun", "Send Light Lc Om Set Unacknowledged", cli_modelc_light_lc_om_set_unacknowledged}, /* Send Light Lc Property Get */ { "propertyget", "Send Light Lc Property Get", cli_modelc_light_lc_property_get}, /* Send Light Lc Property Set */ { "propertyset", "Send Light Lc Property Set", cli_modelc_light_lc_property_set}, /* Send Light Lc Property Set Unacknowledged */ { "propertysetun", "Send Light Lc Property Set Unacknowledged", cli_modelc_light_lc_property_set_unacknowledged} }; /* --------------------------------------------- External Global Variables */ static MS_ACCESS_MODEL_HANDLE appl_light_lc_client_model_handle; /* --------------------------------------------- Function */ API_RESULT cli_modelc_light_lc(UINT32 argc, UCHAR *argv[]) { API_RESULT retval; CONSOLE_OUT("In Model Client - Light_Lc\n"); cli_cmd_stack_push((CLI_COMMAND *)cli_modelc_light_lc_cmd_list, sizeof(cli_modelc_light_lc_cmd_list) / sizeof(CLI_COMMAND)); retval = cli_help(argc, argv); return retval; } /* light_lc client CLI entry point */ API_RESULT cli_modelc_light_lc_setup(UINT32 argc, UCHAR *argv[]) { MS_ACCESS_ELEMENT_HANDLE element_handle; API_RESULT retval; static UCHAR model_initialized = 0x00; MS_IGNORE_UNUSED_PARAM(argc); MS_IGNORE_UNUSED_PARAM(argv); /** * Register with Access Layer. */ retval = API_FAILURE; if (0x00 == model_initialized) { /* Use Default Element Handle. Index 0 */ element_handle = MS_ACCESS_DEFAULT_ELEMENT_HANDLE; retval = MS_light_lc_client_init ( element_handle, &appl_light_lc_client_model_handle, cli_light_lc_client_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Light Lc Client Initialized. Model Handle: 0x%04X\n", appl_light_lc_client_model_handle); } else { CONSOLE_OUT( "[ERR] Light Lc Client Initialization Failed. Result: 0x%04X\n", retval); } model_initialized = 0x01; } return retval; } /* Send Light Lc Light Onoff Get */ API_RESULT cli_modelc_light_lc_light_onoff_get(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; CONSOLE_OUT (">> Send Light Lc Light Onoff Get\n"); retval = MS_light_lc_light_onoff_get(); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Light Onoff Set */ API_RESULT cli_modelc_light_lc_light_onoff_set(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_LIGHT_ONOFF_SET_STRUCT param; CONSOLE_OUT (">> Send Light Lc Light Onoff Set\n"); if (2 <= argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.light_onoff = (UCHAR)choice; CONSOLE_OUT("Light OnOff (8-bit in HEX): 0x%02X\n", param.light_onoff); choice = CLI_strtoi(argv[1], CLI_strlen(argv[1]), 16); param.tid = (UCHAR)choice; CONSOLE_OUT("TID (8-bit in HEX): 0x%02X\n", param.tid); } if (4 == argc) { param.optional_fields_present = 0x01; choice = CLI_strtoi(argv[2], CLI_strlen(argv[2]), 16); param.transition_time = (UCHAR)choice; CONSOLE_OUT("Transition Time (8-bit in HEX): 0x%02X\n", param.transition_time); choice = CLI_strtoi(argv[3], CLI_strlen(argv[3]), 16); param.delay = (UCHAR)choice; CONSOLE_OUT("Delay (8-bit in HEX): 0x%02X\n", param.delay); } else { param.optional_fields_present = 0x00; } retval = MS_light_lc_light_onoff_set(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Light Onoff Set Unacknowledged */ API_RESULT cli_modelc_light_lc_light_onoff_set_unacknowledged(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_LIGHT_ONOFF_SET_STRUCT param; CONSOLE_OUT (">> Send Light Lc Light Onoff Set Unacknowledged\n"); if (2 <= argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.light_onoff = (UCHAR)choice; CONSOLE_OUT("Light OnOff (8-bit in HEX): 0x%02X\n", param.light_onoff); choice = CLI_strtoi(argv[1], CLI_strlen(argv[1]), 16); param.tid = (UCHAR)choice; CONSOLE_OUT("TID (8-bit in HEX): 0x%02X\n", param.tid); } if (4 == argc) { param.optional_fields_present = 0x01; choice = CLI_strtoi(argv[2], CLI_strlen(argv[2]), 16); param.transition_time = (UCHAR)choice; CONSOLE_OUT("Transition Time (8-bit in HEX): 0x%02X\n", param.transition_time); choice = CLI_strtoi(argv[3], CLI_strlen(argv[3]), 16); param.delay = (UCHAR)choice; CONSOLE_OUT("Delay (8-bit in HEX): 0x%02X\n", param.delay); } else { param.optional_fields_present = 0x00; } retval = MS_light_lc_light_onoff_set_unacknowledged(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Mode Get */ API_RESULT cli_modelc_light_lc_mode_get(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; CONSOLE_OUT (">> Send Light Lc Mode Get\n"); retval = MS_light_lc_mode_get(); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Mode Set */ API_RESULT cli_modelc_light_lc_mode_set(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_MODE_STRUCT param; CONSOLE_OUT (">> Send Light Lc Mode Set\n"); if (1 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.mode = (UCHAR)choice; CONSOLE_OUT("Mode (8-bit in HEX): 0x%02X\n", param.mode); } retval = MS_light_lc_mode_set(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Mode Set Unacknowledged */ API_RESULT cli_modelc_light_lc_mode_set_unacknowledged(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_MODE_STRUCT param; CONSOLE_OUT (">> Send Light Lc Mode Set Unacknowledged\n"); if (1 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.mode = (UCHAR)choice; CONSOLE_OUT("Mode (8-bit in HEX): 0x%02X\n", param.mode); } retval = MS_light_lc_mode_set_unacknowledged(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Om Get */ API_RESULT cli_modelc_light_lc_om_get(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; CONSOLE_OUT (">> Send Light Lc Om Get\n"); retval = MS_light_lc_om_get(); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Om Set */ API_RESULT cli_modelc_light_lc_om_set(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_OM_STRUCT param; CONSOLE_OUT (">> Send Light Lc Om Set\n"); if (1 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.mode = (UCHAR)choice; CONSOLE_OUT("Mode (8-bit in HEX): 0x%02X\n", param.mode); } retval = MS_light_lc_om_set(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Om Set Unacknowledged */ API_RESULT cli_modelc_light_lc_om_set_unacknowledged(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_OM_STRUCT param; CONSOLE_OUT (">> Send Light Lc Om Set Unacknowledged\n"); if (1 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.mode = (UCHAR)choice; CONSOLE_OUT("Mode (8-bit in HEX): 0x%02X\n", param.mode); } retval = MS_light_lc_om_set_unacknowledged(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Property Get */ API_RESULT cli_modelc_light_lc_property_get(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_PROPERTY_GET_STRUCT param; CONSOLE_OUT (">> Send Light Lc Property Get\n"); if (1 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.light_lc_property_id = (UINT16)choice; CONSOLE_OUT("Light LC Property ID (16-bit in HEX): 0x%04X\n", param.light_lc_property_id); } retval = MS_light_lc_property_get(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); return retval; } /* Send Light Lc Property Set */ API_RESULT cli_modelc_light_lc_property_set(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_PROPERTY_SET_STRUCT param; retval = API_FAILURE; CONSOLE_OUT (">> Send Light Lc Property Set\n"); if (2 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.light_lc_property_id = (UINT16)choice; CONSOLE_OUT("Light LC Property ID (16-bit in HEX): 0x%04X\n", param.light_lc_property_id); choice = CLI_strlen(argv[1]); { UINT16 input_len; input_len = (UINT16)choice; param.light_lc_property_value = EM_alloc_mem(input_len); if(NULL == param.light_lc_property_value) { CONSOLE_OUT ("Memory allocation failed for Light LC Property Value. Returning\n"); return retval; } param.light_lc_property_value_len = (UINT16) input_len; CLI_strtoarray ( argv[1], CLI_strlen(argv[1]), &param.light_lc_property_value[0], input_len ); } } retval = MS_light_lc_property_set(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); if(NULL != param.light_lc_property_value) { EM_free_mem(param.light_lc_property_value); } return retval; } /* Send Light Lc Property Set Unacknowledged */ API_RESULT cli_modelc_light_lc_property_set_unacknowledged(UINT32 argc, UCHAR * argv[]) { API_RESULT retval; int choice; MS_LIGHT_LC_PROPERTY_SET_STRUCT param; retval = API_FAILURE; CONSOLE_OUT (">> Send Light Lc Property Set Unacknowledged\n"); if (2 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); param.light_lc_property_id = (UINT16)choice; CONSOLE_OUT("Light LC Property ID (16-bit in HEX): 0x%04X\n", param.light_lc_property_id); choice = CLI_strlen(argv[1]); { UINT16 input_len; input_len = (UINT16)choice; param.light_lc_property_value = EM_alloc_mem(input_len); if(NULL == param.light_lc_property_value) { CONSOLE_OUT ("Memory allocation failed for Light LC Property Value. Returning\n"); return retval; } param.light_lc_property_value_len = (UINT16) input_len; CLI_strtoarray ( argv[1], CLI_strlen(argv[1]), &param.light_lc_property_value[0], input_len ); } } retval = MS_light_lc_property_set_unacknowledged(&param); CONSOLE_OUT ("retval = 0x%04X\n", retval); if(NULL != param.light_lc_property_value) { EM_free_mem(param.light_lc_property_value); } return retval; } /* Get Model Handle */ API_RESULT cli_modelc_light_lc_get_model_handle(UINT32 argc, UCHAR *argv[]) { API_RESULT retval; #if 0 MS_ACCESS_MODEL_HANDLE model_handle; retval = MS_light_lc_get_model_handle(&model_handle); if (API_SUCCESS == retval) { CONSOLE_OUT (">> Model Handle 0x%04X\n", model_handle); } else { CONSOLE_OUT (">> Get Model Handle Failed. Status 0x%04X\n", retval); } #else retval = API_FAILURE; CONSOLE_OUT("To be implemented\n"); #endif /* 0 */ return retval; } /* Set Publish Address */ API_RESULT cli_modelc_light_lc_set_publish_address(UINT32 argc, UCHAR * argv[]) { int choice; API_RESULT retval; MS_ACCESS_MODEL_HANDLE model_handle; MS_ACCESS_PUBLISH_INFO publish_info; /* Set Publish Information */ EM_mem_set(&publish_info, 0, sizeof(publish_info)); publish_info.addr.use_label = MS_FALSE; model_handle = appl_light_lc_client_model_handle; CONSOLE_OUT("Model Handle (16-bit in HEX): 0x%04X\n", model_handle); /* Check Number of Arguments */ if (2 == argc) { choice = CLI_strtoi(argv[0], CLI_strlen(argv[0]), 16); publish_info.addr.addr = (UINT16)choice; CONSOLE_OUT("Light_Lc Server Address (16-bit in HEX): 0x%04X\n", publish_info.addr.addr); choice = CLI_strtoi(argv[1], CLI_strlen(argv[1]), 16); publish_info.appkey_index = (UINT16)choice; CONSOLE_OUT("AppKey Index: 0x%04X\n", publish_info.appkey_index); } else { CONSOLE_OUT("Invalid Number of Arguments:0x%04X. Returning.\n", argc); return API_FAILURE; } publish_info.remote = MS_FALSE; retval = MS_access_cm_set_model_publication ( model_handle, &publish_info ); if (API_SUCCESS == retval) { CONSOLE_OUT (">> Publish Address is set Successfully.\n"); } else { CONSOLE_OUT (">> Failed to set publish address. Status 0x%04X\n", retval); } return retval; } /** * \brief Client Application Asynchronous Notification Callback. * * \par Description * Light_Lc client calls the registered callback to indicate events occurred to the application. * * \param [in] handle Model Handle. * \param [in] opcode Opcode. * \param [in] data_param Data associated with the event if any or NULL. * \param [in] data_len Size of the event data. 0 if event data is NULL. */ API_RESULT cli_light_lc_client_cb ( /* IN */ MS_ACCESS_MODEL_HANDLE * handle, /* IN */ UINT32 opcode, /* IN */ UCHAR * data_param, /* IN */ UINT16 data_len ) { API_RESULT retval; retval = API_SUCCESS; CONSOLE_OUT ( "[LIGHT_LC_CLIENT] Callback. Opcode 0x%04X\n", opcode); appl_dump_bytes(data_param, data_len); switch(opcode) { case MS_ACCESS_LIGHT_LC_LIGHT_ONOFF_STATUS_OPCODE: { CONSOLE_OUT( "MS_ACCESS_LIGHT_LC_LIGHT_ONOFF_STATUS_OPCODE\n"); } break; case MS_ACCESS_LIGHT_LC_MODE_STATUS_OPCODE: { CONSOLE_OUT( "MS_ACCESS_LIGHT_LC_MODE_STATUS_OPCODE\n"); } break; case MS_ACCESS_LIGHT_LC_OM_STATUS_OPCODE: { CONSOLE_OUT( "MS_ACCESS_LIGHT_LC_OM_STATUS_OPCODE\n"); } break; case MS_ACCESS_LIGHT_LC_PROPERTY_STATUS_OPCODE: { CONSOLE_OUT( "MS_ACCESS_LIGHT_LC_PROPERTY_STATUS_OPCODE\n"); } break; } return retval; } #endif /* CLI_LIGHTINGS_LC_CLIENT_MODEL */
25.994083
150
0.617573
[ "mesh", "model" ]
a257951ba8be66e8b5933bf230244e6b3bf13e12
12,718
h
C
libraries/entities-renderer/src/EntityTreeRenderer.h
BibleUs/hifi
cdf210d08114bb85492844f8a3005810edf3adaa
[ "Apache-2.0" ]
null
null
null
libraries/entities-renderer/src/EntityTreeRenderer.h
BibleUs/hifi
cdf210d08114bb85492844f8a3005810edf3adaa
[ "Apache-2.0" ]
null
null
null
libraries/entities-renderer/src/EntityTreeRenderer.h
BibleUs/hifi
cdf210d08114bb85492844f8a3005810edf3adaa
[ "Apache-2.0" ]
2
2019-06-13T22:25:13.000Z
2022-01-31T15:17:55.000Z
// // EntityTreeRenderer.h // interface/src // // Created by Brad Hefta-Gaub on 12/6/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_EntityTreeRenderer_h #define hifi_EntityTreeRenderer_h #include <QtCore/QSet> #include <QtCore/QStack> #include <QtGui/QMouseEvent> #include <AbstractAudioInterface.h> #include <EntityScriptingInterface.h> // for RayToEntityIntersectionResult #include <EntityTree.h> #include <PointerEvent.h> #include <ScriptCache.h> #include <TextureCache.h> #include <OctreeProcessor.h> #include <render/Forward.h> #include <workload/Space.h> class AbstractScriptingServicesInterface; class AbstractViewStateInterface; class Model; class ScriptEngine; class ZoneEntityItem; class EntityItem; namespace render { namespace entities { class EntityRenderer; using EntityRendererPointer = std::shared_ptr<EntityRenderer>; using EntityRendererWeakPointer = std::weak_ptr<EntityRenderer>; } } using EntityRenderer = render::entities::EntityRenderer; using EntityRendererPointer = render::entities::EntityRendererPointer; using EntityRendererWeakPointer = render::entities::EntityRendererWeakPointer; class Model; using ModelPointer = std::shared_ptr<Model>; using ModelWeakPointer = std::weak_ptr<Model>; using CalculateEntityLoadingPriority = std::function<float(const EntityItem& item)>; // Generic client side Octree renderer class. class EntityTreeRenderer : public OctreeProcessor, public Dependency { Q_OBJECT public: static void setEntitiesShouldFadeFunction(std::function<bool()> func) { _entitiesShouldFadeFunction = func; } static std::function<bool()> getEntitiesShouldFadeFunction() { return _entitiesShouldFadeFunction; } EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, AbstractScriptingServicesInterface* scriptingServices); virtual ~EntityTreeRenderer(); QSharedPointer<EntityTreeRenderer> getSharedFromThis() { return qSharedPointerCast<EntityTreeRenderer>(sharedFromThis()); } virtual char getMyNodeType() const override { return NodeType::EntityServer; } virtual PacketType getMyQueryMessageType() const override { return PacketType::EntityQuery; } virtual PacketType getExpectedPacketType() const override { return PacketType::EntityData; } // Returns the priority at which an entity should be loaded. Higher values indicate higher priority. static float getEntityLoadingPriority(const EntityItem& item) { return _calculateEntityLoadingPriorityFunc(item); } static void setEntityLoadingPriorityFunction(CalculateEntityLoadingPriority fn) { _calculateEntityLoadingPriorityFunc = fn; } void setMouseRayPickID(unsigned int rayPickID) { _mouseRayPickID = rayPickID; } unsigned int getMouseRayPickID() { return _mouseRayPickID; } void setMouseRayPickResultOperator(std::function<RayToEntityIntersectionResult(unsigned int)> getPrevRayPickResultOperator) { _getPrevRayPickResultOperator = getPrevRayPickResultOperator; } void setSetPrecisionPickingOperator(std::function<void(unsigned int, bool)> setPrecisionPickingOperator) { _setPrecisionPickingOperator = setPrecisionPickingOperator; } void shutdown(); void update(bool simulate); EntityTreePointer getTree() { return std::static_pointer_cast<EntityTree>(_tree); } void processEraseMessage(ReceivedMessage& message, const SharedNodePointer& sourceNode); virtual void init() override; /// clears the tree virtual void clearDomainAndNonOwnedEntities() override; virtual void clear() override; /// reloads the entity scripts, calling unload and preload void reloadEntityScripts(); // event handles which may generate entity related events QUuid mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void mouseDoublePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); /// connect our signals to anEntityScriptingInterface for firing of events related clicking, /// hovering over, and entering entities void connectSignalsToSlots(EntityScriptingInterface* entityScriptingInterface); // For Scene.shouldRenderEntities QList<EntityItemID>& getEntitiesLastInScene() { return _entityIDsLastInScene; } std::pair<bool, bool> getZoneInteractionProperties(); bool wantsKeyboardFocus(const EntityItemID& id) const; QObject* getEventHandler(const EntityItemID& id); bool wantsHandControllerPointerEvents(const EntityItemID& id) const; void setProxyWindow(const EntityItemID& id, QWindow* proxyWindow); void setCollisionSound(const EntityItemID& id, const SharedSoundPointer& sound); EntityItemPointer getEntity(const EntityItemID& id); void onEntityChanged(const EntityItemID& id); // Access the workload Space workload::SpacePointer getWorkloadSpace() const { return _space; } EntityEditPacketSender* getPacketSender(); static void setAddMaterialToEntityOperator(std::function<bool(const QUuid&, graphics::MaterialLayer, const std::string&)> addMaterialToEntityOperator) { _addMaterialToEntityOperator = addMaterialToEntityOperator; } static void setRemoveMaterialFromEntityOperator(std::function<bool(const QUuid&, graphics::MaterialPointer, const std::string&)> removeMaterialFromEntityOperator) { _removeMaterialFromEntityOperator = removeMaterialFromEntityOperator; } static bool addMaterialToEntity(const QUuid& entityID, graphics::MaterialLayer material, const std::string& parentMaterialName); static bool removeMaterialFromEntity(const QUuid& entityID, graphics::MaterialPointer material, const std::string& parentMaterialName); static void setAddMaterialToAvatarOperator(std::function<bool(const QUuid&, graphics::MaterialLayer, const std::string&)> addMaterialToAvatarOperator) { _addMaterialToAvatarOperator = addMaterialToAvatarOperator; } static void setRemoveMaterialFromAvatarOperator(std::function<bool(const QUuid&, graphics::MaterialPointer, const std::string&)> removeMaterialFromAvatarOperator) { _removeMaterialFromAvatarOperator = removeMaterialFromAvatarOperator; } static bool addMaterialToAvatar(const QUuid& avatarID, graphics::MaterialLayer material, const std::string& parentMaterialName); static bool removeMaterialFromAvatar(const QUuid& avatarID, graphics::MaterialPointer material, const std::string& parentMaterialName); signals: void enterEntity(const EntityItemID& entityItemID); void leaveEntity(const EntityItemID& entityItemID); void collisionWithEntity(const EntityItemID& idA, const EntityItemID& idB, const Collision& collision); public slots: void addingEntity(const EntityItemID& entityID); void deletingEntity(const EntityItemID& entityID); void entityScriptChanging(const EntityItemID& entityID, const bool reload); void entityCollisionWithEntity(const EntityItemID& idA, const EntityItemID& idB, const Collision& collision); void updateEntityRenderStatus(bool shouldRenderEntities); void updateZone(const EntityItemID& id); // optional slots that can be wired to menu items void setDisplayModelBounds(bool value) { _displayModelBounds = value; } void setPrecisionPicking(bool value) { _setPrecisionPickingOperator(_mouseRayPickID, value); } EntityRendererPointer renderableForEntityId(const EntityItemID& id) const; render::ItemID renderableIdForEntityId(const EntityItemID& id) const; void handleSpaceUpdate(std::pair<int32_t, glm::vec4> proxyUpdate); protected: virtual OctreePointer createTree() override { EntityTreePointer newTree = EntityTreePointer(new EntityTree(true)); newTree->createRootElement(); return newTree; } private: void addPendingEntities(const render::ScenePointer& scene, render::Transaction& transaction); void updateChangedEntities(const render::ScenePointer& scene, render::Transaction& transaction); EntityRendererPointer renderableForEntity(const EntityItemPointer& entity) const { return renderableForEntityId(entity->getID()); } render::ItemID renderableIdForEntity(const EntityItemPointer& entity) const { return renderableIdForEntityId(entity->getID()); } void resetEntitiesScriptEngine(); bool findBestZoneAndMaybeContainingEntities(QVector<EntityItemID>* entitiesContainingAvatar = nullptr); bool applyLayeredZones(); void stopDomainAndNonOwnedEntities(); void checkAndCallPreload(const EntityItemID& entityID, bool reload = false, bool unloadFirst = false); EntityItemID _currentHoverOverEntityID; EntityItemID _currentClickingOnEntityID; QScriptValueList createEntityArgs(const EntityItemID& entityID); bool checkEnterLeaveEntities(); void leaveDomainAndNonOwnedEntities(); void leaveAllEntities(); void forceRecheckEntities(); glm::vec3 _avatarPosition { 0.0f }; QVector<EntityItemID> _currentEntitiesInside; bool _wantScripts; ScriptEnginePointer _entitiesScriptEngine; void playEntityCollisionSound(const EntityItemPointer& entity, const Collision& collision); bool _lastPointerEventValid; PointerEvent _lastPointerEvent; AbstractViewStateInterface* _viewState; AbstractScriptingServicesInterface* _scriptingServices; bool _displayModelBounds; bool _shuttingDown { false }; QMultiMap<QUrl, EntityItemID> _waitingOnPreload; unsigned int _mouseRayPickID; std::function<RayToEntityIntersectionResult(unsigned int)> _getPrevRayPickResultOperator; std::function<void(unsigned int, bool)> _setPrecisionPickingOperator; class LayeredZone { public: LayeredZone(std::shared_ptr<ZoneEntityItem> zone, QUuid id, float volume) : zone(zone), id(id), volume(volume) {} LayeredZone(std::shared_ptr<ZoneEntityItem> zone) : LayeredZone(zone, zone->getID(), zone->getVolumeEstimate()) {} bool operator<(const LayeredZone& r) const { return std::tie(volume, id) < std::tie(r.volume, r.id); } bool operator==(const LayeredZone& r) const { return id == r.id; } bool operator<=(const LayeredZone& r) const { return (*this < r) || (*this == r); } std::shared_ptr<ZoneEntityItem> zone; QUuid id; float volume; }; class LayeredZones : public std::set<LayeredZone> { public: LayeredZones() {}; LayeredZones(LayeredZones&& other); // avoid accidental misconstruction LayeredZones(const LayeredZones&) = delete; LayeredZones& operator=(const LayeredZones&) = delete; LayeredZones& operator=(LayeredZones&&) = delete; void clear(); void clearNonLocalLayeredZones(); std::pair<iterator, bool> insert(const LayeredZone& layer); void update(std::shared_ptr<ZoneEntityItem> zone); bool contains(const LayeredZones& other); std::shared_ptr<ZoneEntityItem> getZone() { return empty() ? nullptr : begin()->zone; } private: std::map<QUuid, iterator> _map; iterator _skyboxLayer { end() }; }; LayeredZones _layeredZones; float _avgRenderableUpdateCost { 0.0f }; uint64_t _lastZoneCheck { 0 }; const uint64_t ZONE_CHECK_INTERVAL = USECS_PER_MSEC * 100; // ~10hz const float ZONE_CHECK_DISTANCE = 0.001f; ReadWriteLockable _changedEntitiesGuard; std::unordered_set<EntityItemID> _changedEntities; std::unordered_map<EntityItemID, EntityRendererPointer> _renderablesToUpdate; std::unordered_map<EntityItemID, EntityRendererPointer> _entitiesInScene; std::unordered_map<EntityItemID, EntityItemWeakPointer> _entitiesToAdd; // For Scene.shouldRenderEntities QList<EntityItemID> _entityIDsLastInScene; static int _entitiesScriptEngineCount; static CalculateEntityLoadingPriority _calculateEntityLoadingPriorityFunc; static std::function<bool()> _entitiesShouldFadeFunction; mutable std::mutex _spaceLock; workload::SpacePointer _space{ new workload::Space() }; workload::Transaction::Updates _spaceUpdates; static std::function<bool(const QUuid&, graphics::MaterialLayer, const std::string&)> _addMaterialToEntityOperator; static std::function<bool(const QUuid&, graphics::MaterialPointer, const std::string&)> _removeMaterialFromEntityOperator; static std::function<bool(const QUuid&, graphics::MaterialLayer, const std::string&)> _addMaterialToAvatarOperator; static std::function<bool(const QUuid&, graphics::MaterialPointer, const std::string&)> _removeMaterialFromAvatarOperator; }; #endif // hifi_EntityTreeRenderer_h
45.748201
240
0.769382
[ "render", "model" ]
a25991a82ddcade915625f2ed4777e6e2d0fa62d
7,664
h
C
lonestardist/include/cpu_mining/canonical_graph.h
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestardist/include/cpu_mining/canonical_graph.h
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestardist/include/cpu_mining/canonical_graph.h
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
#ifndef CANONICAL_GRAPH_HPP_ #define CANONICAL_GRAPH_HPP_ #include "embedding.h" typedef std::priority_queue<Edge, std::vector<Edge>, EdgeComparator> EdgeHeap; typedef std::unordered_map<VertexId, BYTE> VertexMap; typedef std::vector<bliss::Graph::Vertex> BlissVertexList; template <typename EmbeddingTy, typename ElementTy> class CanonicalGraph; template <typename EmbeddingTy, typename ElementTy> std::ostream& operator<<(std::ostream& strm, const CanonicalGraph<EmbeddingTy, ElementTy>& cg); template <typename EmbeddingTy, typename ElementTy> class CanonicalGraph { friend std::ostream & operator<< <>(std::ostream & strm, const CanonicalGraph<EmbeddingTy,ElementTy>& cg); public: CanonicalGraph() : number_of_vertices(0), hash_value(0) {} CanonicalGraph(bliss::AbstractGraph* ag, bool is_directed = false) { assert(!is_directed); construct_cg(ag); } CanonicalGraph(const QuickPattern<EmbeddingTy,ElementTy>& qp, bool is_directed = false) { assert(!is_directed); bliss::AbstractGraph* ag = turn_abstract(qp); construct_cg(ag); } ~CanonicalGraph() {} int cmp(const CanonicalGraph& other_cg) const { //compare the numbers of vertices if(get_num_vertices() < other_cg.get_num_vertices()) return -1; if(get_num_vertices() > other_cg.get_num_vertices()) return 1; //compare hash value if(get_hash() < other_cg.get_hash()) return -1; if(get_hash() > other_cg.get_hash()) return 1; //compare edges assert(embedding.size() == other_cg.embedding.size()); for(unsigned i = 0; i < embedding.size(); ++i) { const auto & t1 = embedding.get_element(i); const auto & t2 = other_cg.embedding.get_element(i); int cmp_element = t1.cmp(t2); if(cmp_element != 0) return cmp_element; } return 0; } inline unsigned get_hash() const { return hash_value; } inline int get_num_vertices() const { return number_of_vertices; } //operator for map inline bool operator==(const CanonicalGraph& other) const { return cmp(other) == 0; } //inline EmbeddingTy& get_embedding() { return embedding; } inline EmbeddingTy get_embedding() const { return embedding; } inline void set_number_vertices(int num_vertices) { number_of_vertices = num_vertices; } inline void set_hash_value(unsigned int hash) { hash_value = hash; } inline unsigned get_quick_pattern_index(unsigned i) { return qp_idx[i]; } inline unsigned get_id() const { return hash_value; } inline void clean() { embedding.clean(); } private: EmbeddingTy embedding; std::vector<int> qp_idx; // TODO: try gstl::Vector int number_of_vertices; unsigned hash_value; unsigned support; void construct_cg(bliss::AbstractGraph* ag) { number_of_vertices = ag->get_nof_vertices(); hash_value = ag->get_hash(); transform_to_embedding(ag); } void transform_to_embedding(bliss::AbstractGraph* ag) { bliss::Graph* graph = (bliss::Graph*) ag; VertexSet set; VertexMap map; EdgeHeap min_heap; BlissVertexList vertices = graph->get_vertices_rstream(); VertexId first_src = init_heapAndset(vertices, min_heap, set); assert(first_src != -1); push_first_element(first_src, map, vertices); #ifdef USE_DOMAIN bool is_first_edge = true; #endif while(!min_heap.empty()) { Edge edge = min_heap.top(); #ifdef USE_DOMAIN if (is_first_edge) { qp_idx.push_back(edge.src_domain); is_first_edge = false; } #endif push_element(edge, map, vertices); min_heap.pop(); add_neighbours(edge, min_heap, vertices, set); } } VertexId init_heapAndset(BlissVertexList& vertices, EdgeHeap& min_heap, VertexSet& set) { for(unsigned i = 0; i < vertices.size(); ++i) { if(!vertices[i].edges.empty()) { for(auto v: vertices[i].edges) { #ifdef USE_DOMAIN min_heap.push(Edge(i, v.first, v.second.first, v.second.second)); #else min_heap.push(Edge(i, v)); #endif } set.insert(i); return i; } } return -1; } void push_first_element(VertexId first, VertexMap& map, BlissVertexList& vertices){ map[first] = 0; embedding.push_back(ElementTy(first + 1, (BYTE)0, (BYTE)vertices[first].color, (BYTE)0)); } void push_element(Edge& edge, VertexMap& map, BlissVertexList& vertices){ assert(edge.src < edge.dst); if(map.find(edge.src) != map.end()) { embedding.push_back(ElementTy(edge.dst + 1, (BYTE)0, (BYTE)vertices[edge.dst].color, (BYTE)map[edge.src])); #ifdef USE_DOMAIN qp_idx.push_back(edge.dst_domain); #endif if(map.find(edge.dst) == map.end()) { int s = embedding.size() - 1; map[edge.dst] = s; } } else if(map.find(edge.dst) != map.end()) { embedding.push_back(ElementTy(edge.src + 1, (BYTE)0, (BYTE)vertices[edge.src].color, (BYTE)map[edge.dst])); #ifdef USE_DOMAIN qp_idx.push_back(edge.src_domain); #endif if(map.find(edge.src) == map.end()) { int s = embedding.size() - 1; map[edge.src] = s; } } else { //wrong case std::cout << "wrong case!!!" << std::endl; throw std::exception(); } } void add_neighbours(Edge& edge, EdgeHeap& min_heap, BlissVertexList& vertices, VertexSet& set) { add_neighbours(edge.src, min_heap, vertices, set); add_neighbours(edge.dst, min_heap, vertices, set); } void add_neighbours(VertexId srcId, EdgeHeap& min_heap, BlissVertexList& vertices, VertexSet& set) { if(set.find(srcId) == set.end()){ for(auto v: vertices[srcId].edges) { #ifdef USE_DOMAIN VertexId dst = v.first; #else VertexId dst = v; #endif if(set.find(dst) == set.end()) { #ifdef USE_DOMAIN Edge edge(srcId, dst, v.second.first, v.second.second); #else Edge edge(srcId, dst); #endif edge.swap(); min_heap.push(edge); } } set.insert(srcId); } } static void report_aut(void* param, const unsigned n, const unsigned* aut) { assert(param); //fprintf((FILE*) param, "Generator: "); //bliss::print_permutation((FILE*) param, n, aut, 1); //fprintf((FILE*) param, "\n"); } bliss::AbstractGraph* turn_abstract(const QuickPattern<EmbeddingTy,ElementTy>& qp) { bliss::AbstractGraph* ag = 0; //get the number of vertices std::unordered_map<VertexId, BYTE> vertices; for(unsigned index = 0; index < qp.get_size(); ++index) { auto element = qp.at(index); #ifdef ENABLE_LABEL vertices[element.get_vid()] = element.get_vlabel(); #else vertices[element.get_vid()] = 0; #endif } //construct bliss graph const unsigned number_vertices = vertices.size(); ag = new bliss::Graph(vertices.size()); //set vertices for(unsigned i = 0; i < number_vertices; ++i) ag->change_color(i, (unsigned)vertices[i + 1]); //read edges assert(qp.get_size() > 1); for(unsigned index = 1; index < qp.get_size(); ++index) { auto element = qp.at(index); VertexId from, to; from = qp.at(element.get_his()).get_vid(); to = element.get_vid(); //std::cout << "Adding edge: " << from << " --> " << to << "\n"; ag->add_edge(from - 1, to - 1, std::make_pair((unsigned)element.get_his(), index)); } bliss::Stats stats; const unsigned * cl = ag->canonical_form(stats, &report_aut, stdout); // canonical labeling. This is expensive. bliss::AbstractGraph* cf = ag->permute(cl); //permute to canonical form delete ag; return cf; } }; template <typename EmbeddingTy, typename ElementTy> std::ostream & operator<<(std::ostream & strm, const CanonicalGraph<EmbeddingTy,ElementTy>& cg) { strm << "{" << cg.embedding << "; " << cg.get_num_vertices() << "}"; return strm; } namespace std { //template<> template <typename EmbeddingTy, typename ElementTy> struct hash<CanonicalGraph<EmbeddingTy,ElementTy> > { std::size_t operator()(const CanonicalGraph<EmbeddingTy,ElementTy>& cg) const { return std::hash<int>()(cg.get_hash()); } }; } #endif // CANONICAL_GRAPH_HPP_
34.522523
147
0.695981
[ "vector" ]
a25b5686963800dcb676b9add36d2ab09d3d61f7
2,533
h
C
connectivity/shill/test-rpc-proxy/proxy_rpc_server.h
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/test-rpc-proxy/proxy_rpc_server.h
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/test-rpc-proxy/proxy_rpc_server.h
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
// // Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PROXY_RPC_SERVER_H #define PROXY_RPC_SERVER_H #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <iostream> #include <base/logging.h> #include <base/callback.h> #include "XmlRpc.h" #include "proxy_shill_wifi_client.h" typedef const base::Callback<XmlRpc::XmlRpcValue( XmlRpc::XmlRpcValue, ProxyShillWifiClient*)> RpcServerMethodHandler; class ProxyRpcServer; class ProxyRpcServerMethod : public XmlRpc::XmlRpcServerMethod { public: ProxyRpcServerMethod(const std::string& method_name, const RpcServerMethodHandler& handler, ProxyShillWifiClient* shill_wifi_client, ProxyRpcServer* server); // This is the function signature exposed by the XmlRpc++ library // that we depend on and hence the non-const references. void execute(XmlRpc::XmlRpcValue& params_in, XmlRpc::XmlRpcValue& value_out); std::string help(void); private: RpcServerMethodHandler handler_; // RPC server methods hold a copy of the raw pointer to the instance of // the |ShillWifiClient| owned by the RPC server. ProxyShillWifiClient* shill_wifi_client_; DISALLOW_COPY_AND_ASSIGN(ProxyRpcServerMethod); }; class ProxyRpcServer : public XmlRpc::XmlRpcServer { public: ProxyRpcServer(int server_port, std::unique_ptr<ProxyShillWifiClient> shill_wifi_client); void Run(); void RegisterRpcMethod(const std::string& method_name, const RpcServerMethodHandler& handler); private: int server_port_; // RPC server owns the only instance of the |ShillWifiClient| used. std::unique_ptr<ProxyShillWifiClient> shill_wifi_client_; // Instances of the various methods registered with the server. std::vector<std::unique_ptr<ProxyRpcServerMethod>> methods_; DISALLOW_COPY_AND_ASSIGN(ProxyRpcServer); }; #endif // PROXY_RPC_SERVER_H
32.896104
79
0.739045
[ "vector" ]
a26b29c723b9eb4f143fc83da455aafa5157a7bb
1,694
h
C
src/ios_tools/chrome/browser/net/retryable_url_fetcher.h
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/ios_tools/chrome/browser/net/retryable_url_fetcher.h
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/ios_tools/chrome/browser/net/retryable_url_fetcher.h
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_NET_RETRYABLE_URL_FETCHER_H_ #define IOS_CHROME_BROWSER_NET_RETRYABLE_URL_FETCHER_H_ #import <Foundation/Foundation.h> #include "net/base/backoff_entry.h" namespace net { class URLRequestContextGetter; } // namespace net // Delegate protocol for RetryableURLFetcher object. @protocol RetryableURLFetcherDelegate<NSObject> // Returns the HTTP URL for RetryableURLFetcher to fetch. - (NSString*)urlToFetch; // Callback function after URL has been fetched. |response| is the content of // the HTTP response. This method may be called with a nil |response| if the // HTTP request failed. - (void)processSuccessResponse:(NSString*)response; @end @interface RetryableURLFetcher : NSObject // Designated initializer. |context| and |delegate| must not be nil. If |policy| // is not null, it specifies how often to retry the URL fetch on a call to // -startFetch. If |policy| is null, there is no retry. - (instancetype) initWithRequestContextGetter:(net::URLRequestContextGetter*)context delegate:(id<RetryableURLFetcherDelegate>)delegate backoffPolicy:(const net::BackoffEntry::Policy*)policy; // Starts fetching URL. Uses the backoff policy specified when the object was // initialized. - (void)startFetch; // Returns the number of times that this URL Fetcher failed to receive a // success response. Returns 0 if this URL Fetcher was not set up to do retries. - (int)failureCount; @end #endif // IOS_CHROME_BROWSER_NET_RETRYABLE_URL_FETCHER_H_
33.88
80
0.763872
[ "object" ]
a26dccd12759731cacc1d97924ed6edab3919c26
12,763
h
C
aws-cpp-sdk-cognito-idp/include/aws/cognito-idp/model/GetUserResult.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2019-10-10T20:58:44.000Z
2019-10-10T20:58:44.000Z
aws-cpp-sdk-cognito-idp/include/aws/cognito-idp/model/GetUserResult.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-cognito-idp/include/aws/cognito-idp/model/GetUserResult.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/cognito-idp/model/AttributeType.h> #include <aws/cognito-idp/model/MFAOptionType.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace CognitoIdentityProvider { namespace Model { /** * <p>Represents the response from the server from the request to get information * about the user.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUserResponse">AWS * API Reference</a></p> */ class AWS_COGNITOIDENTITYPROVIDER_API GetUserResult { public: GetUserResult(); GetUserResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); GetUserResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline const Aws::String& GetUsername() const{ return m_username; } /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline void SetUsername(const Aws::String& value) { m_username = value; } /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline void SetUsername(Aws::String&& value) { m_username = std::move(value); } /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline void SetUsername(const char* value) { m_username.assign(value); } /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline GetUserResult& WithUsername(const Aws::String& value) { SetUsername(value); return *this;} /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline GetUserResult& WithUsername(Aws::String&& value) { SetUsername(std::move(value)); return *this;} /** * <p>The user name of the user you wish to retrieve from the get user request.</p> */ inline GetUserResult& WithUsername(const char* value) { SetUsername(value); return *this;} /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline const Aws::Vector<AttributeType>& GetUserAttributes() const{ return m_userAttributes; } /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline void SetUserAttributes(const Aws::Vector<AttributeType>& value) { m_userAttributes = value; } /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline void SetUserAttributes(Aws::Vector<AttributeType>&& value) { m_userAttributes = std::move(value); } /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline GetUserResult& WithUserAttributes(const Aws::Vector<AttributeType>& value) { SetUserAttributes(value); return *this;} /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline GetUserResult& WithUserAttributes(Aws::Vector<AttributeType>&& value) { SetUserAttributes(std::move(value)); return *this;} /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline GetUserResult& AddUserAttributes(const AttributeType& value) { m_userAttributes.push_back(value); return *this; } /** * <p>An array of name-value pairs representing user attributes.</p> <p>For custom * attributes, you must prepend the <code>custom:</code> prefix to the attribute * name.</p> */ inline GetUserResult& AddUserAttributes(AttributeType&& value) { m_userAttributes.push_back(std::move(value)); return *this; } /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline const Aws::Vector<MFAOptionType>& GetMFAOptions() const{ return m_mFAOptions; } /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline void SetMFAOptions(const Aws::Vector<MFAOptionType>& value) { m_mFAOptions = value; } /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline void SetMFAOptions(Aws::Vector<MFAOptionType>&& value) { m_mFAOptions = std::move(value); } /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline GetUserResult& WithMFAOptions(const Aws::Vector<MFAOptionType>& value) { SetMFAOptions(value); return *this;} /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline GetUserResult& WithMFAOptions(Aws::Vector<MFAOptionType>&& value) { SetMFAOptions(std::move(value)); return *this;} /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline GetUserResult& AddMFAOptions(const MFAOptionType& value) { m_mFAOptions.push_back(value); return *this; } /** * <p> <i>This response parameter is no longer supported.</i> It provides * information only about SMS MFA configurations. It doesn't provide information * about TOTP software token MFA configurations. To look up information about * either type of MFA configuration, use the use the * <a>GetUserResponse$UserMFASettingList</a> response instead.</p> */ inline GetUserResult& AddMFAOptions(MFAOptionType&& value) { m_mFAOptions.push_back(std::move(value)); return *this; } /** * <p>The user's preferred MFA setting.</p> */ inline const Aws::String& GetPreferredMfaSetting() const{ return m_preferredMfaSetting; } /** * <p>The user's preferred MFA setting.</p> */ inline void SetPreferredMfaSetting(const Aws::String& value) { m_preferredMfaSetting = value; } /** * <p>The user's preferred MFA setting.</p> */ inline void SetPreferredMfaSetting(Aws::String&& value) { m_preferredMfaSetting = std::move(value); } /** * <p>The user's preferred MFA setting.</p> */ inline void SetPreferredMfaSetting(const char* value) { m_preferredMfaSetting.assign(value); } /** * <p>The user's preferred MFA setting.</p> */ inline GetUserResult& WithPreferredMfaSetting(const Aws::String& value) { SetPreferredMfaSetting(value); return *this;} /** * <p>The user's preferred MFA setting.</p> */ inline GetUserResult& WithPreferredMfaSetting(Aws::String&& value) { SetPreferredMfaSetting(std::move(value)); return *this;} /** * <p>The user's preferred MFA setting.</p> */ inline GetUserResult& WithPreferredMfaSetting(const char* value) { SetPreferredMfaSetting(value); return *this;} /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline const Aws::Vector<Aws::String>& GetUserMFASettingList() const{ return m_userMFASettingList; } /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline void SetUserMFASettingList(const Aws::Vector<Aws::String>& value) { m_userMFASettingList = value; } /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline void SetUserMFASettingList(Aws::Vector<Aws::String>&& value) { m_userMFASettingList = std::move(value); } /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline GetUserResult& WithUserMFASettingList(const Aws::Vector<Aws::String>& value) { SetUserMFASettingList(value); return *this;} /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline GetUserResult& WithUserMFASettingList(Aws::Vector<Aws::String>&& value) { SetUserMFASettingList(std::move(value)); return *this;} /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline GetUserResult& AddUserMFASettingList(const Aws::String& value) { m_userMFASettingList.push_back(value); return *this; } /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline GetUserResult& AddUserMFASettingList(Aws::String&& value) { m_userMFASettingList.push_back(std::move(value)); return *this; } /** * <p>The MFA options that are enabled for the user. The possible values in this * list are <code>SMS_MFA</code> and <code>SOFTWARE_TOKEN_MFA</code>.</p> */ inline GetUserResult& AddUserMFASettingList(const char* value) { m_userMFASettingList.push_back(value); return *this; } private: Aws::String m_username; Aws::Vector<AttributeType> m_userAttributes; Aws::Vector<MFAOptionType> m_mFAOptions; Aws::String m_preferredMfaSetting; Aws::Vector<Aws::String> m_userMFASettingList; }; } // namespace Model } // namespace CognitoIdentityProvider } // namespace Aws
41.983553
140
0.691374
[ "vector", "model" ]
a270eb146db59b2097eca646cedef7d6a6e40bb8
2,267
h
C
src/test/resources/samples/langs/C/elf.h
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
8,271
2015-01-01T15:04:43.000Z
2022-03-31T06:18:14.000Z
src/test/resources/samples/langs/C/elf.h
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
3,238
2015-01-01T14:25:12.000Z
2022-03-30T17:37:51.000Z
src/test/resources/samples/langs/C/elf.h
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
4,070
2015-01-01T11:40:51.000Z
2022-03-31T13:45:53.000Z
#pragma once /* Copyright © 2011 Lukas Martini * * This file is part of Xelix. * * Xelix 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. * * Xelix 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 Xelix. If not, see <http://www.gnu.org/licenses/>. */ #include <lib/generic.h> #include <tasks/scheduler.h> #define ELF_TYPE_NONE 0 #define ELF_TYPE_REL 1 #define ELF_TYPE_EXEC 2 #define ELF_TYPE_DYN 3 #define ELF_TYPE_CORE 4 #define ELF_ARCH_NONE 0 #define ELF_ARCH_386 3 #define ELF_VERSION_CURRENT 1 typedef struct { unsigned char magic[4]; /* Note: There _is_ other stuff in here, but we don't need it */ unsigned char pad[12]; } __attribute__((packed)) elf_ident_t; typedef struct { uint32_t type; uint32_t offset; void* virtaddr; void* physaddr; uint32_t filesize; uint32_t memsize; uint32_t flags; uint32_t alignment; } __attribute__((packed)) elf_program_t; typedef struct { elf_ident_t ident; uint16_t type; /* Object file type */ uint16_t machine; /* Architecture */ uint32_t version; /* Object file version */ void* entry; /* Entry point virtual address */ uint32_t phoff; /* Program header table file offset */ uint32_t shoff; /* Section header table file offset */ uint32_t flags; /* Processor-specific flags */ uint16_t ehsize; /* ELF header size in bytes */ uint16_t phentsize; /* Program header table entry size */ uint16_t phnum; /* Program header table entry count */ uint16_t shentsize; /* Section header table entry size */ uint16_t shnum; /* Section header table entry count */ uint16_t shstrndx; /* Section header string table index */ } __attribute__((packed)) elf_t; task_t* elf_load(elf_t* bin, char* name, char** environ, char** argv, int argc); task_t* elf_load_file(char* path, char** environ, char** argv, int argc);
31.929577
80
0.728275
[ "object" ]
a27515aeaa2debabdb14a03d271fe423d13b19d2
17,841
c
C
git-2.2.1/builtin/fsck.c
daikohunter128/EdamameApp
e702b45ad8ecebd782ffa6650ac2b32f9d17ef34
[ "MIT" ]
null
null
null
git-2.2.1/builtin/fsck.c
daikohunter128/EdamameApp
e702b45ad8ecebd782ffa6650ac2b32f9d17ef34
[ "MIT" ]
3
2020-02-26T00:45:02.000Z
2020-03-04T17:03:58.000Z
git-2.2.1/builtin/fsck.c
daikohunter128/EdamameApp
e702b45ad8ecebd782ffa6650ac2b32f9d17ef34
[ "MIT" ]
null
null
null
#include "builtin.h" #include "cache.h" #include "commit.h" #include "tree.h" #include "blob.h" #include "tag.h" #include "refs.h" #include "pack.h" #include "cache-tree.h" #include "tree-walk.h" #include "fsck.h" #include "parse-options.h" #include "dir.h" #include "progress.h" #include "streaming.h" #define REACHABLE 0x0001 #define SEEN 0x0002 #define HAS_OBJ 0x0004 static int show_root; static int show_tags; static int show_unreachable; static int include_reflogs = 1; static int check_full = 1; static int check_strict; static int keep_cache_objects; static unsigned char head_sha1[20]; static const char *head_points_at; static int errors_found; static int write_lost_and_found; static int verbose; static int show_progress = -1; static int show_dangling = 1; #define ERROR_OBJECT 01 #define ERROR_REACHABLE 02 #define ERROR_PACK 04 #ifdef NO_D_INO_IN_DIRENT #define SORT_DIRENT 0 #define DIRENT_SORT_HINT(de) 0 #else #define SORT_DIRENT 1 #define DIRENT_SORT_HINT(de) ((de)->d_ino) #endif static void objreport(struct object *obj, const char *severity, const char *err, va_list params) { fprintf(stderr, "%s in %s %s: ", severity, typename(obj->type), sha1_to_hex(obj->sha1)); vfprintf(stderr, err, params); fputs("\n", stderr); } __attribute__((format (printf, 2, 3))) static int objerror(struct object *obj, const char *err, ...) { va_list params; va_start(params, err); errors_found |= ERROR_OBJECT; objreport(obj, "error", err, params); va_end(params); return -1; } __attribute__((format (printf, 3, 4))) static int fsck_error_func(struct object *obj, int type, const char *err, ...) { va_list params; va_start(params, err); objreport(obj, (type == FSCK_WARN) ? "warning" : "error", err, params); va_end(params); return (type == FSCK_WARN) ? 0 : 1; } static struct object_array pending; static int mark_object(struct object *obj, int type, void *data) { struct object *parent = data; /* * The only case data is NULL or type is OBJ_ANY is when * mark_object_reachable() calls us. All the callers of * that function has non-NULL obj hence ... */ if (!obj) { /* ... these references to parent->fld are safe here */ printf("broken link from %7s %s\n", typename(parent->type), sha1_to_hex(parent->sha1)); printf("broken link from %7s %s\n", (type == OBJ_ANY ? "unknown" : typename(type)), "unknown"); errors_found |= ERROR_REACHABLE; return 1; } if (type != OBJ_ANY && obj->type != type) /* ... and the reference to parent is safe here */ objerror(parent, "wrong object type in link"); if (obj->flags & REACHABLE) return 0; obj->flags |= REACHABLE; if (!(obj->flags & HAS_OBJ)) { if (parent && !has_sha1_file(obj->sha1)) { printf("broken link from %7s %s\n", typename(parent->type), sha1_to_hex(parent->sha1)); printf(" to %7s %s\n", typename(obj->type), sha1_to_hex(obj->sha1)); errors_found |= ERROR_REACHABLE; } return 1; } add_object_array(obj, NULL, &pending); return 0; } static void mark_object_reachable(struct object *obj) { mark_object(obj, OBJ_ANY, NULL); } static int traverse_one_object(struct object *obj) { int result; struct tree *tree = NULL; if (obj->type == OBJ_TREE) { tree = (struct tree *)obj; if (parse_tree(tree) < 0) return 1; /* error already displayed */ } result = fsck_walk(obj, mark_object, obj); if (tree) free_tree_buffer(tree); return result; } static int traverse_reachable(void) { struct progress *progress = NULL; unsigned int nr = 0; int result = 0; if (show_progress) progress = start_progress_delay(_("Checking connectivity"), 0, 0, 2); while (pending.nr) { struct object_array_entry *entry; struct object *obj; entry = pending.objects + --pending.nr; obj = entry->item; result |= traverse_one_object(obj); display_progress(progress, ++nr); } stop_progress(&progress); return !!result; } static int mark_used(struct object *obj, int type, void *data) { if (!obj) return 1; obj->used = 1; return 0; } /* * Check a single reachable object */ static void check_reachable_object(struct object *obj) { /* * We obviously want the object to be parsed, * except if it was in a pack-file and we didn't * do a full fsck */ if (!(obj->flags & HAS_OBJ)) { if (has_sha1_pack(obj->sha1)) return; /* it is in pack - forget about it */ printf("missing %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1)); errors_found |= ERROR_REACHABLE; return; } } /* * Check a single unreachable object */ static void check_unreachable_object(struct object *obj) { /* * Missing unreachable object? Ignore it. It's not like * we miss it (since it can't be reached), nor do we want * to complain about it being unreachable (since it does * not exist). */ if (!obj->parsed) return; /* * Unreachable object that exists? Show it if asked to, * since this is something that is prunable. */ if (show_unreachable) { printf("unreachable %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1)); return; } /* * "!used" means that nothing at all points to it, including * other unreachable objects. In other words, it's the "tip" * of some set of unreachable objects, usually a commit that * got dropped. * * Such starting points are more interesting than some random * set of unreachable objects, so we show them even if the user * hasn't asked for _all_ unreachable objects. If you have * deleted a branch by mistake, this is a prime candidate to * start looking at, for example. */ if (!obj->used) { if (show_dangling) printf("dangling %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1)); if (write_lost_and_found) { char *filename = git_path("lost-found/%s/%s", obj->type == OBJ_COMMIT ? "commit" : "other", sha1_to_hex(obj->sha1)); FILE *f; if (safe_create_leading_directories(filename)) { error("Could not create lost-found"); return; } if (!(f = fopen(filename, "w"))) die_errno("Could not open '%s'", filename); if (obj->type == OBJ_BLOB) { if (stream_blob_to_fd(fileno(f), obj->sha1, NULL, 1)) die_errno("Could not write '%s'", filename); } else fprintf(f, "%s\n", sha1_to_hex(obj->sha1)); if (fclose(f)) die_errno("Could not finish '%s'", filename); } return; } /* * Otherwise? It's there, it's unreachable, and some other unreachable * object points to it. Ignore it - it's not interesting, and we showed * all the interesting cases above. */ } static void check_object(struct object *obj) { if (verbose) fprintf(stderr, "Checking %s\n", sha1_to_hex(obj->sha1)); if (obj->flags & REACHABLE) check_reachable_object(obj); else check_unreachable_object(obj); } static void check_connectivity(void) { int i, max; /* Traverse the pending reachable objects */ traverse_reachable(); /* Look up all the requirements, warn about missing objects.. */ max = get_max_object_index(); if (verbose) fprintf(stderr, "Checking connectivity (%d objects)\n", max); for (i = 0; i < max; i++) { struct object *obj = get_indexed_object(i); if (obj) check_object(obj); } } static int fsck_obj(struct object *obj) { if (obj->flags & SEEN) return 0; obj->flags |= SEEN; if (verbose) fprintf(stderr, "Checking %s %s\n", typename(obj->type), sha1_to_hex(obj->sha1)); if (fsck_walk(obj, mark_used, NULL)) objerror(obj, "broken links"); if (fsck_object(obj, NULL, 0, check_strict, fsck_error_func)) return -1; if (obj->type == OBJ_TREE) { struct tree *item = (struct tree *) obj; free_tree_buffer(item); } if (obj->type == OBJ_COMMIT) { struct commit *commit = (struct commit *) obj; free_commit_buffer(commit); if (!commit->parents && show_root) printf("root %s\n", sha1_to_hex(commit->object.sha1)); } if (obj->type == OBJ_TAG) { struct tag *tag = (struct tag *) obj; if (show_tags && tag->tagged) { printf("tagged %s %s", typename(tag->tagged->type), sha1_to_hex(tag->tagged->sha1)); printf(" (%s) in %s\n", tag->tag, sha1_to_hex(tag->object.sha1)); } } return 0; } static int fsck_sha1(const unsigned char *sha1) { struct object *obj = parse_object(sha1); if (!obj) { errors_found |= ERROR_OBJECT; return error("%s: object corrupt or missing", sha1_to_hex(sha1)); } obj->flags |= HAS_OBJ; return fsck_obj(obj); } static int fsck_obj_buffer(const unsigned char *sha1, enum object_type type, unsigned long size, void *buffer, int *eaten) { struct object *obj; obj = parse_object_buffer(sha1, type, size, buffer, eaten); if (!obj) { errors_found |= ERROR_OBJECT; return error("%s: object corrupt or missing", sha1_to_hex(sha1)); } obj->flags = HAS_OBJ; return fsck_obj(obj); } /* * This is the sorting chunk size: make it reasonably * big so that we can sort well.. */ #define MAX_SHA1_ENTRIES (1024) struct sha1_entry { unsigned long ino; unsigned char sha1[20]; }; static struct { unsigned long nr; struct sha1_entry *entry[MAX_SHA1_ENTRIES]; } sha1_list; static int ino_compare(const void *_a, const void *_b) { const struct sha1_entry *a = _a, *b = _b; unsigned long ino1 = a->ino, ino2 = b->ino; return ino1 < ino2 ? -1 : ino1 > ino2 ? 1 : 0; } static void fsck_sha1_list(void) { int i, nr = sha1_list.nr; if (SORT_DIRENT) qsort(sha1_list.entry, nr, sizeof(struct sha1_entry *), ino_compare); for (i = 0; i < nr; i++) { struct sha1_entry *entry = sha1_list.entry[i]; unsigned char *sha1 = entry->sha1; sha1_list.entry[i] = NULL; if (fsck_sha1(sha1)) errors_found |= ERROR_OBJECT; free(entry); } sha1_list.nr = 0; } static void add_sha1_list(unsigned char *sha1, unsigned long ino) { struct sha1_entry *entry = xmalloc(sizeof(*entry)); int nr; entry->ino = ino; hashcpy(entry->sha1, sha1); nr = sha1_list.nr; if (nr == MAX_SHA1_ENTRIES) { fsck_sha1_list(); nr = 0; } sha1_list.entry[nr] = entry; sha1_list.nr = ++nr; } static inline int is_loose_object_file(struct dirent *de, char *name, unsigned char *sha1) { if (strlen(de->d_name) != 38) return 0; memcpy(name + 2, de->d_name, 39); return !get_sha1_hex(name, sha1); } static void fsck_dir(int i, char *path) { DIR *dir = opendir(path); struct dirent *de; char name[100]; if (!dir) return; if (verbose) fprintf(stderr, "Checking directory %s\n", path); sprintf(name, "%02x", i); while ((de = readdir(dir)) != NULL) { unsigned char sha1[20]; if (is_dot_or_dotdot(de->d_name)) continue; if (is_loose_object_file(de, name, sha1)) { add_sha1_list(sha1, DIRENT_SORT_HINT(de)); continue; } if (starts_with(de->d_name, "tmp_obj_")) continue; fprintf(stderr, "bad sha1 file: %s/%s\n", path, de->d_name); } closedir(dir); } static int default_refs; static int fsck_handle_reflog_ent(unsigned char *osha1, unsigned char *nsha1, const char *email, unsigned long timestamp, int tz, const char *message, void *cb_data) { struct object *obj; if (verbose) fprintf(stderr, "Checking reflog %s->%s\n", sha1_to_hex(osha1), sha1_to_hex(nsha1)); if (!is_null_sha1(osha1)) { obj = lookup_object(osha1); if (obj) { obj->used = 1; mark_object_reachable(obj); } } obj = lookup_object(nsha1); if (obj) { obj->used = 1; mark_object_reachable(obj); } return 0; } static int fsck_handle_reflog(const char *logname, const unsigned char *sha1, int flag, void *cb_data) { for_each_reflog_ent(logname, fsck_handle_reflog_ent, NULL); return 0; } static int fsck_handle_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data) { struct object *obj; obj = parse_object(sha1); if (!obj) { error("%s: invalid sha1 pointer %s", refname, sha1_to_hex(sha1)); errors_found |= ERROR_REACHABLE; /* We'll continue with the rest despite the error.. */ return 0; } if (obj->type != OBJ_COMMIT && is_branch(refname)) error("%s: not a commit", refname); default_refs++; obj->used = 1; mark_object_reachable(obj); return 0; } static void get_default_heads(void) { if (head_points_at && !is_null_sha1(head_sha1)) fsck_handle_ref("HEAD", head_sha1, 0, NULL); for_each_rawref(fsck_handle_ref, NULL); if (include_reflogs) for_each_reflog(fsck_handle_reflog, NULL); /* * Not having any default heads isn't really fatal, but * it does mean that "--unreachable" no longer makes any * sense (since in this case everything will obviously * be unreachable by definition. * * Showing dangling objects is valid, though (as those * dangling objects are likely lost heads). * * So we just print a warning about it, and clear the * "show_unreachable" flag. */ if (!default_refs) { fprintf(stderr, "notice: No default references\n"); show_unreachable = 0; } } static void fsck_object_dir(const char *path) { int i; struct progress *progress = NULL; if (verbose) fprintf(stderr, "Checking object directory\n"); if (show_progress) progress = start_progress(_("Checking object directories"), 256); for (i = 0; i < 256; i++) { static char dir[4096]; sprintf(dir, "%s/%02x", path, i); fsck_dir(i, dir); display_progress(progress, i+1); } stop_progress(&progress); fsck_sha1_list(); } static int fsck_head_link(void) { int flag; int null_is_error = 0; if (verbose) fprintf(stderr, "Checking HEAD link\n"); head_points_at = resolve_ref_unsafe("HEAD", 0, head_sha1, &flag); if (!head_points_at) return error("Invalid HEAD"); if (!strcmp(head_points_at, "HEAD")) /* detached HEAD */ null_is_error = 1; else if (!starts_with(head_points_at, "refs/heads/")) return error("HEAD points to something strange (%s)", head_points_at); if (is_null_sha1(head_sha1)) { if (null_is_error) return error("HEAD: detached HEAD points at nothing"); fprintf(stderr, "notice: HEAD points to an unborn branch (%s)\n", head_points_at + 11); } return 0; } static int fsck_cache_tree(struct cache_tree *it) { int i; int err = 0; if (verbose) fprintf(stderr, "Checking cache tree\n"); if (0 <= it->entry_count) { struct object *obj = parse_object(it->sha1); if (!obj) { error("%s: invalid sha1 pointer in cache-tree", sha1_to_hex(it->sha1)); return 1; } obj->used = 1; mark_object_reachable(obj); if (obj->type != OBJ_TREE) err |= objerror(obj, "non-tree in cache-tree"); } for (i = 0; i < it->subtree_nr; i++) err |= fsck_cache_tree(it->down[i]->cache_tree); return err; } static char const * const fsck_usage[] = { N_("git fsck [options] [<object>...]"), NULL }; static struct option fsck_opts[] = { OPT__VERBOSE(&verbose, N_("be verbose")), OPT_BOOL(0, "unreachable", &show_unreachable, N_("show unreachable objects")), OPT_BOOL(0, "dangling", &show_dangling, N_("show dangling objects")), OPT_BOOL(0, "tags", &show_tags, N_("report tags")), OPT_BOOL(0, "root", &show_root, N_("report root nodes")), OPT_BOOL(0, "cache", &keep_cache_objects, N_("make index objects head nodes")), OPT_BOOL(0, "reflogs", &include_reflogs, N_("make reflogs head nodes (default)")), OPT_BOOL(0, "full", &check_full, N_("also consider packs and alternate objects")), OPT_BOOL(0, "strict", &check_strict, N_("enable more strict checking")), OPT_BOOL(0, "lost-found", &write_lost_and_found, N_("write dangling objects in .git/lost-found")), OPT_BOOL(0, "progress", &show_progress, N_("show progress")), OPT_END(), }; int cmd_fsck(int argc, const char **argv, const char *prefix) { int i, heads; struct alternate_object_database *alt; errors_found = 0; check_replace_refs = 0; argc = parse_options(argc, argv, prefix, fsck_opts, fsck_usage, 0); if (show_progress == -1) show_progress = isatty(2); if (verbose) show_progress = 0; if (write_lost_and_found) { check_full = 1; include_reflogs = 0; } fsck_head_link(); fsck_object_dir(get_object_directory()); prepare_alt_odb(); for (alt = alt_odb_list; alt; alt = alt->next) { char namebuf[PATH_MAX]; int namelen = alt->name - alt->base; memcpy(namebuf, alt->base, namelen); namebuf[namelen - 1] = 0; fsck_object_dir(namebuf); } if (check_full) { struct packed_git *p; uint32_t total = 0, count = 0; struct progress *progress = NULL; prepare_packed_git(); if (show_progress) { for (p = packed_git; p; p = p->next) { if (open_pack_index(p)) continue; total += p->num_objects; } progress = start_progress(_("Checking objects"), total); } for (p = packed_git; p; p = p->next) { /* verify gives error messages itself */ if (verify_pack(p, fsck_obj_buffer, progress, count)) errors_found |= ERROR_PACK; count += p->num_objects; } stop_progress(&progress); } heads = 0; for (i = 0; i < argc; i++) { const char *arg = argv[i]; unsigned char sha1[20]; if (!get_sha1(arg, sha1)) { struct object *obj = lookup_object(sha1); /* Error is printed by lookup_object(). */ if (!obj) continue; obj->used = 1; mark_object_reachable(obj); heads++; continue; } error("invalid parameter: expected sha1, got '%s'", arg); } /* * If we've not been given any explicit head information, do the * default ones from .git/refs. We also consider the index file * in this case (ie this implies --cache). */ if (!heads) { get_default_heads(); keep_cache_objects = 1; } if (keep_cache_objects) { read_cache(); for (i = 0; i < active_nr; i++) { unsigned int mode; struct blob *blob; struct object *obj; mode = active_cache[i]->ce_mode; if (S_ISGITLINK(mode)) continue; blob = lookup_blob(active_cache[i]->sha1); if (!blob) continue; obj = &blob->object; obj->used = 1; mark_object_reachable(obj); } if (active_cache_tree) fsck_cache_tree(active_cache_tree); } check_connectivity(); return errors_found; }
24.30654
102
0.672664
[ "object" ]
a27c8a368c0d2e0e5a1fb08b24321fa431d216fb
8,795
c
C
jni/foe_fuseball.c
tomasskare/cyclone2000
2d7d88c749010e8f7b7b62973287efa75f329c43
[ "MIT" ]
null
null
null
jni/foe_fuseball.c
tomasskare/cyclone2000
2d7d88c749010e8f7b7b62973287efa75f329c43
[ "MIT" ]
null
null
null
jni/foe_fuseball.c
tomasskare/cyclone2000
2d7d88c749010e8f7b7b62973287efa75f329c43
[ "MIT" ]
null
null
null
#include <jni.h> #include <android/log.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include <GLES2/gl2.h> #include "debug.h" #include "native_main.h" #include "engine.h" #include "matrix.h" #include "shaders.h" #include "gamearea.h" #include "foe_fuseball.h" #include "score.h" #include "banner.h" #include "object.h" #include "game_graphics/foe_fuseball_data.h" typedef struct foe_fuseball_s { object_t *ga_obj; int edge, toedge, section; double last_move, timer; int armflip[5]; double last_flip; GLfloat tx, ty, tz; GLfloat totx, toty; GLfloat fromtx, fromty; GLfloat toangle, fromangle; GLfloat angle, rotate; GLfloat offset; int num_indices; } foe_fuseball_t; static int foe_fuseball_get_section(foe_fuseball_t *fb, int oedge) { int edge = oedge == -1 ? fb->edge : oedge; if(fb->section != -1) return fb->section; else return gamearea_section_by_edge(fb->ga_obj, edge); } static void foe_fuseball_destroy(object_t *obj) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; int i; free(fb); for(i = 0 ; i < obj->num_globjs ; i++) engine_globject_free(GLOBJ(i)); free(obj->globjs); free(obj); } static int foe_fuseball_update(object_t *obj, uint64_t prev_msec, uint64_t msec) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; float diff = msec - prev_msec; int i; DEBUG(DEBUG_UPDATE, " "); if(fb->last_flip + 50 < msec) { i = rand() % 5; fb->armflip[i] = !fb->armflip[i]; fb->last_flip = msec; } fb->rotate -= diff * 360 / 4000; while(fb->rotate < 0.0) fb->rotate += 360.0; if(!FLAG_TST(obj->flags, OBJECT_F_FOE_EDGE)) { if(fb->section == -1) fb->tz += diff / 900; // Change behaviour at rim if(fb->tz >= GAMEAREA_FOE_EDGE_ZPOS) { fb->tz = GAMEAREA_FOE_EDGE_ZPOS; engine_object_onedge(obj); } } else { fb->offset -= diff / 2500; if(fb->offset < 0.0) fb->offset = 0.0; // Fuseball fries on both sides of the edge it's on. // If it's moving, fries on the section. if(engine_collision_detect(obj, OBJECT_F_PLAYER, foe_fuseball_get_section(fb, -1), -1.0, (double)fb->tz)) return 0; // If on edge, check the other section too. if(fb->section == -1) { int oedge = gamearea_edge_offset_get(fb->ga_obj, fb->edge, -1); if(engine_collision_detect(obj, OBJECT_F_PLAYER, foe_fuseball_get_section(fb, oedge), -1.0, (double)fb->tz)) return 0; } } if(fb->section != -1) { GLfloat dtx = (fb->totx - fb->fromtx) * diff / 800; GLfloat dty = (fb->toty - fb->fromty) * diff / 800; GLfloat angdiff = fb->toangle - fb->fromangle; GLfloat dang; fb->timer += diff; if(angdiff > 180.0) angdiff -= 360.0; else if(angdiff < -180.0) angdiff = -angdiff - 360; dang = angdiff * diff / 800; if(fabs(fb->totx - fb->tx) < fabs(dtx) || fabs(fb->toty - fb->ty) < fabs(dty)) { fb->tx = fb->totx; fb->ty = fb->toty; fb->angle = fb->toangle; fb->edge = fb->toedge; fb->section = -1; } else { fb->tx += dtx; fb->ty += dty; fb->angle += dang; } } if(fb->last_move + 2500 < msec) { // Start move toward player. int closed = gamearea_closed_get(fb->ga_obj); int num_edges = gamearea_num_edges_get(fb->ga_obj); int player_section = gamearea_player_section_get(fb->ga_obj); int move_dir = player_section - gamearea_section_by_edge(fb->ga_obj, fb->edge); if(closed && (move_dir > num_edges / 2 || move_dir < -num_edges / 2)) move_dir = -move_dir; if(move_dir < 0) move_dir = -1; else move_dir = 1; fb->toedge = gamearea_edge_offset_get(fb->ga_obj, fb->edge, move_dir); fb->fromtx = fb->tx; fb->fromty = fb->ty; gamearea_edge_pos_get(fb->ga_obj, fb->toedge, &fb->totx, &fb->toty); fb->fromangle = fb->angle; fb->toangle = gamearea_edge_angle_get(fb->ga_obj, fb->toedge); fb->section = gamearea_section_by_edge(fb->ga_obj, (move_dir < 0 ? fb->toedge : fb->edge)); fb->timer = 0.0; fb->last_move = msec; } return 1; } static void foe_fuseball_draw(object_t *obj) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; float tmpmtx[16]; int i; DEBUG(DEBUG_DRAW, " "); matrix_set_translate(tmpmtx, fb->tx, fb->ty, fb->tz); matrix_rotate(tmpmtx, MTX_AXIS_Z, fb->angle); matrix_translate(tmpmtx, 0.0f, fb->offset, 0.0f); for(i = 0 ; i < 5 ; i++) { int globj = fb->armflip[i] ? i : i + 5; matrix_rotate_to(GLOBJ(globj)->mtx_model, tmpmtx, MTX_AXIS_Z, fb->rotate + 72.0f * i); engine_globject_draw_prepare(GLOBJ(globj)); glDrawElements(GL_TRIANGLES, fb->num_indices, GL_UNSIGNED_SHORT, 0); engine_globject_draw_cleanup(GLOBJ(globj)); } } static int foe_fuseball_collision(object_t *obj, object_t *srcobj, int section, double minz, double maxz) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; // Only hit when moving between edges and in the middle of the section. if(fb->section != section) return 0; if(fb->timer < 350.0 || fb->timer > 450.0) return 0; if((double)fb->tz < minz || (double)fb->tz > maxz) return 0; return 1; } static int foe_fuseball_hit(object_t *obj, object_t *srcobj) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; object_t *ban; banner_coords_t *bn; int rnd; /* Randomize score 250, 500 or 750. */ rnd = rand() % 3; bn = &score_banners[rnd]; score_increase(250 * (rnd + 1)); ban = banner_create(fb->ga_obj, native_tex_id(TEX_FUSEBALL_SCORE), 0, fb->tx, fb->ty, fb->tz, bn->tx1, bn->tx2, bn->ty1, bn->ty2, bn->w, bn->h, BANNER_F_DONT_COMPENSATE); engine_object_add(ban, 2); native_callback(CALLBACK_PLAY_SOUND, SOUND_EXPLOSION, 0, 0); return 1; } static void foe_fuseball_posget(object_t *obj, int *section, double *zpos) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; if(section) *section = foe_fuseball_get_section(fb, -1); if(zpos) *zpos = fb->tz; } static void foe_fuseball_reinit(object_t *obj, int doalloc) { foe_fuseball_t *fb = (foe_fuseball_t *)obj->object; int i; /* First five are left flip, other five are right flip. */ for(i = 0 ; i < 5 ; i++) { if(doalloc) { engine_globject_alloc(GLOBJ(i)); engine_globject_alloc(GLOBJ(i + 5)); } if(gfx_details >= GFX_DETAILS_HIGH) { engine_globject_init_ex(GLOBJ(i), SHADERS_LIGHT1, high_num_vertices, high_l_vertices, 0, high_num_vertices, high_l_normals, 0, high_num_vertices, high_colours[i], 0, high_num_indices, high_l_indices, 0); engine_globject_init_ex(GLOBJ(i + 5), SHADERS_LIGHT1, high_num_vertices, high_r_vertices, 0, high_num_vertices, high_r_normals, 0, high_num_vertices, high_colours[i], 0, high_num_indices, high_r_indices, 0); fb->num_indices = high_num_indices; } else { engine_globject_init(GLOBJ(i), SHADERS_LIGHT1, low_num_vertices, low_l_vertices, 0, low_num_vertices, low_colours[i], 0, low_num_indices, low_l_indices, 0); engine_globject_init(GLOBJ(i + 5), SHADERS_LIGHT1, low_num_vertices, low_r_vertices, 0, low_num_vertices, low_colours[i], 0, low_num_indices, low_r_indices, 0); fb->num_indices = low_num_indices; } } } object_t *foe_fuseball_create(object_t *ga_obj, int edge, GLfloat zpos) { object_t *obj; foe_fuseball_t *fb; int i; DEBUG(DEBUG_CREATE, " "); fb = calloc(1, sizeof(*fb)); obj = calloc(1, sizeof(*obj)); obj->destroy_cb = foe_fuseball_destroy; obj->update_cb = foe_fuseball_update; obj->draw_cb = foe_fuseball_draw; obj->collision_cb = foe_fuseball_collision; obj->hit_cb = foe_fuseball_hit; obj->posget_cb = foe_fuseball_posget; obj->reinit_cb = foe_fuseball_reinit; obj->object = fb; FLAG_SET(obj->flags, OBJECT_F_FOE); FLAG_SET(obj->flags, OBJECT_F_FOE_FRIER); /* Five colours, two flips */ obj->num_globjs = 5 * 2; obj->globjs = calloc(obj->num_globjs, sizeof(*obj->globjs)); foe_fuseball_reinit(obj, 1); for(i = 0 ; i < 5 * 2 ; i++) { GLOBJ(i)->alpha = 1.0f; GLOBJ(i)->spec_colour[0] = 0.8f; GLOBJ(i)->spec_colour[1] = 0.8f; GLOBJ(i)->spec_colour[2] = 0.8f; GLOBJ(i)->spec_colour[3] = 1.0f; GLOBJ(i)->spec_shininess = 16.0f; GLOBJ(i)->light1 = &engine_light1; } fb->ga_obj = ga_obj; fb->edge = edge; gamearea_edge_pos_get(fb->ga_obj, fb->edge, &fb->tx, &fb->ty); fb->tz = zpos; fb->angle = gamearea_edge_angle_get(fb->ga_obj, fb->edge); fb->toedge = fb->edge; fb->section = -1; fb->offset = 0.22f; return obj; }
25.200573
80
0.636953
[ "object" ]
a27da4809c14be31bd3ce01c5bc7934ce57500fa
4,208
h
C
ppapi/proxy/ppb_graphics_3d_proxy.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
2
2020-06-10T07:15:26.000Z
2020-12-13T19:44:12.000Z
ppapi/proxy/ppb_graphics_3d_proxy.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
ppapi/proxy/ppb_graphics_3d_proxy.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PPAPI_PROXY_PPB_GRAPHICS_3D_PROXY_H_ #define PPAPI_PROXY_PPB_GRAPHICS_3D_PROXY_H_ #include <vector> #include "base/shared_memory.h" #include "gpu/command_buffer/common/command_buffer.h" #include "ppapi/c/pp_graphics_3d.h" #include "ppapi/c/pp_instance.h" #include "ppapi/proxy/interface_proxy.h" #include "ppapi/proxy/proxy_completion_callback_factory.h" #include "ppapi/proxy/serialized_structs.h" #include "ppapi/shared_impl/ppb_graphics_3d_shared.h" #include "ppapi/shared_impl/resource.h" #include "ppapi/utility/completion_callback_factory.h" namespace ppapi { class HostResource; namespace proxy { class Graphics3D : public PPB_Graphics3D_Shared { public: explicit Graphics3D(const HostResource& resource); virtual ~Graphics3D(); bool Init(gpu::gles2::GLES2Implementation* share_gles2); // Graphics3DTrusted API. These are not implemented in the proxy. virtual PP_Bool InitCommandBuffer() OVERRIDE; virtual PP_Bool SetGetBuffer(int32_t shm_id) OVERRIDE; virtual PP_Graphics3DTrustedState GetState() OVERRIDE; virtual PP_Bool Flush(int32_t put_offset) OVERRIDE; virtual PP_Graphics3DTrustedState FlushSync(int32_t put_offset) OVERRIDE; virtual int32_t CreateTransferBuffer(uint32_t size) OVERRIDE; virtual PP_Bool DestroyTransferBuffer(int32_t id) OVERRIDE; virtual PP_Bool GetTransferBuffer(int32_t id, int* shm_handle, uint32_t* shm_size) OVERRIDE; virtual PP_Graphics3DTrustedState FlushSyncFast( int32_t put_offset, int32_t last_known_get) OVERRIDE; protected: // Graphics3DImpl overrides. virtual gpu::CommandBuffer* GetCommandBuffer() OVERRIDE; virtual int32 DoSwapBuffers() OVERRIDE; private: scoped_ptr<gpu::CommandBuffer> command_buffer_; DISALLOW_COPY_AND_ASSIGN(Graphics3D); }; class PPB_Graphics3D_Proxy : public InterfaceProxy { public: PPB_Graphics3D_Proxy(Dispatcher* dispatcher); virtual ~PPB_Graphics3D_Proxy(); static PP_Resource CreateProxyResource( PP_Instance instance, PP_Resource share_context, const int32_t* attrib_list); // InterfaceProxy implementation. virtual bool OnMessageReceived(const IPC::Message& msg); static const ApiID kApiID = API_ID_PPB_GRAPHICS_3D; private: void OnMsgCreate(PP_Instance instance, HostResource share_context, const std::vector<int32_t>& attribs, HostResource* result); void OnMsgInitCommandBuffer(const HostResource& context); void OnMsgSetGetBuffer(const HostResource& context, int32 id); void OnMsgGetState(const HostResource& context, gpu::CommandBuffer::State* state, bool* success); void OnMsgFlush(const HostResource& context, int32 put_offset, int32 last_known_get, gpu::CommandBuffer::State* state, bool* success); void OnMsgAsyncFlush(const HostResource& context, int32 put_offset); void OnMsgCreateTransferBuffer(const HostResource& context, int32 size, int32* id); void OnMsgDestroyTransferBuffer(const HostResource& context, int32 id); void OnMsgGetTransferBuffer(const HostResource& context, int32 id, ppapi::proxy::SerializedHandle* transfer_buffer); void OnMsgSwapBuffers(const HostResource& context); // Renderer->plugin message handlers. void OnMsgSwapBuffersACK(const HostResource& context, int32_t pp_error); void SendSwapBuffersACKToPlugin(int32_t result, const HostResource& context); ProxyCompletionCallbackFactory<PPB_Graphics3D_Proxy> callback_factory_; DISALLOW_COPY_AND_ASSIGN(PPB_Graphics3D_Proxy); }; } // namespace proxy } // namespace ppapi #endif // PPAPI_PROXY_PPB_GRAPHICS_3D_PROXY_H_
35.361345
79
0.70366
[ "vector" ]
a27ecab92d281f24feb26120d7cb110a800bf61c
2,287
h
C
ugene/src/corelibs/U2Remote/src/RemoteMachineScanDialogImpl.h
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Remote/src/RemoteMachineScanDialogImpl.h
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Remote/src/RemoteMachineScanDialogImpl.h
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * 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. */ #ifndef _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_ #define _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_ #include <QtCore/QTimer> #include <QtGui/QDialog> #include <U2Remote/RemoteMachine.h> #include <ui/ui_RemoteMachineScanDialog.h> namespace U2 { typedef QList< RemoteMachineSettings * > RemoteMachineScanDialogModel; class RemoteMachineScanDialogImpl : public QDialog, public Ui::RemoteMachineScanDialog { Q_OBJECT public: static const int SCAN_UPDATE_TIME = 500; /* 0.5 seconds */ public: RemoteMachineScanDialogImpl(); ~RemoteMachineScanDialogImpl(); RemoteMachineScanDialogModel getModel() const; private: void addMachines( const QList< RemoteMachineSettings* > newMachines ); void addMachine( RemoteMachineSettings * machine ); void addNextMachineToTable( RemoteMachineSettings * ); void cleanup(); bool hasSameMachineInTheList( RemoteMachineSettings* ) const; void resizeTable(); private slots: void sl_cancelPushButtonClicked(); void sl_okPushButtonClicked(); void sl_startScan( const QString & protoId ); void sl_updatePushButtonClicked(); private: RemoteMachineScanDialogModel model; /* machines by order as in the table */ QList< RemoteMachineScanner * > runningScanners; QTimer updateTimer; }; // RemoteMachineScanDialogImpl } // U2 #endif // _U2_REMOTE_MACHINE_SCAN_DIALOG_IMPL_H_
32.671429
88
0.737648
[ "model" ]
a2861cc653c6004b33326d2dd3aa78b466163188
1,902
h
C
DIYDOOM/Notes014/src/DIYDoom/ViewRenderer.h
amroibrahim/DIYDoom
8802a38917725c0e7afee13d77813aaa3b211410
[ "MIT" ]
317
2019-06-20T21:36:20.000Z
2022-03-04T12:59:48.000Z
DIYDOOM/Notes014/src/DIYDoom/ViewRenderer.h
amroibrahim/DIYDoom
8802a38917725c0e7afee13d77813aaa3b211410
[ "MIT" ]
7
2019-08-18T05:01:54.000Z
2020-11-23T05:10:25.000Z
DIYDOOM/Notes014/src/DIYDoom/ViewRenderer.h
amroibrahim/DIYDoom
8802a38917725c0e7afee13d77813aaa3b211410
[ "MIT" ]
19
2019-06-21T04:06:17.000Z
2022-01-06T23:29:56.000Z
#pragma once #include <list> #include <map> #include <string> #include <SDL.h> #include "DataTypes.h" #include "Angle.h" class Map; class Player; class ViewRenderer { public: ViewRenderer(SDL_Renderer *pRenderer); ~ViewRenderer(); void Init(Map *pMap, Player *pPlayer); void Render(bool IsAutomap); void AddWallInFOV(Seg &seg, Angle V1Angle, Angle V2Angle, Angle V1AngleFromPlayer, Angle V2AngleFromPlayer); void InitFrame(); void SetDrawColor(int R, int G, int B); void DrawRect(int X1, int Y1, int X2, int Y2); void DrawLine(int X1, int Y1, int X2, int Y2); protected: struct SolidSegmentRange { int XStart; int XEnd; }; void RenderAutoMap(); void Render3DView(); void ClipSolidWalls(Seg &seg, int V1XScreen, int V2XScreen, Angle V1Angle, Angle V2Angle); void StoreWallRange(Seg &seg, int V1XScreen, int V2XScreen, Angle V1Angle, Angle V2Angle); void CalculateWallHeightSimple(Seg &seg, int V1XScreen, int V2XScreen, Angle V1Angle, Angle V2Angle); void CalculateCeilingFloorHeight(Seg &seg, int &VXScreen, float &DistanceToV, float &CeilingVOnScreen, float &FloorVOnScreen); void PartialSeg(Seg &seg, Angle &V1Angle, Angle &V2Angle, float &DistanceToV1, bool IsLeftSide); void RenderSolidWall(Seg &seg, int XStart, int XStop); int AngleToScreen(Angle angle); int RemapXToScreen(int XMapPosition); int RemapYToScreen(int YMapPosition); int m_iRenderXSize; int m_iRenderYSize; int m_iAutoMapScaleFactor; int m_iDistancePlayerToScreen; int m_HalfScreenWidth; int m_HalfScreenHeight; SDL_Color GetWallColor(std::string textureName); Map *m_pMap; Player *m_pPlayer; SDL_Renderer *m_pRenderer; std::list<SolidSegmentRange> m_SolidWallRanges; std::map<std::string, SDL_Color> m_WallColor; std::map<int, Angle> m_ScreenXToAngle; };
27.565217
130
0.713985
[ "render" ]
a287aa9feef6d0581d3f59d8f57aa1029d962967
5,452
h
C
generation/WinSDK/RecompiledIdlHeaders/winrt/activation.h
forksnd/win32metadata
3e92612032578896ca3eebd543701c97a95d5214
[ "MIT" ]
984
2021-01-21T17:39:07.000Z
2022-03-30T16:29:34.000Z
generation/WinSDK/RecompiledIdlHeaders/winrt/activation.h
forksnd/win32metadata
3e92612032578896ca3eebd543701c97a95d5214
[ "MIT" ]
684
2021-01-21T20:24:26.000Z
2022-03-31T23:06:50.000Z
generation/WinSDK/RecompiledIdlHeaders/winrt/activation.h
forksnd/win32metadata
3e92612032578896ca3eebd543701c97a95d5214
[ "MIT" ]
65
2021-01-21T18:21:34.000Z
2022-03-24T05:08:12.000Z
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.01.0626 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __activation_h__ #define __activation_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #ifndef DECLSPEC_XFGVIRT #if _CONTROL_FLOW_GUARD_XFG #define DECLSPEC_XFGVIRT(base, func) __declspec(xfg_virtual(base, func)) #else #define DECLSPEC_XFGVIRT(base, func) #endif #endif /* Forward Declarations */ #ifndef __IActivationFactory_FWD_DEFINED__ #define __IActivationFactory_FWD_DEFINED__ typedef interface IActivationFactory IActivationFactory; #endif /* __IActivationFactory_FWD_DEFINED__ */ /* header files for imported files */ #include "inspectable.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_activation_0000_0000 */ /* [local] */ //+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (c) Microsoft Corporation. All rights reserved. // //-------------------------------------------------------------------------- #if ( _MSC_VER >= 1020 ) #pragma once #endif extern RPC_IF_HANDLE __MIDL_itf_activation_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_activation_0000_0000_v0_0_s_ifspec; #ifndef __IActivationFactory_INTERFACE_DEFINED__ #define __IActivationFactory_INTERFACE_DEFINED__ /* interface IActivationFactory */ /* [unique][uuid][object] */ typedef /* [unique] */ __RPC_unique_pointer IActivationFactory *PACTIVATIONFACTORY; EXTERN_C const IID IID_IActivationFactory; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("00000035-0000-0000-C000-000000000046") IActivationFactory : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE ActivateInstance( /* [out] */ __RPC__deref_out_opt IInspectable **instance) = 0; }; #else /* C style interface */ typedef struct IActivationFactoryVtbl { BEGIN_INTERFACE DECLSPEC_XFGVIRT(IUnknown, QueryInterface) HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IActivationFactory * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); DECLSPEC_XFGVIRT(IUnknown, AddRef) ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IActivationFactory * This); DECLSPEC_XFGVIRT(IUnknown, Release) ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IActivationFactory * This); DECLSPEC_XFGVIRT(IInspectable, GetIids) HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in IActivationFactory * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); DECLSPEC_XFGVIRT(IInspectable, GetRuntimeClassName) HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in IActivationFactory * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); DECLSPEC_XFGVIRT(IInspectable, GetTrustLevel) HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in IActivationFactory * This, /* [out] */ __RPC__out TrustLevel *trustLevel); DECLSPEC_XFGVIRT(IActivationFactory, ActivateInstance) HRESULT ( STDMETHODCALLTYPE *ActivateInstance )( __RPC__in IActivationFactory * This, /* [out] */ __RPC__deref_out_opt IInspectable **instance); END_INTERFACE } IActivationFactoryVtbl; interface IActivationFactory { CONST_VTBL struct IActivationFactoryVtbl *lpVtbl; }; #ifdef COBJMACROS #define IActivationFactory_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IActivationFactory_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IActivationFactory_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IActivationFactory_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define IActivationFactory_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define IActivationFactory_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define IActivationFactory_ActivateInstance(This,instance) \ ( (This)->lpVtbl -> ActivateInstance(This,instance) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IActivationFactory_INTERFACE_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
26.595122
98
0.684703
[ "object" ]
a287c9079fa327b7b96974b4d80fbeb16d9388b4
2,737
h
C
Example/Pods/Headers/Public/Tempo_ios_sdk/CartoMobileSDK/vectorelements/Text.h
jesusgeographica/pruebaSDK
329f6b27674137fda682cd1e974c2bb6b5901d99
[ "MIT" ]
null
null
null
Example/Pods/Headers/Public/Tempo_ios_sdk/CartoMobileSDK/vectorelements/Text.h
jesusgeographica/pruebaSDK
329f6b27674137fda682cd1e974c2bb6b5901d99
[ "MIT" ]
null
null
null
Example/Pods/Headers/Public/Tempo_ios_sdk/CartoMobileSDK/vectorelements/Text.h
jesusgeographica/pruebaSDK
329f6b27674137fda682cd1e974c2bb6b5901d99
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_TEXT_H_ #define _CARTO_TEXT_H_ #include "vectorelements/Label.h" #include <memory> #include <string> namespace carto { class TextStyle; /** * A text element that can be displayed on the map. */ class Text : public Label { public: /** * Constructs a Text object with the specified style and attaches it to a billboard element. * @param baseBillboard The billboard this text label will be attached to. * @param style The style that defines what this text label looks like. * @param text The text to be displayed. */ Text(const std::shared_ptr<Billboard>& baseBillboard, const std::shared_ptr<TextStyle>& style, const std::string& text); /** * Constructs a Text object from a geometry object and a style. * @param geometry The geometry object that defines the location of this text label. * @param style The style that defines what this text label looks like. * @param text The text to be displayed. */ Text(const std::shared_ptr<Geometry>& geometry, const std::shared_ptr<TextStyle>& style, const std::string& text); /** * Constructs a Text object from a map position and a style. * @param pos The map position that defines the location of this text label. * @param style The style that defines what this text label looks like. * @param text The text to be displayed. */ Text(const MapPos& pos, const std::shared_ptr<TextStyle>& style, const std::string& text); virtual ~Text(); virtual std::shared_ptr<Bitmap> drawBitmap(float dpToPX) const; /** * Returns the display text. * @return The display text. */ std::string getText() const; /** * Sets the display text. * @param text The text to be displayed. */ void setText(const std::string& text); /** * Returns the style of this text label. * @return The style that defines what this text label looks like. */ std::shared_ptr<TextStyle> getStyle() const; /** * Sets the style for this text label. * @param style The new style that defines what this text label looks like. */ void setStyle(const std::shared_ptr<TextStyle>& style); private: static const int MAX_CANVAS_SIZE = 8192; std::shared_ptr<TextStyle> _style; std::string _text; }; } #endif
33.790123
125
0.621483
[ "geometry", "object" ]
a288376e6dc690caec02dbfcf4ca98b0a0a44ef9
7,522
h
C
CosBase/include/cos/cos/coscls.h
zhuyadong/COS
0056f1b42120614ec25331d9a40349390c1d03fb
[ "Apache-2.0" ]
292
2015-01-03T08:06:47.000Z
2022-03-20T18:28:33.000Z
CosBase/include/cos/cos/coscls.h
devel-chm/COS
66adcdae7292d384f4ec3034df1236db9c29ee8d
[ "Apache-2.0" ]
25
2015-07-14T13:52:59.000Z
2019-04-23T12:08:52.000Z
CosBase/include/cos/cos/coscls.h
devel-chm/COS
66adcdae7292d384f4ec3034df1236db9c29ee8d
[ "Apache-2.0" ]
44
2015-09-18T09:09:18.000Z
2022-03-20T18:28:11.000Z
#ifndef COS_COS_COSCLS_H #define COS_COS_COSCLS_H /** * C Object System * COS core classes * * Copyright 2006+ Laurent Deniau <laurent.deniau@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef COS_COS_COS_H #error "COS: use <cos/cos/cos.h> instead of <cos/cos/coscls.h>" #endif /* NOTE-USER: core class hierarchy COS classes, meta classes and property meta classes hierarchy follows the principle of 'uniform object oriented programming' a-la SmallTalk (i.e. everything-is-an-object) and the 'safe metaclass compatibility model' (see "Safe MetaClass Programming", OOPSLA'98). 1) Behaviors are Objects 2) Classes and Generics are Behaviors 3) Meta classes are Classes 4) Property classes are Meta classes Legend: -> means 'subclass of' Class => means 'instance of' ^ | o------o NIL +----------->| mAny |===========>v ^ | o------o v | | ^ v o-----o o-------o | v | Any |============>| pmAny |============|==========>v v o-----o o-------o | v v ^ o---------o v v | +---------->| mObject |======v==>v | | o---------o v v | | ^ v v o--------o o----------o | v v | Object |========>| pmObject |===========|==========>v v o--------o o----------o | v v ^ o-----------o v v | +--------->| mBehavior |=====v==>v | | o-----------o v v | | ^ v v o----------o o------------o | v v | Behavior |======>| pmBehavior |==========|==========>v v o----------o o------------o | v v ^ o--------o v v | +---------->| mClass |=======v==>v | | o--------o v v | | ^ v v o-------o o---------o | v v | Class |==========>| pmClass |===========|==========>v v o-------o o---------o | v v ^ o------------o v v | +-------->| mMetaClass |=====v==>v | | o------------o v v | | ^ v v o-----------o o-------------o | v v ========>| MetaClass |======>| pmMetaClass |=========|==========>v v ^ o-----------o o-------------o | v v ^ ^ o----------------o v v ^ | +------->| mPropMetaClass |==v==>v ^ | | o----------------o v v ^ | | v v ^ o---------------o o-----------------o v v ^ ===>| PropMetaClass |===>| pmPropMetaClass |=================>v v ^ ^ o---------------o o-----------------o v v ^ ^ v v ^ ^<============================================================X v ^ ^ v ^<===============================================================^===X ^ ^ Class ^ ^ ^ ^ ^ | ^ ^ o------o ^ ^ NIL +------------>| mNil |=======^==>^ ^ | o------o ^ ^ | | ^ ^ ^ o-----o o-------o | ^ ^ | Nil |============>| pmNil |============|==========>^ ^ o-----o o-------o | ^ ^ ^ o-----------o ^ ^ | +--------->| mProperty |=====^==>^ | | o-----------o ^ ^ | | ^ ^ o----------o o------------o ^ ^ | Property |======>| pmProperty |=====================>^ ^ o----------o o------------o */ COS_CLS_DEF(Any, _) COS_CLS_END COS_CLS_DEF(Object, Any) // root of most objects COS_CLS_END COS_CLS_DEF(Behavior, Object) /* id is storing cryptic information (LSB->MSB): u27 tag {1..134217727} (unique) u5 rnk {0..31} (class rank) OR {1..5} (generic rank) */ U32 id; U32 line; STR file; COS_CLS_END COS_CLS_DEF(Generic, Behavior) STR str; STR sig; struct cos_generic_rcvinfo *rcvinfo; struct cos_generic_arginfo *arginfo; U16 argsize; U16 retsize; U32 mth; U32 info; // store cryptic information, see cos/cos/generic.h COS_CLS_END COS_CLS_DEF(Class, Behavior) STR str; U32 isz; struct Class* spr; struct Class* cls; U32 prp[2]; COS_CLS_END COS_CLS_DEF(Method, Object) U32 line; STR file; struct Generic* gen; U32 info; // store cryptic information, see cos/cos/method.h U32 arnd; COS_CLS_END COS_CLS_DEF(Method1, Method) IMP1 fct; struct Class* cls[1]; COS_CLS_END COS_CLS_DEF(Method2, Method) IMP2 fct; struct Class* cls[2]; COS_CLS_END COS_CLS_DEF(Method3, Method) IMP3 fct; struct Class* cls[3]; COS_CLS_END COS_CLS_DEF(Method4, Method) IMP4 fct; struct Class* cls[4]; COS_CLS_END COS_CLS_DEF(Method5, Method) IMP5 fct; struct Class* cls[5]; COS_CLS_END // standard precicates #ifdef COS_DISABLE_ALL #define COS_DISABLE_STD_PREDICATES #endif #ifndef COS_DISABLE_STD_PREDICATES COS_CLS_USE(Nil, True, False); #endif #endif // COS_COS_COSCLS_H
40.010638
78
0.319862
[ "object", "model" ]
a29cf77436bf09460622a1a4eeb8bdf82f55947d
4,212
h
C
Samples/OceanDemo/include/MaterialControls.h
Frankincense/ogre
927d459a7e9d5a9990b4c565ec4ab492f6124566
[ "MIT" ]
1
2020-07-12T20:29:19.000Z
2020-07-12T20:29:19.000Z
Samples/OceanDemo/include/MaterialControls.h
SweeneyChoi/ogre
e719ced4dbefb6a46888b4d1115a75f126948697
[ "MIT" ]
null
null
null
Samples/OceanDemo/include/MaterialControls.h
SweeneyChoi/ogre
e719ced4dbefb6a46888b4d1115a75f126948697
[ "MIT" ]
4
2016-06-21T23:12:37.000Z
2019-11-05T17:08:06.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #ifndef __MaterialControls_H__ #define __MaterialControls_H__ #include "OgreString.h" enum ShaderValType { GPU_VERTEX, GPU_FRAGMENT, MAT_SPECULAR, MAT_DIFFUSE, MAT_AMBIENT, MAT_SHININESS, MAT_EMISSIVE }; //--------------------------------------------------------------------------- struct ShaderControl { Ogre::String Name; Ogre::String ParamName; ShaderValType ValType; float MinVal; float MaxVal; size_t ElementIndex; mutable size_t PhysicalIndex; float getRange(void) const { return MaxVal - MinVal; } float convertParamToScrollPosition(const float val) const { return val - MinVal; } float convertScrollPositionToParam(const float val) const { return val + MinVal; } }; typedef Ogre::vector<ShaderControl>::type ShaderControlsContainer; typedef ShaderControlsContainer::iterator ShaderControlIterator; // used for materials that have user controls //--------------------------------------------------------------------------- class MaterialControls { public: MaterialControls(const Ogre::String& displayName, const Ogre::String& materialName) : mDisplayName(displayName) , mMaterialName(materialName) { }; ~MaterialControls(void){} const Ogre::String& getDisplayName(void) const { return mDisplayName; } const Ogre::String& getMaterialName(void) const { return mMaterialName; } size_t getShaderControlCount(void) const { return mShaderControlsContainer.size(); } const ShaderControl& getShaderControl(const size_t idx) const { assert( idx < mShaderControlsContainer.size() ); return mShaderControlsContainer[idx]; } /** add a new control by passing a string parameter @param params is a string using the following format: "<Control Name>, <Shader parameter name>, <Parameter Type>, <Min Val>, <Max Val>, <Parameter Sub Index>" <Control Name> is the string displayed for the control name on screen <Shader parameter name> is the name of the variable in the shader <Parameter Type> can be GPU_VERTEX, GPU_FRAGMENT <Min Val> minimum value that parameter can be <Max Val> maximum value that parameter can be <Parameter Sub Index> index into the the float array of the parameter. All GPU parameters are assumed to be float[4]. */ void addControl(const Ogre::String& params); protected: Ogre::String mDisplayName; Ogre::String mMaterialName; ShaderControlsContainer mShaderControlsContainer; }; typedef Ogre::vector<MaterialControls>::type MaterialControlsContainer; typedef MaterialControlsContainer::iterator MaterialControlsIterator; //--------------------------------------------------------------------------- /** loads material shader controls from a configuration file A .controls file is made up of the following: [<material display name>] material = <material name> control = <Control Name>, <Shader parameter name>, <Parameter Type>, <Min Val>, <Max Val>, <Parameter Sub Index> <material display name> is what is displayed in the material combo box. <material name> is the name of the material in the material script. control is the shader control associated with the material. The order of the contol definitions in the .controls file determines their order when displayed in the controls window. you can have multiple .controls files or put them all in one. */ void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename); /** load all control files found in resource paths */ void loadAllMaterialControlFiles(MaterialControlsContainer& controlsContainer); #endif // __MaterialControls_H__
36.947368
126
0.673314
[ "object", "vector" ]
a29d596f589f4fcf38e0aa58a717fe2a2a203ca6
1,800
h
C
domain/include/alibabacloud/domain/model/GetOperationOssUploadPolicyResult.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
domain/include/alibabacloud/domain/model/GetOperationOssUploadPolicyResult.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
domain/include/alibabacloud/domain/model/GetOperationOssUploadPolicyResult.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_DOMAIN_MODEL_GETOPERATIONOSSUPLOADPOLICYRESULT_H_ #define ALIBABACLOUD_DOMAIN_MODEL_GETOPERATIONOSSUPLOADPOLICYRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/domain/DomainExport.h> namespace AlibabaCloud { namespace Domain { namespace Model { class ALIBABACLOUD_DOMAIN_EXPORT GetOperationOssUploadPolicyResult : public ServiceResult { public: GetOperationOssUploadPolicyResult(); explicit GetOperationOssUploadPolicyResult(const std::string &payload); ~GetOperationOssUploadPolicyResult(); std::string getFileDir()const; std::string getEncodedPolicy()const; std::string getAccessid()const; std::string getSignature()const; std::string getHost()const; std::string getExpireTime()const; protected: void parse(const std::string &payload); private: std::string fileDir_; std::string encodedPolicy_; std::string accessid_; std::string signature_; std::string host_; std::string expireTime_; }; } } } #endif // !ALIBABACLOUD_DOMAIN_MODEL_GETOPERATIONOSSUPLOADPOLICYRESULT_H_
29.508197
92
0.753889
[ "vector", "model" ]
a2a41e30ef4d74337f9e77ab7462b2a29c857e3d
2,517
h
C
Unmanaged/HVisionSystem/include/Matrox/Structures.h
wiseants/Varins
8b9153bc46c669c572f2e56fe313a92cb546c5ae
[ "MS-PL" ]
null
null
null
Unmanaged/HVisionSystem/include/Matrox/Structures.h
wiseants/Varins
8b9153bc46c669c572f2e56fe313a92cb546c5ae
[ "MS-PL" ]
null
null
null
Unmanaged/HVisionSystem/include/Matrox/Structures.h
wiseants/Varins
8b9153bc46c669c572f2e56fe313a92cb546c5ae
[ "MS-PL" ]
null
null
null
#ifndef __RASTER_PRIVATE_STRUCTURES__ #define __RASTER_PRIVATE_STRUCTURES__ #include <list> #pragma warning(push) #pragma warning(disable:4018) #include <vector> #pragma warning(pop) #define TINY 1.0e-20 struct ROISize { long left; long top; long width; long height; }; struct SCharPoint { char m_x; char m_y; }; struct SLongPoint { long m_x; long m_y; }; typedef std::list<SLongPoint> LPointList; typedef LPointList::iterator LPointListIterator; struct SDoublePoint { double m_x; double m_y; }; typedef std::list<SDoublePoint> DPointList; typedef DPointList::iterator DPointListIterator; typedef std::vector<SDoublePoint> DPointVector; typedef DPointVector::iterator DPointVectorIterator; struct SDouble3DPoint { double m_x; double m_y; double m_z; }; struct SLineSpec { double m_theta; // radian double m_cos; double m_sin; double m_rho; // positive }; typedef std::list<SLineSpec> LineSpecList; typedef LineSpecList::iterator LineSpecListIterator; typedef LineSpecList::const_iterator LineSpecListConstIterator; struct SLongRange { long m_start; long m_end; }; typedef std::list<SLongRange> LRangeList; typedef LRangeList::iterator LRangeListIterator; struct _SBlobInfo // Bottom-Up type. { double m_ax; // Area center double m_ay; // Area center double m_gx; // Gravity center double m_gy; // Gravity center long m_area; // Area long m_weight; // Weight long m_density; // Average Intensity long m_left; // x-coord long m_right; // x-coord long m_lower; // y-coord long m_upper; // y-coord long m_width; // m_right - m_left long m_height; // m_upper - m_lower bool m_IsValid; }; struct SPatchVertexes { double m_x1; // 화면 좌측 아래를 원점으로 하여 double m_y1; // 원점에서 가장 가까운 점을 기준점으로 시계 반대 방향으로 순서를 매긴다. double m_x2; double m_y2; double m_x3; double m_y3; double m_x4; double m_y4; }; struct SNeighborPoint { double m_x0; // 현재 픽셀은 0번 double m_y0; double m_x1; // 현재 관심 픽셀로부터 우측에 있는 교점을 1번으로 하여 double m_y1; // 시계 반대 방향으로 순서을 매긴다. double m_x2; double m_y2; double m_x3; double m_y3; double m_x4; double m_y4; }; __forceinline CArchive &operator>>(CArchive &ar, SCharPoint &dst){ return ar >> dst.m_x >> dst.m_y;} __forceinline CArchive &operator<<(CArchive &ar, SCharPoint &src){ return ar << src.m_x << src.m_y;} __forceinline CArchive &operator>>(CArchive &ar, SDoublePoint &dst){ return ar >> dst.m_x >> dst.m_y;} __forceinline CArchive &operator<<(CArchive &ar, SDoublePoint &src){ return ar << src.m_x << src.m_y;} #endif
18.507353
68
0.72944
[ "vector" ]
a2a720a4a6726d5c465c7e2fd45c92415797baa8
5,331
h
C
FireRender.Maya.Src/FireRenderAOV.h
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
null
null
null
FireRender.Maya.Src/FireRenderAOV.h
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
null
null
null
FireRender.Maya.Src/FireRenderAOV.h
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
null
null
null
/********************************************************************** Copyright 2020 Advanced Micro Devices, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #pragma once #include <maya/MString.h> #include "RenderRegion.h" #include "RenderStamp.h" #include <memory> // Maya 2015 has min/max defined, what prevents imageio.h from being compiled #undef min #undef max #include <imageio.h> // Forward declarations. class FireRenderContext; #if MAYA_API_VERSION < 20180000 class MFnDependencyNode; #endif struct RV_PIXEL; /** AOV description of channel components and data types. */ struct AOVDescription { const char* components[4]; OIIO::TypeDesc types; }; /** Automated handler for RV_PIXEL data. Uses aligned memory manager and prevents unnecessary re-allocations */ class PixelBuffer { RV_PIXEL * m_pBuffer; size_t m_size; size_t m_width; size_t m_height; public: PixelBuffer() : m_pBuffer(nullptr) , m_size(0) , m_width(0) , m_height(0) { } virtual ~PixelBuffer() { reset(); } public: operator bool() const { return m_pBuffer != nullptr; } RV_PIXEL * const get() const { return m_pBuffer; } size_t size() const { return m_size; } size_t width() const { return m_width; } size_t height() const { return m_height; } float* data() { return (float*)m_pBuffer; } void resize(size_t newCount); void resize(size_t width, size_t height) { m_width = width; m_height = height; resize(width*height); } void reset() { if (m_pBuffer) { #ifdef WIN32 _aligned_free(m_pBuffer); #else free(m_pBuffer); #endif } m_pBuffer = nullptr; m_size = 0; } void overwrite(const RV_PIXEL* input, const RenderRegion& region, unsigned int totalHeight, unsigned int totalWidth, int aov_id = 0); void debugDump(unsigned int totalHeight, unsigned int totalWidth, std::string& fbName); }; typedef std::map<unsigned int, PixelBuffer> AOVPixelBuffers; /** AOV data. */ class FireRenderAOV { public: // Life Cycle // ----------------------------------------------------------------------------- FireRenderAOV(const FireRenderAOV& other); FireRenderAOV(unsigned int id, const MString& attribute, const MString& name, const MString& folder, AOVDescription description); virtual ~FireRenderAOV() {} public: FireRenderAOV& operator=(const FireRenderAOV& other); // Public Methods // ----------------------------------------------------------------------------- /** Check that the AOV is active and in a valid state. */ bool IsValid(const FireRenderContext& context) const; /** Set the size of the AOVs, including the full frame buffer size. */ void setRegion(const RenderRegion& region, unsigned int frameWidth, unsigned int frameHeight); /** Allocate pixels for active AOVs. */ void allocatePixels(); /** Free pixels for active AOVs. */ void freePixels(); /** Read the frame buffer pixels for this AOV. */ void readFrameBuffer(FireRenderContext& context, bool flip, bool isDenoiserDisabled = false); /** Send the AOV pixels to the Maya render view. */ void sendToRenderView(); /** Write the AOV to file. */ typedef void(*FileWrittenCallback)(const MString&); bool writeToFile(const MString& filePath, bool colorOnly, unsigned int imageFormat, FileWrittenCallback fileWrittenCallback = nullptr) const; /** Get an AOV output path for the given file path. */ MString getOutputFilePath( const MString& filePath ) const; /** Setup render stamp */ void setRenderStamp(const MString& renderStamp); // Properties // ----------------------------------------------------------------------------- /** The numeric AOV ID. */ unsigned int id; /** The RPR globals attribute name. */ MString attribute; /** The AOV name for display in the UI. */ MString name; /** The AOV output folder (or channel in a multi-channel EXR). */ MString folder; /** Render stamp template. Empty string when not used. */ MString renderStamp; /** The AOV data format description. */ AOVDescription description; /** True if this AOV is active for the current render. */ bool active; /** AOV pixel data. Allocated if the buffer is active. */ PixelBuffer pixels; /** Getting settings for making post processing*/ virtual void ReadFromGlobals(const MFnDependencyNode& globals) {} static const std::string& GetAOVName(int aov_id); protected: /** Make post processing for the specific AOV if required*/ virtual void PostProcess(){} protected: // Members // ----------------------------------------------------------------------------- /** AOV region. */ RenderRegion m_region; /** Frame buffer width. */ unsigned int m_frameWidth; /** Frame buffer height. */ unsigned int m_frameHeight; /** Render Stamp */ std::unique_ptr<FireMaya::RenderStamp> m_renderStamp; };
23.799107
142
0.662352
[ "render" ]
a2aaa17d1270e78a652c4f3df492ba6abba0357d
1,906
h
C
src/program.h
wtrsltnk/king-of-the-bombspot
9c07d9fdd87b2cf8029fb43e35095ea040ee8c40
[ "MIT" ]
null
null
null
src/program.h
wtrsltnk/king-of-the-bombspot
9c07d9fdd87b2cf8029fb43e35095ea040ee8c40
[ "MIT" ]
null
null
null
src/program.h
wtrsltnk/king-of-the-bombspot
9c07d9fdd87b2cf8029fb43e35095ea040ee8c40
[ "MIT" ]
null
null
null
#ifndef _PROGRAM_H_ #define _PROGRAM_H_ #include "common/application.h" #include "common/camera.h" #include <GL/glextl.h> #include <glm/glm.hpp> #include <glm/gtc/quaternion.hpp> #include <valve/hl1bspasset.h> #include <valve/hl1bspinstance.h> #include <valve/hl1mdlinstance.h> using namespace valve; class Object { public: Object() : _parent(nullptr), _instance(nullptr) {} glm::mat4 LocalMatrix() const; glm::mat4 WorldMatrix() const; Object *_parent; glm::quat _rotation; glm::vec3 _position; AssetInstance *_instance; void Render(const glm::mat4 &proj); }; class Program : public Application { public: Program(); virtual ~Program(); int Width() { return this->_width; } int Height() { return this->_height; } public: virtual const char *GetWindowTitle() { return "King of the Bombspot"; } virtual void GetContextAttributes(int &major, int &minor, bool &core) { major = 3; minor = 1; core = false; } virtual int GetWindowFlags(); virtual bool InitializeApplication(System *sys); virtual bool InitializeGraphics(); virtual void GameLoop(); virtual bool IsRunning(); void StopRunning(); virtual void Resize(int w, int h); virtual void MouseMove(int x, int y); virtual void MouseButtonDown(int exit, int x, int y); virtual void MouseButtonUp(int exit, int x, int y); virtual void MouseWheel(int x, int y); virtual void KeyAction(int key, int action); virtual void Close(); virtual void Destroy(); private: int _width = 1024; int _height = 768; bool _running = true; System *_sys = nullptr; glm::mat4 _proj; int _lastX = 0; int _lastY = 0; bool _pan = false; Camera _cam; hl1::BspAsset *_asset = nullptr; hl1::BspInstance *_instance = nullptr; std::vector<Object *> _objects; }; #endif // _PROGRAM_H_
23.243902
75
0.66107
[ "render", "object", "vector" ]
a2ae94627cba9a32a2de0ef8fb7f86b4b9641299
1,593
h
C
herald/include/herald/payload/simple/k.h
debojyoti-majumder/herald-for-cpp
694733d0f17e410bfdc0f9eb709c047b00ac6100
[ "Apache-2.0" ]
8
2021-04-02T22:39:50.000Z
2022-03-05T21:50:54.000Z
herald/include/herald/payload/simple/k.h
adamfowleruk/herald-for-cpp
6268834298462caa26bec84c3ab887e624928304
[ "Apache-2.0" ]
49
2021-04-02T10:59:42.000Z
2021-12-30T16:44:46.000Z
herald/include/herald/payload/simple/k.h
adamfowleruk/herald-for-cpp
6268834298462caa26bec84c3ab887e624928304
[ "Apache-2.0" ]
8
2021-03-31T18:57:49.000Z
2021-09-19T08:53:11.000Z
// Copyright 2021 Herald Project Contributors // SPDX-License-Identifier: Apache-2.0 // #ifndef HERALD_SIMPLE_K_H #define HERALD_SIMPLE_K_H #include "secret_key.h" #include "matching_key.h" #include "contact_key.h" #include "contact_identifier.h" #include "../../datatype/data.h" #include "../../datatype/time_interval.h" namespace herald { namespace payload { namespace simple { using namespace herald::datatype; class K { public: K() noexcept; K(const K& other) noexcept; K(K&&) = delete; K(int keyLength, int daysFor, int periodsInDay) noexcept; K(int keyLength, int daysFor, int periodsInDay, TimeInterval epochBeginning) noexcept; ~K() noexcept; static TimeInterval getEpoch() noexcept; int day(Date on) const noexcept; int period(Date at) const noexcept; MatchingKey matchingKey(const SecretKey& secretKey, const int dayFor) noexcept; ContactKey contactKey(const SecretKey& secretKey, const int dayFor, const int periodFor) noexcept; ContactIdentifier contactIdentifier(const SecretKey& secretKey, const int dayFor, const int periodFor) noexcept; // NOTE I'm keeping the old functions here in case we need to use a caching version on another platform // const std::vector<MatchingKey>& matchingKeys(const SecretKey& secretKey) noexcept; // const std::vector<ContactKey> contactKeys(const MatchingKey& matchingKey) noexcept; // const ContactIdentifier contactIdentifier(const ContactKey& contactKey) noexcept; private: const int keyLength; const int daysFor; const int periodsInDay; const TimeInterval epoch; }; } } } #endif
25.285714
114
0.755807
[ "vector" ]
a2b194574b7db347ecdaad5115fc23f7ef3af2c1
11,110
h
C
iOS/SpeakThru/Pods/GoogleAPIClientForREST/Source/GeneratedServices/Vision/GTLRVisionQuery.h
klabertants/mipt_thesis
a12d8d4612b3dca01862360053e219849e493161
[ "MIT" ]
1
2020-11-07T19:03:45.000Z
2020-11-07T19:03:45.000Z
iOS/SpeakThru/Pods/GoogleAPIClientForREST/Source/GeneratedServices/Vision/GTLRVisionQuery.h
klabertants/mipt_thesis
a12d8d4612b3dca01862360053e219849e493161
[ "MIT" ]
null
null
null
iOS/SpeakThru/Pods/GoogleAPIClientForREST/Source/GeneratedServices/Vision/GTLRVisionQuery.h
klabertants/mipt_thesis
a12d8d4612b3dca01862360053e219849e493161
[ "MIT" ]
null
null
null
// NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // Cloud Vision API (vision/v1) // Description: // Integrates Google Vision features, including image labeling, face, logo, // and landmark detection, optical character recognition (OCR), and detection // of explicit content, into applications. // Documentation: // https://cloud.google.com/vision/ #if GTLR_BUILT_AS_FRAMEWORK #import "GTLR/GTLRQuery.h" #else #import "GTLRQuery.h" #endif #if GTLR_RUNTIME_VERSION != 3000 #error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source. #endif @class GTLRVision_AsyncBatchAnnotateFilesRequest; @class GTLRVision_BatchAnnotateImagesRequest; @class GTLRVision_CancelOperationRequest; // Generated comments include content from the discovery document; avoid them // causing warnings since clang's checks are some what arbitrary. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" NS_ASSUME_NONNULL_BEGIN /** * Parent class for other Vision query classes. */ @interface GTLRVisionQuery : GTLRQuery /** Selector specifying which fields to include in a partial response. */ @property(nonatomic, copy, nullable) NSString *fields; @end /** * Run asynchronous image detection and annotation for a list of generic * files, such as PDF files, which may contain multiple pages and multiple * images per page. Progress and results can be retrieved through the * `google.longrunning.Operations` interface. * `Operation.metadata` contains `OperationMetadata` (metadata). * `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results). * * Method: vision.files.asyncBatchAnnotate * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_FilesAsyncBatchAnnotate : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForFilesAsyncBatchAnnotateWithObject:] /** * Fetches a @c GTLRVision_Operation. * * Run asynchronous image detection and annotation for a list of generic * files, such as PDF files, which may contain multiple pages and multiple * images per page. Progress and results can be retrieved through the * `google.longrunning.Operations` interface. * `Operation.metadata` contains `OperationMetadata` (metadata). * `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results). * * @param object The @c GTLRVision_AsyncBatchAnnotateFilesRequest to include in * the query. * * @return GTLRVisionQuery_FilesAsyncBatchAnnotate */ + (instancetype)queryWithObject:(GTLRVision_AsyncBatchAnnotateFilesRequest *)object; @end /** * Run image detection and annotation for a batch of images. * * Method: vision.images.annotate * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_ImagesAnnotate : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForImagesAnnotateWithObject:] /** * Fetches a @c GTLRVision_BatchAnnotateImagesResponse. * * Run image detection and annotation for a batch of images. * * @param object The @c GTLRVision_BatchAnnotateImagesRequest to include in the * query. * * @return GTLRVisionQuery_ImagesAnnotate */ + (instancetype)queryWithObject:(GTLRVision_BatchAnnotateImagesRequest *)object; @end /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * Method: vision.locations.operations.get * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_LocationsOperationsGet : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForLocationsOperationsGetWithname:] /** The name of the operation resource. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRVision_Operation. * * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * @param name The name of the operation resource. * * @return GTLRVisionQuery_LocationsOperationsGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. * * Method: vision.operations.cancel * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_OperationsCancel : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForOperationsCancelWithObject:name:] /** The name of the operation resource to be cancelled. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRVision_Empty. * * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. * * @param object The @c GTLRVision_CancelOperationRequest to include in the * query. * @param name The name of the operation resource to be cancelled. * * @return GTLRVisionQuery_OperationsCancel */ + (instancetype)queryWithObject:(GTLRVision_CancelOperationRequest *)object name:(NSString *)name; @end /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * * Method: vision.operations.delete * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_OperationsDelete : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForOperationsDeleteWithname:] /** The name of the operation resource to be deleted. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRVision_Empty. * * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * * @param name The name of the operation resource to be deleted. * * @return GTLRVisionQuery_OperationsDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * Method: vision.operations.get * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_OperationsGet : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForOperationsGetWithname:] /** The name of the operation resource. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRVision_Operation. * * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * @param name The name of the operation resource. * * @return GTLRVisionQuery_OperationsGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/ * /operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/ *}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * * Method: vision.operations.list * * Authorization scope(s): * @c kGTLRAuthScopeVisionCloudPlatform * @c kGTLRAuthScopeVisionCloudVision */ @interface GTLRVisionQuery_OperationsList : GTLRVisionQuery // Previous library name was // +[GTLQueryVision queryForOperationsListWithname:] /** The standard list filter. */ @property(nonatomic, copy, nullable) NSString *filter; /** The name of the operation's parent resource. */ @property(nonatomic, copy, nullable) NSString *name; /** The standard list page size. */ @property(nonatomic, assign) NSInteger pageSize; /** The standard list page token. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Fetches a @c GTLRVision_ListOperationsResponse. * * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/ * /operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/ *}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * * @param name The name of the operation's parent resource. * * @return GTLRVisionQuery_OperationsList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithName:(NSString *)name; @end NS_ASSUME_NONNULL_END #pragma clang diagnostic pop
34.71875
126
0.748965
[ "object" ]
a2c85cc37972306e60adb71abe0e53590c7cad1b
14,279
c
C
linux/sound/pci/ca0106/ca0106_proc.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
3
2020-11-06T05:17:03.000Z
2020-11-06T07:32:34.000Z
linux/sound/pci/ca0106/ca0106_proc.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
null
null
null
linux/sound/pci/ca0106/ca0106_proc.c
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
1
2020-11-06T07:32:55.000Z
2020-11-06T07:32:55.000Z
/* * Copyright (c) 2004 James Courtier-Dutton <James@superbug.demon.co.uk> * Driver CA0106 chips. e.g. Sound Blaster Audigy LS and Live 24bit * Version: 0.0.18 * * FEATURES currently supported: * See ca0106_main.c for features. * * Changelog: * Support interrupts per period. * Removed noise from Center/LFE channel when in Analog mode. * Rename and remove mixer controls. * 0.0.6 * Use separate card based DMA buffer for periods table list. * 0.0.7 * Change remove and rename ctrls into lists. * 0.0.8 * Try to fix capture sources. * 0.0.9 * Fix AC3 output. * Enable S32_LE format support. * 0.0.10 * Enable playback 48000 and 96000 rates. (Rates other that these do not work, even with "plug:front".) * 0.0.11 * Add Model name recognition. * 0.0.12 * Correct interrupt timing. interrupt at end of period, instead of in the middle of a playback period. * Remove redundent "voice" handling. * 0.0.13 * Single trigger call for multi channels. * 0.0.14 * Set limits based on what the sound card hardware can do. * playback periods_min=2, periods_max=8 * capture hw constraints require period_size = n * 64 bytes. * playback hw constraints require period_size = n * 64 bytes. * 0.0.15 * Separate ca0106.c into separate functional .c files. * 0.0.16 * Modified Copyright message. * 0.0.17 * Add iec958 file in proc file system to show status of SPDIF in. * 0.0.18 * Implement support for Line-in capture on SB Live 24bit. * * This code was initially based on code from ALSA's emu10k1x.c which is: * Copyright (c) by Francisco Moraes <fmoraes@nc.rr.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/moduleparam.h> #include <linux/io.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/pcm.h> #include <sound/ac97_codec.h> #include <sound/info.h> #include <sound/asoundef.h> #include "ca0106.h" struct snd_ca0106_category_str { int val; const char *name; }; static struct snd_ca0106_category_str snd_ca0106_con_category[] = { { IEC958_AES1_CON_DAT, "DAT" }, { IEC958_AES1_CON_VCR, "VCR" }, { IEC958_AES1_CON_MICROPHONE, "microphone" }, { IEC958_AES1_CON_SYNTHESIZER, "synthesizer" }, { IEC958_AES1_CON_RATE_CONVERTER, "rate converter" }, { IEC958_AES1_CON_MIXER, "mixer" }, { IEC958_AES1_CON_SAMPLER, "sampler" }, { IEC958_AES1_CON_PCM_CODER, "PCM coder" }, { IEC958_AES1_CON_IEC908_CD, "CD" }, { IEC958_AES1_CON_NON_IEC908_CD, "non-IEC908 CD" }, { IEC958_AES1_CON_GENERAL, "general" }, }; static void snd_ca0106_proc_dump_iec958( struct snd_info_buffer *buffer, u32 value) { int i; u32 status[4]; status[0] = value & 0xff; status[1] = (value >> 8) & 0xff; status[2] = (value >> 16) & 0xff; status[3] = (value >> 24) & 0xff; if (! (status[0] & IEC958_AES0_PROFESSIONAL)) { /* consumer */ snd_iprintf(buffer, "Mode: consumer\n"); snd_iprintf(buffer, "Data: "); if (!(status[0] & IEC958_AES0_NONAUDIO)) { snd_iprintf(buffer, "audio\n"); } else { snd_iprintf(buffer, "non-audio\n"); } snd_iprintf(buffer, "Rate: "); switch (status[3] & IEC958_AES3_CON_FS) { case IEC958_AES3_CON_FS_44100: snd_iprintf(buffer, "44100 Hz\n"); break; case IEC958_AES3_CON_FS_48000: snd_iprintf(buffer, "48000 Hz\n"); break; case IEC958_AES3_CON_FS_32000: snd_iprintf(buffer, "32000 Hz\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Copyright: "); if (status[0] & IEC958_AES0_CON_NOT_COPYRIGHT) { snd_iprintf(buffer, "permitted\n"); } else { snd_iprintf(buffer, "protected\n"); } snd_iprintf(buffer, "Emphasis: "); if ((status[0] & IEC958_AES0_CON_EMPHASIS) != IEC958_AES0_CON_EMPHASIS_5015) { snd_iprintf(buffer, "none\n"); } else { snd_iprintf(buffer, "50/15us\n"); } snd_iprintf(buffer, "Category: "); for (i = 0; i < ARRAY_SIZE(snd_ca0106_con_category); i++) { if ((status[1] & IEC958_AES1_CON_CATEGORY) == snd_ca0106_con_category[i].val) { snd_iprintf(buffer, "%s\n", snd_ca0106_con_category[i].name); break; } } if (i >= ARRAY_SIZE(snd_ca0106_con_category)) { snd_iprintf(buffer, "unknown 0x%x\n", status[1] & IEC958_AES1_CON_CATEGORY); } snd_iprintf(buffer, "Original: "); if (status[1] & IEC958_AES1_CON_ORIGINAL) { snd_iprintf(buffer, "original\n"); } else { snd_iprintf(buffer, "1st generation\n"); } snd_iprintf(buffer, "Clock: "); switch (status[3] & IEC958_AES3_CON_CLOCK) { case IEC958_AES3_CON_CLOCK_1000PPM: snd_iprintf(buffer, "1000 ppm\n"); break; case IEC958_AES3_CON_CLOCK_50PPM: snd_iprintf(buffer, "50 ppm\n"); break; case IEC958_AES3_CON_CLOCK_VARIABLE: snd_iprintf(buffer, "variable pitch\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } } else { snd_iprintf(buffer, "Mode: professional\n"); snd_iprintf(buffer, "Data: "); if (!(status[0] & IEC958_AES0_NONAUDIO)) { snd_iprintf(buffer, "audio\n"); } else { snd_iprintf(buffer, "non-audio\n"); } snd_iprintf(buffer, "Rate: "); switch (status[0] & IEC958_AES0_PRO_FS) { case IEC958_AES0_PRO_FS_44100: snd_iprintf(buffer, "44100 Hz\n"); break; case IEC958_AES0_PRO_FS_48000: snd_iprintf(buffer, "48000 Hz\n"); break; case IEC958_AES0_PRO_FS_32000: snd_iprintf(buffer, "32000 Hz\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Rate Locked: "); if (status[0] & IEC958_AES0_PRO_FREQ_UNLOCKED) snd_iprintf(buffer, "no\n"); else snd_iprintf(buffer, "yes\n"); snd_iprintf(buffer, "Emphasis: "); switch (status[0] & IEC958_AES0_PRO_EMPHASIS) { case IEC958_AES0_PRO_EMPHASIS_CCITT: snd_iprintf(buffer, "CCITT J.17\n"); break; case IEC958_AES0_PRO_EMPHASIS_NONE: snd_iprintf(buffer, "none\n"); break; case IEC958_AES0_PRO_EMPHASIS_5015: snd_iprintf(buffer, "50/15us\n"); break; case IEC958_AES0_PRO_EMPHASIS_NOTID: default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Stereophonic: "); if ((status[1] & IEC958_AES1_PRO_MODE) == IEC958_AES1_PRO_MODE_STEREOPHONIC) { snd_iprintf(buffer, "stereo\n"); } else { snd_iprintf(buffer, "not indicated\n"); } snd_iprintf(buffer, "Userbits: "); switch (status[1] & IEC958_AES1_PRO_USERBITS) { case IEC958_AES1_PRO_USERBITS_192: snd_iprintf(buffer, "192bit\n"); break; case IEC958_AES1_PRO_USERBITS_UDEF: snd_iprintf(buffer, "user-defined\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Sample Bits: "); switch (status[2] & IEC958_AES2_PRO_SBITS) { case IEC958_AES2_PRO_SBITS_20: snd_iprintf(buffer, "20 bit\n"); break; case IEC958_AES2_PRO_SBITS_24: snd_iprintf(buffer, "24 bit\n"); break; case IEC958_AES2_PRO_SBITS_UDEF: snd_iprintf(buffer, "user defined\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } snd_iprintf(buffer, "Word Length: "); switch (status[2] & IEC958_AES2_PRO_WORDLEN) { case IEC958_AES2_PRO_WORDLEN_22_18: snd_iprintf(buffer, "22 bit or 18 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_23_19: snd_iprintf(buffer, "23 bit or 19 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_24_20: snd_iprintf(buffer, "24 bit or 20 bit\n"); break; case IEC958_AES2_PRO_WORDLEN_20_16: snd_iprintf(buffer, "20 bit or 16 bit\n"); break; default: snd_iprintf(buffer, "unknown\n"); break; } } } static void snd_ca0106_proc_iec958(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; u32 value; value = snd_ca0106_ptr_read(emu, SAMPLE_RATE_TRACKER_STATUS, 0); snd_iprintf(buffer, "Status: %s, %s, %s\n", (value & 0x100000) ? "Rate Locked" : "Not Rate Locked", (value & 0x200000) ? "SPDIF Locked" : "No SPDIF Lock", (value & 0x400000) ? "Audio Valid" : "No valid audio" ); snd_iprintf(buffer, "Estimated sample rate: %u\n", ((value & 0xfffff) * 48000) / 0x8000 ); if (value & 0x200000) { snd_iprintf(buffer, "IEC958/SPDIF input status:\n"); value = snd_ca0106_ptr_read(emu, SPDIF_INPUT_STATUS, 0); snd_ca0106_proc_dump_iec958(buffer, value); } snd_iprintf(buffer, "\n"); } static void snd_ca0106_proc_reg_write32(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long flags; char line[64]; u32 reg, val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x", &reg, &val) != 2) continue; if (reg < 0x40 && val <= 0xffffffff) { spin_lock_irqsave(&emu->emu_lock, flags); outl(val, emu->port + (reg & 0xfffffffc)); spin_unlock_irqrestore(&emu->emu_lock, flags); } } } static void snd_ca0106_proc_reg_read32(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=4) { spin_lock_irqsave(&emu->emu_lock, flags); value = inl(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %08lX\n", i, value); } } static void snd_ca0106_proc_reg_read16(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned int value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=2) { spin_lock_irqsave(&emu->emu_lock, flags); value = inw(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %04X\n", i, value); } } static void snd_ca0106_proc_reg_read8(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned int value; unsigned long flags; int i; snd_iprintf(buffer, "Registers:\n\n"); for(i = 0; i < 0x20; i+=1) { spin_lock_irqsave(&emu->emu_lock, flags); value = inb(emu->port + i); spin_unlock_irqrestore(&emu->emu_lock, flags); snd_iprintf(buffer, "Register %02X: %02X\n", i, value); } } static void snd_ca0106_proc_reg_read1(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; int i,j; snd_iprintf(buffer, "Registers\n"); for(i = 0; i < 0x40; i++) { snd_iprintf(buffer, "%02X: ",i); for (j = 0; j < 4; j++) { value = snd_ca0106_ptr_read(emu, i, j); snd_iprintf(buffer, "%08lX ", value); } snd_iprintf(buffer, "\n"); } } static void snd_ca0106_proc_reg_read2(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; unsigned long value; int i,j; snd_iprintf(buffer, "Registers\n"); for(i = 0x40; i < 0x80; i++) { snd_iprintf(buffer, "%02X: ",i); for (j = 0; j < 4; j++) { value = snd_ca0106_ptr_read(emu, i, j); snd_iprintf(buffer, "%08lX ", value); } snd_iprintf(buffer, "\n"); } } static void snd_ca0106_proc_reg_write(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; char line[64]; unsigned int reg, channel_id , val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x %x", &reg, &channel_id, &val) != 3) continue; if (reg < 0x80 && val <= 0xffffffff && channel_id <= 3) snd_ca0106_ptr_write(emu, reg, channel_id, val); } } static void snd_ca0106_proc_i2c_write(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ca0106 *emu = entry->private_data; char line[64]; unsigned int reg, val; while (!snd_info_get_line(buffer, line, sizeof(line))) { if (sscanf(line, "%x %x", &reg, &val) != 2) continue; if ((reg <= 0x7f) || (val <= 0x1ff)) { snd_ca0106_i2c_write(emu, reg, val); } } } int snd_ca0106_proc_init(struct snd_ca0106 *emu) { struct snd_info_entry *entry; if(! snd_card_proc_new(emu->card, "iec958", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_iec958); if(! snd_card_proc_new(emu->card, "ca0106_reg32", &entry)) { snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read32); entry->c.text.write = snd_ca0106_proc_reg_write32; entry->mode |= 0200; } if(! snd_card_proc_new(emu->card, "ca0106_reg16", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read16); if(! snd_card_proc_new(emu->card, "ca0106_reg8", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read8); if(! snd_card_proc_new(emu->card, "ca0106_regs1", &entry)) { snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read1); entry->c.text.write = snd_ca0106_proc_reg_write; entry->mode |= 0200; } if(! snd_card_proc_new(emu->card, "ca0106_i2c", &entry)) { entry->c.text.write = snd_ca0106_proc_i2c_write; entry->private_data = emu; entry->mode |= 0200; } if(! snd_card_proc_new(emu->card, "ca0106_regs2", &entry)) snd_info_set_text_ops(entry, emu, snd_ca0106_proc_reg_read2); return 0; }
31.451542
106
0.674207
[ "model" ]
a2ce84ac8918f1244efe1d5e8fad3285f5538c3e
2,672
h
C
platform/ios/Classes/trigger/cons.h
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
7
2015-04-17T20:50:13.000Z
2019-09-21T10:45:39.000Z
platform/ios/Classes/trigger/cons.h
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
null
null
null
platform/ios/Classes/trigger/cons.h
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
8
2015-01-18T09:37:17.000Z
2021-04-21T05:54:38.000Z
#ifndef __CONS_H__ #define __CONS_H__ #include "cocos2d.h" #include "cocos-ext.h" #include "ExtensionMacros.h" class TimeElapsed : public cocos2d::extension::BaseTriggerCondition { DECLARE_CLASS_INFO public: TimeElapsed(void); virtual ~TimeElapsed(void); virtual bool init(); virtual bool detect(); virtual void serialize(const rapidjson::Value &val); virtual void removeAll(); virtual void update(float dt); private: float _fTotalTime; float _fTmpTime; cocos2d::CCScheduler *_pScheduler; bool _bSuc; }; class ArmatureActionState : public cocos2d::extension::BaseTriggerCondition { DECLARE_CLASS_INFO public: ArmatureActionState(void); virtual ~ArmatureActionState(void); virtual bool init(); virtual bool detect(); virtual void serialize(const rapidjson::Value &val); virtual void removeAll(); void animationEvent(cocos2d::extension::CCArmature *armature, cocos2d::extension::MovementEventType movementType, const char *movementID); private: int _nTag; std::string _comName; std::string _aniname; int _nState; bool _bSuc; }; class NodeInRect : public cocos2d::extension::BaseTriggerCondition { DECLARE_CLASS_INFO public: NodeInRect(void); virtual ~NodeInRect(void); virtual bool init(); virtual bool detect(); virtual void serialize(const rapidjson::Value &val); virtual void removeAll(); private: int _nTag; cocos2d::CCPoint _origin; cocos2d::CCSize _size; }; class NodeVisible : public cocos2d::extension::BaseTriggerCondition { DECLARE_CLASS_INFO public: NodeVisible(void); virtual ~NodeVisible(void); virtual bool init(); virtual bool detect(); virtual void serialize(const rapidjson::Value &val); virtual void removeAll(); private: int _nTag; bool _bVisible; }; class RectangleCollisionTest : public cocos2d::extension::BaseTriggerCondition { DECLARE_CLASS_INFO public: RectangleCollisionTest(void); virtual ~RectangleCollisionTest(void); virtual bool init(); virtual bool detect(); virtual void serialize(const rapidjson::Value &val); virtual void removeAll(); private: bool isRectCollision(cocos2d::CCRect rect1, cocos2d::CCRect rect2); cocos2d::CCNode* getNode(cocos2d::CCNode *pNode, std::string comName); void split(const std::string& s,const std::string& delim,std::vector<int>* ret); private: int _nTag_A; std::string _strComName_A; int _nAOffsetX; int _nAOffsetY; std::vector<int> _vecTags; std::string _strComName_B; int _nBOffsetX; int _nBOffsetY; }; #endif
24.072072
141
0.704341
[ "vector" ]
a2d38864ad501059ffefb6aaa41e1efc205ea4d2
8,934
h
C
code/3rdParty/ogdf/include/ogdf/fileformats/OgmlParser.h
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
41
2018-12-19T17:32:44.000Z
2021-11-27T03:44:53.000Z
code/3rdParty/ogdf/include/ogdf/fileformats/OgmlParser.h
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
16
2019-01-17T13:36:02.000Z
2021-12-13T21:18:45.000Z
code/3rdParty/ogdf/include/ogdf/fileformats/OgmlParser.h
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
2
2018-11-01T12:53:26.000Z
2018-11-07T06:31:03.000Z
/** \file * \brief Implementation of auxiliary classes OgmlAttributeValue, * OgmlAttribute and OgmlTag. * * \author Christian Wolf and Bernd Zey * * \par License: * This file is part of the Open Graph Drawing Framework (OGDF). * * \par * Copyright (C)<br> * See README.md in the OGDF root directory for details. * * \par * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 or 3 as published by the Free Software Foundation; * see the file LICENSE.txt included in the packaging of this file * for details. * * \par * 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. * * \par * You should have received a copy of the GNU General Public * License along with this program; if not, see * http://www.gnu.org/copyleft/gpl.html */ //KK: Commented out the constraint stuff using //o //CG: compound graph stuff has been removed with commit 2465 #pragma once #include <ogdf/fileformats/Ogml.h> #include <ogdf/fileformats/XmlParser.h> #include <ogdf/basic/Hashing.h> #include <ogdf/cluster/ClusterGraph.h> #include <ogdf/cluster/ClusterGraphAttributes.h> namespace ogdf { //! Objects of this class represent a validating parser for files in %Ogml. class OgmlParser { private: // struct definitions for mapping of templates struct OgmlNodeTemplate; struct OgmlEdgeTemplate; #if 0 struct OgmlLabelTemplate; #endif struct OgmlSegment; class OgmlAttributeValue; class OgmlAttribute; class OgmlTag; friend std::ostream& operator<<(std::ostream& os, const OgmlParser::OgmlAttribute& oa); friend std::ostream& operator<<(std::ostream& os, const OgmlParser::OgmlTag& ot); Hashing<int, OgmlTag> *m_tags; //!< Hashtable for saving all ogml tags. Hashing<int, OgmlAttribute> *m_attributes; //!< Hashtable for saving all ogml attributes. Hashing<int, OgmlAttributeValue> *m_attValues; //!< Hashtable for saving all values of ogml attributes. enum Mode { compMode = 0, choiceMode, optMode }; mutable Ogml::GraphType m_graphType; //!< Saves a graph type. Is set by checkGraphType. Hashing<string, const XmlTagObject*> m_ids; //!< Saves all ids of an ogml-file. /** * Checks if all tags (XmlTagObject), their attributes (XmlAttributeObject) and * their values are valid (are tags expected, do they own the rigth attributes...) * and sets a valid flag to these. Furthermore it checks if ids of tags are * unique and if id references are valid. * See OgmlTag.h for semantics of the encodings. * Returns the validity state of the current processed tag. */ int validate(const XmlTagObject *xmlTag, int ogmlTag); #if 0 /** * Wrapper method for validate method above. * Returns true when validation is successfull, false otherwise. */ bool validate(const char* fileName); #endif //! Prints some useful information about un-/successful validation. void printValidityInfo(const OgmlTag &ot, const XmlTagObject &xto, int valStatus, int line); #if 0 /** * Finds the OGML-tag in the parse tree with the specified id, * stores the tag in xmlTag * recTag is the tag for recursive calls * returns false if something goes wrong */ bool getXmlTagObjectById(XmlTagObject *recTag, string id, XmlTagObject *&xmlTag); #endif /** * Checks the graph type and stores it in the member variable m_graphType * xmlTag has to be the root or the graph or the structure Ogml-tag * returns false if something goes wrong */ bool checkGraphType(const XmlTagObject *xmlTag) const; //! Returns true iff subgraph is an hierarchical graph. bool isGraphHierarchical(const XmlTagObject *xmlTag) const; //! Returns true iff node contains other nodes. bool isNodeHierarchical(const XmlTagObject *xmlTag) const; Ogml::GraphType getGraphType() { return m_graphType; }; // id hash tables // required variables for building // hash table with id from file and node Hashing<string, node> m_nodes; Hashing<string, edge> m_edges; Hashing<string, cluster> m_clusters; // hash table for bend-points Hashing<string, DPoint> m_points; // hash table for checking uniqueness of ids // (key:) int = id in the created graph // (info:) string = id in the ogml file Hashing<int, string> m_nodeIds; Hashing<int, string> m_edgeIds; Hashing<int, string> m_clusterIds; // build methods //! Builds a graph; ignores nodes which have hierarchical structure. bool buildGraph(Graph &G); //! Builds a cluster graph. bool buildCluster( const XmlTagObject *rootTag, Graph &G, ClusterGraph &CG); //! Recursive part of buildCluster. bool buildClusterRecursive( const XmlTagObject *xmlTag, cluster parent, Graph &G, ClusterGraph &CG); //! Build a cluster graph with style/layout attributes. bool addAttributes( Graph &G, GraphAttributes &GA, ClusterGraphAttributes *pCGA, const XmlTagObject *root); //! Recursive method for setting labels of clusters and nodes. bool setLabelsRecursive( Graph &G, GraphAttributes &GA, ClusterGraphAttributes *pCGA, XmlTagObject *root); // helping pointer for constraints-loading // this pointer is set in the building methods // so we don't have to traverse the tree in buildConstraints XmlTagObject* m_constraintsTag; // hashing lists for templates // string = id Hashing<string, OgmlNodeTemplate*> m_ogmlNodeTemplates; Hashing<string, OgmlEdgeTemplate*> m_ogmlEdgeTemplates; //Hashing<string, OgmlLabelTemplate> m_ogmlLabelTemplates; // auxiliary methods for mapping graph attributes //! Returns fill pattern of string \p s. FillPattern getFillPattern(string s); //! Returns the shape as an integer value. Shape getShape(string s); //! Maps the OGML attribute values to corresponding GDE values. string getNodeTemplateFromOgmlValue(string s); //! Returns the line type as an integer value. StrokeType getStrokeType(string s); // arrow style, actually a "boolean" function // because it returns only 0 or 1 according to GDE // sot <=> source or target int getArrowStyleAsInt(string s); // the matching method to getArrowStyleAsInt EdgeArrow getArrowStyle(int i); // function that operates on a string // the input string contains "&lt;" instead of "<" // and "&gt;" instead of ">" // to disable interpreting the string as xml-tags (by XmlParser) // so this function substitutes "<" for "&lt;" string getLabelCaptionFromString(string str); //! Returns the integer value of the id at the end of the string (if it exists). bool getIdFromString(string str, int &id); //! Unified read method for graphs. bool doRead( std::istream &is, Graph &G, ClusterGraph *pCG, GraphAttributes *pGA, ClusterGraphAttributes *pCGA); public: //! Constructs an OGML parser. OgmlParser(); ~OgmlParser(); //! Reads a graph \p G from std::istream \p is in OGML format. /** * @param is is the input stream to be parsed as OGML file. * @param G is the graph to be build from the OGML file. * @return true if succesfull, false otherwise. */ bool read(std::istream &is, Graph &G) { return doRead(is, G, nullptr, nullptr, nullptr); } //! Reads a cluster graph \p CG from std::istream \p is in OGML format. /** * @param is is the input stream to be parsed as OGML file. * @param G is the graph to be build from the OGML file; must be the graph associated with \p CG. * @param CG is the cluster graph to be build from the OGML file. * @return true if succesfull, false otherwise. */ bool read(std::istream &is, Graph &G, ClusterGraph &CG) { return doRead(is, G, &CG, nullptr, nullptr); } //! Reads a graph \p G with attributes \p GA from std::istream \p is in OGML format. /** * @param is is the input stream to be parsed as OGML file. * @param G is the graph to be build from the OGML file. * @param GA are the graph attributes (associated with \p G) in which layout and style information are stored. * @return true if succesfull, false otherwise. */ bool read( std::istream &is, Graph &G, GraphAttributes &GA) { return doRead(is, G, nullptr, &GA, nullptr); } //! Reads a cluster graph \p CG with attributes \p CGA from std::istream \p is in OGML format. /** * @param is is the input stream to be parsed as OGML file. * @param G is the graph to be build from the OGML file; must be the graph associated with \p CG. * @param CG is the cluster graph to be build from the OGML file. * @param CGA are the cluster graph attributes (associated with \p CG) in which layout and style information are stored. * @return true if succesfull, false otherwise. */ bool read( std::istream &is, Graph &G, ClusterGraph &CG, ClusterGraphAttributes &CGA) { return doRead(is, G, &CG, &CGA, &CGA); } }; }
31.020833
121
0.722633
[ "shape" ]
a2d7c1b0d6014c66f32b69c98cfaa5a2d938199f
3,250
h
C
examples/complex_fluids/ex2/InterpolationUtilities.h
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
null
null
null
examples/complex_fluids/ex2/InterpolationUtilities.h
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
1
2020-11-30T14:22:45.000Z
2020-12-01T21:28:24.000Z
examples/complex_fluids/ex2/InterpolationUtilities.h
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
null
null
null
// --------------------------------------------------------------------- // // Copyright (c) 2019 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- #ifndef included_InterpolationUtilities #define included_InterpolationUtilities #include "ibamr/namespaces.h" #include <ibamr/app_namespaces.h> #include "ibtk/HierarchyGhostCellInterpolation.h" #include "ibtk/IBTK_MPI.h" #include "ibtk/IndexUtilities.h" #include "Box.h" #include "CartesianGridGeometry.h" #include "CartesianPatchGeometry.h" #include "CellIndex.h" #include "Index.h" #include "IntVector.h" #include "RobinBcCoefStrategy.h" #include "SAMRAI_config.h" #include "tbox/Pointer.h" #include <Patch.h> #include <PatchLevel.h> #include <vector> namespace SAMRAI { namespace hier { template <int DIM> class Patch; template <int DIM> class PatchHierarchy; template <int DIM> class Variable; } // namespace hier } // namespace SAMRAI namespace IBTK { class InterpolationUtilities { public: // Use polynomial interpolation static double interpolate(const std::vector<double>& X, const int data_idx, SAMRAI::tbox::Pointer<SAMRAI::pdat::CellVariable<NDIM, double> > Q_var, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > patch_hierarchy, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, const double data_time, const int depth = 0); // Use least squares interpolation static double interpolateL2(const std::vector<double>& X, const int data_idx, SAMRAI::tbox::Pointer<SAMRAI::pdat::CellVariable<NDIM, double> > Q_var, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > patch_hierarchy, const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs, const double data_time, const int depth = 0); static double weight_fcn(const std::vector<double>&, const std::vector<double>&); private: static double interpolate(const double& x, const std::vector<int>& xi, const std::vector<double>& yi); static double interpolate_in_boxes(const CellIndex<NDIM>& idx, const std::vector<double>& X, SAMRAI::pdat::CellData<NDIM, int>& r_data, SAMRAI::pdat::CellData<NDIM, double>& q_data, Pointer<CartesianPatchGeometry<NDIM> > pgeom, const Box<NDIM>& pbox, int dim, int cycle, std::vector<int>& completed_dims); }; } // namespace IBTK #endif
35.714286
107
0.560308
[ "vector" ]
313dd6e3f32ee9bf23da9d90ae64c140bcb1140a
6,868
h
C
src/eckit/types/Types.h
dvuckovic/eckit
58a918e7be8fe073f37683abf639374ab1ad3e4f
[ "Apache-2.0" ]
10
2018-03-01T22:11:10.000Z
2021-05-17T14:13:58.000Z
src/eckit/types/Types.h
dvuckovic/eckit
58a918e7be8fe073f37683abf639374ab1ad3e4f
[ "Apache-2.0" ]
43
2018-04-11T11:13:44.000Z
2022-03-31T15:28:03.000Z
src/eckit/types/Types.h
dvuckovic/eckit
58a918e7be8fe073f37683abf639374ab1ad3e4f
[ "Apache-2.0" ]
20
2018-03-07T21:36:50.000Z
2022-03-30T13:25:25.000Z
/* * (C) Copyright 1996- 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. */ // File Types.h // Baudouin Raoult - ECMWF Jun 96 #ifndef eckit_Types_h #define eckit_Types_h #include <array> #include <cstddef> #include <iostream> #include <iterator> #include <map> #include <set> #include <utility> #include <vector> #include "eckit/runtime/TaskID.h" // to be removed namespace eckit { //---------------------------------------------------------------------------------------------------------------------- typedef unsigned long Ordinal; ///< for counting typedef std::vector<Ordinal> OrdinalList; typedef std::vector<std::string> StringList; typedef std::set<std::string> StringSet; typedef std::map<std::string, std::string> StringDict; //---------------------------------------------------------------------------------------------------------------------- template <typename S, typename T> inline std::ostream& operator<<(std::ostream& s, const std::pair<S, T>& p) { s << "<" << p.first << "," << p.second << ">"; return s; } //---------------------------------------------------------------------------------------------------------------------- template <class T> class output_list { std::vector<T> v_; bool first_; std::ostream& s_; void flush(); public: void push_back(const T&); output_list(std::ostream&); ~output_list(); }; struct output_iterator { typedef std::output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; }; template <class T> class output_list_iterator : public output_iterator { output_list<T>* list_; public: output_list_iterator(output_list<T>* l) : list_(l) {} ~output_list_iterator() {} output_list_iterator<T>& operator=(const T& v) { list_->push_back(v); return *this; } output_list_iterator<T>& operator*() { return *this; } output_list_iterator<T>& operator++() { return *this; } output_list_iterator<T>& operator++(int) { return *this; } }; //---------------------------------------------------------------------------------------------------------------------- class VectorPrintSimple {}; class VectorPrintContracted {}; template <typename T> struct VectorPrintSelector { typedef VectorPrintContracted selector; }; template <> struct VectorPrintSelector<std::string> { typedef VectorPrintSimple selector; }; template <> struct VectorPrintSelector<double> { typedef VectorPrintSimple selector; }; template <typename K, typename V> struct VectorPrintSelector<std::pair<K, V> > { typedef VectorPrintSimple selector; }; template <class T> inline std::ostream& __print_list(std::ostream& s, const T& t, VectorPrintContracted) { output_list<typename T::value_type> l(s); output_list_iterator<typename T::value_type> os(&l); std::copy(t.begin(), t.end(), os); return s; } template <typename T> inline std::ostream& __print_list(std::ostream& s, const std::vector<T>& t, VectorPrintSimple) { s << '['; for (Ordinal i = 0; i < t.size(); i++) { if (i != 0) s << ','; s << t[i]; } s << ']'; return s; } template <typename T, std::size_t N> inline std::ostream& __print_list(std::ostream& s, const std::array<T, N>& t, VectorPrintSimple) { s << '['; for (Ordinal i = 0; i < t.size(); i++) { if (i != 0) s << ','; s << t[i]; } s << ']'; return s; } template <typename K, typename V> inline std::ostream& __print_container(std::ostream& s, const std::map<K, V>& m) { const char* sep = ""; s << "{"; for (typename std::map<K, V>::const_iterator it = m.begin(); it != m.end(); ++it) { s << sep << it->first << "=" << it->second; sep = ","; } s << "}"; return s; } template <typename T> inline std::ostream& __print_container(std::ostream& s, const std::set<T>& m) { const char* sep = ""; s << "{"; for (typename std::set<T>::const_iterator it = m.begin(); it != m.end(); ++it) { s << sep << *it; sep = ","; } s << "}"; return s; } } // namespace eckit //---------------------------------------------------------------------------------------------------------------------- namespace std { // n.b. This overload needs to go either in the namespace std:: (which contains // ostream, vector), the global namespace, or the namespace containing T. // Otherwise it will not be found when doing lookups. // // --> Probably best to put it in std::. It is acceptable to add "template // specializations for any standard library template" if the "declaration // depends on user-defined types". template <class T> inline std::ostream& operator<<(std::ostream& s, const std::vector<T>& v) { return eckit::__print_list(s, v, typename eckit::VectorPrintSelector<T>::selector()); } template <class T, std::size_t N> inline std::ostream& operator<<(std::ostream& s, const std::array<T, N>& v) { return eckit::__print_list(s, v, typename eckit::VectorPrintSelector<T>::selector()); } template <typename K, typename V> inline std::ostream& operator<<(std::ostream& s, const std::map<K, V>& m) { return eckit::__print_container(s, m); } template <typename T> inline std::ostream& operator<<(std::ostream& s, const std::set<T>& m) { return eckit::__print_container(s, m); } } // namespace std //---------------------------------------------------------------------------------------------------------------------- namespace eckit { //---------------------------------------------------------------------------------------------------------------------- class Stream; // forward /// Operators to send vectors in streams template <class T> Stream& operator<<(Stream&, const std::vector<T>&); template <class T> Stream& operator>>(Stream&, std::vector<T>&); /// Operators to send sets in streams template <class T> Stream& operator<<(Stream&, const std::vector<T>&); template <class T> Stream& operator>>(Stream&, std::vector<T>&); /// Operators to send maps in streams /// Note: the value type V must have a constructor from Stream& template <class K, class V> Stream& operator<<(Stream&, const std::map<K, V>&); template <class K, class V> Stream& operator>>(Stream&, std::map<K, V>&); //---------------------------------------------------------------------------------------------------------------------- } // namespace eckit #include "eckit/types/Types.cc" #endif
28.497925
120
0.557513
[ "vector" ]
313f29a873e5b6aad824b529f9e85fc007b72ccd
7,678
h
C
FCollada/FCDocument/FCDPhysicsModel.h
matthewlai/fcollada
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
[ "MIT" ]
9
2016-04-22T05:47:37.000Z
2021-03-02T08:58:56.000Z
FCollada/FCDocument/FCDPhysicsModel.h
matthewlai/fcollada
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
[ "MIT" ]
5
2018-12-17T13:49:54.000Z
2021-11-26T17:22:16.000Z
FCollada/FCDocument/FCDPhysicsModel.h
matthewlai/fcollada
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
[ "MIT" ]
5
2018-06-26T19:42:58.000Z
2021-10-11T13:03:31.000Z
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ /** @file FCDPhysicsModel.h This file contains the FCDPhysicsModel class. */ #ifndef _FCD_PHYSICSMODEL_H_ #define _FCD_PHYSICSMODEL_H_ #ifndef _FCD_ENTITY_H_ #include "FCDocument/FCDEntity.h" #endif // _FCD_ENTITY_H_ #ifndef _FU_URI_H_ #include "FUtils/FUUri.h" #endif // _FU_URI_H_ class FCDocument; class FCDPhysicsRigidBody; class FCDPhysicsRigidConstraint; class FCDPhysicsModelInstance; class FUUri; typedef FUObjectContainer<FCDPhysicsModelInstance> FCDPhysicsModelInstanceContainer; /**< A dynamically-sized containment array for physics mode instances. */ typedef FUObjectContainer<FCDPhysicsRigidBody> FCDPhysicsRigidBodyContainer; /**< A dynamically-sized containment array for rigid bodies. */ typedef FUObjectContainer<FCDPhysicsRigidConstraint> FCDPhysicsRigidConstraintContainer; /**< A dynamically-sized containment array for rigid constraints. */ /** A COLLADA physics model. A physics model can contain rigid bodies, rigid constraints, or instances of previously defined physics models. For example, a house physics model could contain a number of instantiated physics models such as walls. @ingroup FCDocument */ class FCOLLADA_EXPORT FCDPhysicsModel : public FCDEntity { private: typedef fm::map<xmlNode*, FUUri> ModelInstanceNameNodeMap; DeclareObjectType(FCDEntity); FCDPhysicsModelInstanceContainer instances; FCDPhysicsRigidBodyContainer rigidBodies; FCDPhysicsRigidConstraintContainer rigidConstraints; ModelInstanceNameNodeMap modelInstancesMap; public: /** Constructor: do not use directly. Create new physics models using the FCDLibrary::AddEntity function. @param document The COLLADA document that contains this physics model. */ FCDPhysicsModel(FCDocument* document); /** Destructor. */ virtual ~FCDPhysicsModel(); /** Retrieves the entity type for this class. This function is part of the FCDEntity interface. @return The entity type: PHYSICS_MODEL. */ virtual Type GetType() const { return FCDEntity::PHYSICS_MODEL; } /** Retrieves the instantiated physics models that are part of this physics model. @return The physics model instances. */ FCDPhysicsModelInstanceContainer& GetInstances() { return instances; } const FCDPhysicsModelInstanceContainer& GetInstances() const { return instances; } /**< See above. */ /** Retrieves the number of instantiated physics models that are part of this physics model. @return The number of instantiated physics models. */ size_t GetInstanceCount() const { return instances.size(); } /** Retrieves a specific instantiated physics model that is a part of this physics model. @param index The index of the instance. @return The physics model instance. */ FCDPhysicsModelInstance* GetInstance(size_t index) { FUAssert(index < instances.size(), return NULL); return instances.at(index); } const FCDPhysicsModelInstance* GetInstance(size_t index) const { FUAssert(index < instances.size(), return NULL); return instances.at(index); } /**< See above. */ /** Adds a instantiated physics model to this physics model. @param model The physics model to be instanced in this physics model. If this value is NULL, then there is no associated physics model for the instance yet. It should be filled in. @return The new physics model instance. */ FCDPhysicsModelInstance* AddPhysicsModelInstance(FCDPhysicsModel* model = NULL); /** Retrieves the rigid bodies that are a part of this physics model. @return The rigid bodies. */ FCDPhysicsRigidBodyContainer& GetRigidBodies() { return rigidBodies; } const FCDPhysicsRigidBodyContainer& GetRigidBodies() const { return rigidBodies; } /**< See above. */ /** Retrieves the number of rigid bodies that are a part of this physics model. @return The number of rigid bodies. */ size_t GetRigidBodyCount() const { return rigidBodies.size(); } /** Retrieves a specific rigid body that is a part of this physics model by its index. @param index The index of the rigid body. @return The rigid body. */ FCDPhysicsRigidBody* GetRigidBody(size_t index) { FUAssert(index < rigidBodies.size(), return NULL); return rigidBodies.at(index); } const FCDPhysicsRigidBody* GetRigidBody(size_t index) const { FUAssert(index < rigidBodies.size(), return NULL); return rigidBodies.at(index); } /**< See above. */ /** Retrieves a specific rigid body that is a part of this physics model by its sid. @param sid The sid of the rigid body. @return The rigid body. */ inline FCDPhysicsRigidBody* FindRigidBodyFromSid(const fm::string& sid) { return const_cast<FCDPhysicsRigidBody*>(const_cast<const FCDPhysicsModel*>(this)->FindRigidBodyFromSid(sid)); } const FCDPhysicsRigidBody* FindRigidBodyFromSid(const fm::string& sid) const; /**< See above. */ /** Adds a rigid body to this physics model. @return The new rigid body. */ FCDPhysicsRigidBody* AddRigidBody(); /** Retrieves the rigid constraints that are a part of this physics model. @return The rigid constraints. */ FCDPhysicsRigidConstraintContainer& GetRigidConstraints() { return rigidConstraints; } const FCDPhysicsRigidConstraintContainer& GetRigidConstraints() const { return rigidConstraints; } /**< See above. */ /** Retrieves the number of rigid constraints that are a part of this physics model. @return The number of rigid constraints. */ size_t GetRigidConstraintCount() const { return rigidConstraints.size(); } /** Retrieves a specific rigid constraint that is a part of tihs physics model by its index. @param index The index of the rigid constraint. @return The rigid constraint. */ FCDPhysicsRigidConstraint* GetRigidConstraint(size_t index) { FUAssert(index < GetRigidConstraintCount(), return NULL); return rigidConstraints.at(index); } const FCDPhysicsRigidConstraint* GetRigidConstraint(size_t index) const { FUAssert(index < GetRigidConstraintCount(), return NULL); return rigidConstraints.at(index); } /**< See above. */ /** Retrieves a specific rigid constraint that is a part of tihs physics model by its sid. @param sid The sid of the rigid constraint. @return The rigid constraint. */ inline FCDPhysicsRigidConstraint* FindRigidConstraintFromSid(const fm::string& sid) { return const_cast<FCDPhysicsRigidConstraint*>(const_cast<const FCDPhysicsModel*>(this)->FindRigidConstraintFromSid(sid)); } const FCDPhysicsRigidConstraint* FindRigidConstraintFromSid(const fm::string& sid) const; /**< See above. */ /** Adds a rigid constraint to this physics model. @return The new rigid constraint. */ FCDPhysicsRigidConstraint* AddRigidConstraint(); /** Copies the physics model into a clone. @param clone The empty clone. If this pointer is NULL, a new physics model will be created and you will need to release the returned pointer manually. @param cloneChildren Whether to recursively clone this entity's children. @return The clone. */ virtual FCDEntity* Clone(FCDEntity* clone = NULL, bool cloneChildren = false) const; /** [INTERNAL] Attaches the model instances. Because model instances can instance other models, the ordering is unknown so this cannot be done in the LoadFromXML call. This method should be called after LoadFromXML is applied to all physics models. */ bool AttachModelInstances(); /** [INTERNAL] Cleans up the sub identifiers. The sub identifiers must be unique with respect to its parent. This method corrects the sub ids if there are conflicts. */ virtual void CleanSubId(); }; #endif // _FCD_PHYSICSMODEL_H_
45.164706
210
0.772337
[ "model" ]
3140a12b11fe3db33e91219855d390db47386f54
661
h
C
src/services/pcn-dynmon/src/models/ExtractionOptions.h
stefalbi/polycube
f7b65ece48505458796cb4969d41677e991fbdc8
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-dynmon/src/models/ExtractionOptions.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-dynmon/src/models/ExtractionOptions.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
#pragma once #include "../base/ExtractionOptionsBase.h" class MetricConfig; using namespace polycube::service::model; class ExtractionOptions : public ExtractionOptionsBase { public: ExtractionOptions(MetricConfig &parent, const ExtractionOptionsJsonObject &conf); ~ExtractionOptions() = default; /** * When true, map entries are deleted after being extracted */ bool getEmptyOnRead() override; /** * When true, the map is swapped with a new one before reading its content to provide thread safety and atomicity on read/write operations */ bool getSwapOnRead() override; private: bool m_emptyOnRead; bool m_swapOnRead; };
23.607143
141
0.74584
[ "model" ]
3140c7ffb863cbd406e2c3edebf3eb1deea2dedd
2,694
c
C
bugs/macosx-ppc/gcc-4.0-03.c
IBorne/quest
906c11d9af6e9fbcabe7f2759b7502eb5d0dbabf
[ "BSD-2-Clause" ]
11
2015-09-12T03:09:48.000Z
2020-01-05T05:11:34.000Z
bugs/macosx-ppc/gcc-4.0-03.c
IBorne/quest
906c11d9af6e9fbcabe7f2759b7502eb5d0dbabf
[ "BSD-2-Clause" ]
null
null
null
bugs/macosx-ppc/gcc-4.0-03.c
IBorne/quest
906c11d9af6e9fbcabe7f2759b7502eb5d0dbabf
[ "BSD-2-Clause" ]
1
2021-03-01T10:58:58.000Z
2021-03-01T10:58:58.000Z
/* $Id: gcc-4.0-03.c 3 2006-04-29 13:17:19Z lindig $ */ /* ./quest -lua quest.lua -n 2 -test demo */ /* : tmp; /scratch/lindig/bin/gcc -v Using built-in specs. Configured with: /scratch/lindig/src/gcc/gcc/configure --cache-file=./config.cache --build=powerpc-apple-darwin7.6.0 --host=powerpc-apple-darwin7.6.0 --target=powerpc-apple-darwin7.6.0 --prefix=/scratch/lindig --with-gcc-version-trigger=/scratch/lindig/src/gcc/gcc/version.c --enable-languages=c --program-transform-name=s,y,y, --srcdir=../../gcc/gcc Thread model: posix gcc version 4.0.0 20050103 (experimental) : tmp; vim apple-bug-varg.c : tmp; /scratch/lindig/bin/gcc -o foo -O2 apple-bug-varg-2.c : tmp; ./foo failed in apple-bug-varg-2.c: 43 failed in apple-bug-varg-2.c: 44 */ #include <stdarg.h> extern int printf (char *, ...); static int errors = 0; static void failed( int line ) { printf ("failed in %s: %d\n", __FILE__, line); errors++; } static unsigned long int *av2 = (unsigned long int *) 361451618U; static struct bt2 { float fv2; } kv2 = { 3984.018652 }; static struct dt2 { char gv2; struct ct2 { unsigned char hv2; unsigned char iv2; } jv2; } lv2 = { '\x4f', { '\x27', '\x20' } }; static struct at2 { short int bv2; char cv2; } dv2 = { 14855, '\x3d' }; static double ev2 = 67318.083071; static unsigned long int * callee_af2( struct bt2 ap2, struct dt2 bp2, ... ) { va_list ap; struct at2 mv2; double nv2; va_start (ap, bp2); if (kv2.fv2 != ap2.fv2) failed (__LINE__); if (lv2.gv2 != bp2.gv2) failed (__LINE__); if (lv2.jv2.hv2 != bp2.jv2.hv2) failed (__LINE__); if (lv2.jv2.iv2 != bp2.jv2.iv2) failed (__LINE__); mv2 = va_arg (ap, struct at2); nv2 = va_arg (ap, double); if (mv2.bv2 != dv2.bv2) failed (__LINE__); if (mv2.cv2 != dv2.cv2) failed (__LINE__); if (nv2 != ev2) failed (__LINE__); va_end (ap); return av2; } static void caller_bf2( ) { unsigned long int *ov2; ov2 = callee_af2 (kv2, lv2, dv2, ev2); if (av2 != ov2) failed (__LINE__); } static union at1 { short int av1; double bv1; } *cv1 = (union at1 *) 440008236U; static union bt1 { double *ev1; char fv1; } gv1 = { (double *) 68753118U }; static double dv1 = 37253.636691; static union at1 * callee_af1( union bt1 ap1, ... ) { va_list ap; double hv1; va_start (ap, ap1); if (gv1.ev1 != ap1.ev1) failed (__LINE__); hv1 = va_arg (ap, double); if (hv1 != dv1) failed (__LINE__); va_end (ap); return cv1; } static void caller_bf1( ) { union at1 *iv1; iv1 = callee_af1 (gv1, dv1); if (cv1 != iv1) failed (__LINE__); } int main( int argc, char **argv ) { caller_bf2 (); caller_bf1 (); return errors; }
26.673267
78
0.634001
[ "model", "transform" ]
31421019e3c7095e7372e2d370eafc795d2952f6
6,392
h
C
eval/src/vespa/eval/onnx/onnx_wrapper.h
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
eval/src/vespa/eval/onnx/onnx_wrapper.h
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
eval/src/vespa/eval/onnx/onnx_wrapper.h
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #ifdef __APPLE__ #include <onnxruntime/core/session/onnxruntime_cxx_api.h> #else #include <onnxruntime/onnxruntime_cxx_api.h> #endif #include <vespa/vespalib/stllike/string.h> #include <vespa/eval/eval/value_type.h> #include <vespa/eval/eval/value.h> #include <vector> #include <map> #include <set> namespace vespalib::eval { struct Value; } namespace vespalib::eval { /** * Wrapper around an ONNX model handeled by onnxruntime. * * Create an Onnx object that will load your model and extract * information about inputs and outputs. Use an Onnx::WirePlanner to * bind vespa value types to each of the onnx model inputs. Ask the * wire planner about the vespa value types corresponding to each of * the model outputs for external wiring. Use the wire planner to make * a WireInfo object which is a simple struct indicating the concrete * onnx and vespa types to be used when converting inputs and * outputs. Create an Onnx::EvalContex based on the model and the wire * plan. Bind actual vespa values to the model inputs, invoke eval and * inspect the results. See the unit test (tests/tensor/onnx_wrapper) * for some examples. **/ class Onnx { public: // model optimization enum class Optimize { ENABLE, DISABLE }; // the size of a dimension struct DimSize { size_t value; vespalib::string name; DimSize() noexcept : value(0), name() {} DimSize(size_t size) noexcept : value(size), name() {} DimSize(const vespalib::string &symbol) noexcept : value(0), name(symbol) {} bool is_known() const { return (value > 0); } bool is_symbolic() const { return !name.empty(); } vespalib::string as_string() const; }; // supported onnx element types enum class ElementType { INT8, INT16, INT32, INT64, UINT8, UINT16, UINT32, UINT64, BFLOAT16, FLOAT, DOUBLE }; // information about a single input or output tensor struct TensorInfo { vespalib::string name; std::vector<DimSize> dimensions; ElementType elements; vespalib::string type_as_string() const; ~TensorInfo(); }; // concrete tensor type with known dimension sizes struct TensorType { ElementType elements; std::vector<int64_t> dimensions; TensorType(ElementType elements_in, std::vector<int64_t> dimensions_in) noexcept : elements(elements_in), dimensions(std::move(dimensions_in)) {} vespalib::string type_as_string() const; }; // how the model should be wired with inputs/outputs struct WireInfo { std::vector<ValueType> vespa_inputs; std::vector<Onnx::TensorType> onnx_inputs; std::vector<Onnx::TensorType> onnx_outputs; std::vector<ValueType> vespa_outputs; ~WireInfo(); }; // planning how we should wire the model based on input types class WirePlanner { private: std::map<vespalib::string,ValueType> _input_types; std::map<vespalib::string,size_t> _symbolic_sizes; std::map<vespalib::string,Onnx::TensorType> _output_types; bool need_model_probe(const Onnx &model) const; void do_model_probe(const Onnx &model); public: WirePlanner() : _input_types(), _symbolic_sizes(), _output_types() {} ~WirePlanner(); static CellType best_cell_type(Onnx::ElementType type); bool bind_input_type(const ValueType &vespa_in, const TensorInfo &onnx_in); std::map<vespalib::string,size_t> get_bound_sizes(const TensorInfo &onnx_in) const; void prepare_output_types(const Onnx &model); ValueType make_output_type(const TensorInfo &onnx_out) const; WireInfo get_wire_info(const Onnx &model) const; }; // evaluation context; use one per thread and keep model/wire_info alive // all parameter values are expected to be bound per evaluation // output values are pre-allocated and will not change class EvalContext { private: using param_fun_t = void (*)(EvalContext &, size_t i, const Value &); using result_fun_t = void (*)(EvalContext &, size_t i); const Onnx &_model; const WireInfo &_wire_info; Ort::MemoryInfo _cpu_memory; std::vector<Ort::Value> _param_values; std::vector<Ort::Value> _result_values; std::vector<Value::UP> _results; std::vector<param_fun_t> _param_binders; std::vector<std::pair<size_t,result_fun_t>> _result_converters; template <typename T> static void adapt_param(EvalContext &self, size_t idx, const Value &param); template <typename SRC, typename DST> static void convert_param(EvalContext &self, size_t idx, const Value &param); template <typename SRC, typename DST> static void convert_result(EvalContext &self, size_t idx); public: struct SelectAdaptParam; struct SelectConvertParam; struct SelectConvertResult; EvalContext(const Onnx &model, const WireInfo &wire_info); ~EvalContext(); size_t num_params() const { return _param_values.size(); } size_t num_results() const { return _result_values.size(); } void bind_param(size_t i, const Value &param); void eval(); void clear_results(); const Value &get_result(size_t i) const; }; private: // common stuff shared between model sessions class Shared { private: Ort::Env _env; Shared(); public: static Shared &get(); Ort::Env &env() { return _env; } }; static Ort::AllocatorWithDefaultOptions _alloc; Shared &_shared; Ort::SessionOptions _options; Ort::Session _session; std::vector<TensorInfo> _inputs; std::vector<TensorInfo> _outputs; std::vector<const char *> _input_name_refs; std::vector<const char *> _output_name_refs; void extract_meta_data() __attribute__((noinline)); public: Onnx(const vespalib::string &model_file, Optimize optimize); ~Onnx(); const std::vector<TensorInfo> &inputs() const { return _inputs; } const std::vector<TensorInfo> &outputs() const { return _outputs; } }; }
36.525714
113
0.666927
[ "object", "vector", "model" ]
3142a3b17655fa63adff5bc757db258687b53064
3,134
h
C
cognitics/include/sfa/Label.h
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
cognitics/include/sfa/Label.h
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
cognitics/include/sfa/Label.h
mikedig/cdb-productivity-api
e2bedaa550a8afa780c01f864d72e0aebd87dd5a
[ "MIT" ]
null
null
null
/************************************************************************* Copyright (c) 2019 Cognitics, 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. ****************************************************************************/ /*! \brief Provides sfa::Label \author Joshua Anghel <janghel@cognitics.net> \date 13 October 2010 \sa OpenGIS Implementation Specification for Geographic Information - Simple Feature Access (OGC 06-103r3 Version 1.2.0) */ #pragma once #include <string> namespace sfa { enum Location { INTERIOR = 0, BOUNDARY = 1, EXTERIOR = 2, UNKNOWN = 3 }; /*!\class sfa::Label Label.h Label.h \brief Label Provides information on a partition of space created by one or more Geometries including the dimension of the space and the location of that space with respect to up to two Geometries. \sa OpenGIS Implementation Specification for Geographic Information - Simple Feature Access (OGC 06-103r3 Version 1.2.0) */ class Label { public: Location loc[2]; int dim; Label(int dimension = -1); Label(Location a, Location b, int dimension = -1); ~Label(void) {} Location& operator[](int i); //! Switches the values of the Locations for the two Geometries in the Label void flip(void); /*!\brief Copies the information of another Label into this Label using copyLabel(Label l, int n). \param l Label to copy information from. */ void copyLabel(const Label& l); /*!\brief Copies the information from another Label for one Geometry only (using the Mod-2 boundary rule). The Mod-2 boundary rule cause the Location in question to be changed to INTERIOR if both the current Location and copy Location are BOUNDARY. If this is not the case, then the Location chosen between the current and copy Location will be the Location with lower enumberated type. \param l Label to copy information from \param n Geometry index to copy information for */ void copyLabel(const Label& l, int n); //! Returns the information contained in this Label as a std::string. std::string print(void) const; }; }
38.691358
120
0.702297
[ "geometry" ]
3142a657dc12343367f10f90077b554431e138fd
8,498
c
C
Areas/NewbieIsle/NewbieIsle/o/Room/fishing_stone.c
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
Areas/NewbieIsle/NewbieIsle/o/Room/fishing_stone.c
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
Areas/NewbieIsle/NewbieIsle/o/Room/fishing_stone.c
yodakingdoms/kingdoms
831b74ba4a086de69cce213ad2398f646c3efb39
[ "MIT" ]
null
null
null
// Rest in this room -> Fall asleep -> fall into water -> some underwater // area perhaps? //------------------------------------------------------------------------ // Added Dreadlord guild to the guilds that don't have to wield the // pole to fish, doh. Dreadlords weren't open when I wrote this room ;) // Yoda - 990418 //------------------------------------------------------------------------ #pragma strict_types #include "../def.h" inherit MASTER_ROOM; inherit MOD_SOUND; void create_object(void); void reset(int arg); void init(void); int do_swim(string str); int do_wade(string str); int do_fish(string str); void watch_float(object fisherman); void catch_fish(object fisherman); void threw_one_back(void); void reset_player(object player); int query_fish_tale_quest_fishing_place(void); mapping fish_caught = ([]); // [ player:number of fish caught this boot ] object *fishermen = ({}); // To check which people are actually fishing. void create_object(void) { set_short("On a stone in the water"); set_long("You are standing on a big stone a few feet from the shore. "+ "The water is clear and it laps gently against the stone. You "+ "wonder why you bothered coming here at all. Seems like there's "+ "not much to do here except look at the small fishes swimming "+ "round the stone near the bottom. You feel safe and calm here as "+ "the island rises over you to the east and the sea stretches out "+ "to the west.\n"); set_new_light(5); set_skip_obvious(1); set_dragon_visibility(3); set_room_hint("Hey, look at those fish. Looks as if this place would be "+ "a good place to sit down with a fishing pole. Perhaps "+ "you could find one somewhere else on the island? I've heard "+ "the best places to look for fishing poles are usually "+ "someplace that is not too far from the shore either.;)\n"); add_item("stone","It's the one under your feet"); add_item("shore","The shore is not far from here. You could easily wade "+ "back there"); add_item("water","It's very clear. You can see the bottom and several "+ "fishes swimming around down there"); add_item("bottom","The bottom looks sandy and nice"); add_item("sand","The bottom is covered with a layer of fine sand"); add_item("fishes","Many different kinds of fish swim around this "+ "stone. This might be a good place to do some fishing!!!"); add_item("island","The tiny little island they call Newbie Island"); add_item("sea","The great grey and blue sea. Far in the distance you "+ "see the continent of Larsia"); add_item("continent|larsia|Larsia","You see it far it the distance to the "+ "west"); add_sounds(30,70,({"The waves lap gently against the stone.\n", "A fish jumps out of the water a yard from the stone "+ "disappearing under the surface again with a *plask*.\n", "A galley ship passes close to the island.\n"})); reset(0); } void reset(int arg) { // Some people like sorcerers waste their fish by // turning them into sp and can't be reset.. fish_caught = ([]); } void init(void) { "/sys/admin/room/admin_room"->visit(987); add_action("do_swim","swim"); add_action("do_wade","wade"); add_action("do_fish","fish"); ::init(); } int do_swim(string str) { W("You wouldn't want to scare the fish away!! Besides... Those fish "+ "might not be very big, but some of them look quite nasty...\n"); S(TP->QN+" looks down into the water for a while.\n"); TP->command("worried"); return 1; } int do_wade(string str) { if(str == "back" || str == "to shore" || str == "shore") { if(member_array(TP,fishermen) > -1) { W("Patience is the sign of any great fisherman. You can't just leave "+ "while your float is bobbing on the waves in front of you.\n"+ "You stay for a while longer.\n"); return 1; } W("You jump down from the stone, back into the water and wade "+ "back to the shore.\n"); TP->move_player("jumps down from the stone and wades back to shore", NROOM+"shore3", "comes wading to the shore from the stone", 1); return 1; } notify_fail("Wade where?\n"); } int do_fish(string str) { if(present("fishingpole",TP) || present("fishing pole",TP) || present("fishpole",TP) || present("fish pole",TP)) { if(TP->query_weapon(1)->id("fishingpole") || TP->query_weapon(1)->id("fishing pole") || TP->query_weapon(1)->id("fishpole") || TP->query_weapon(1)->id("fish pole") || TP->query_guild() == NINJA || TP->query_guild() == DEMON || TP->query_guild() == MONK || TP->query_guild() == DREADLORD) { if(fish_caught[TP] >= 5) { W("You don't think you'll be able to catch more fish right now "+ "than those you already have caught.\n"); return 1; } if(member_array(TP,fishermen) > -1) { W("You're already fishing.\n"); return 1; } W("You throw the hook and the float into the water and sit down "+ "to do some fishing!\n"); S(TP->QN+" sits down to fish for a while.\n"); fishermen += ({TP}); set_alarm(4.0,0.0,"watch_float",TP); return 1; } else { W("It would be easier to fish if you wielded your fishing pole.\n"); S(TP->QN+" tries to fish without using the fishing pole "+TP->QPR+ " has. How odd.\n"); return 1; } } notify_fail("You need a fishing pole to fish!\n"); } void watch_float(object fisherman) { set_this_player(fisherman); // Diablos if(present("fishingpole",fisherman) || present("fishing pole",fisherman) || present("fishpole",fisherman) || present("fish pole",fisherman)) { if(fisherman->query_weapon(1)->id("fishingpole") || fisherman->query_weapon(1)->id("fishing pole") || fisherman->query_weapon(1)->id("fishpole") || fisherman->query_weapon(1)->id("fish pole") || fisherman->query_guild() == NINJA || fisherman->query_guild() == DEMON || fisherman->query_guild() == MONK || fisherman->query_guild() == DREADLORD) { tell_object(fisherman,"You watch the float bob up and down as the " + "water gently laps against the stone where you sit.\n"); set_alarm(4.0,0.0,"catch_fish",fisherman); } else { fishermen -= ({ fisherman }); } } else { fishermen -= ({ fisherman }); } } void catch_fish(object fisherman) { object fish; set_this_player(fisherman); // Diablos if(present("fishingpole",fisherman) || present("fishing pole",fisherman) || present("fishpole",fisherman) || present("fish pole",fisherman)) { if(fisherman->query_weapon(1)->id("fishingpole") || fisherman->query_weapon(1)->id("fishing pole") || fisherman->query_weapon(1)->id("fishpole") || fisherman->query_weapon(1)->id("fish pole") || fisherman->query_guild() == NINJA || fisherman->query_guild() == DEMON || fisherman->query_guild() == MONK || fisherman->query_guild() == DREADLORD) { // Don't think many players will have fishing skill, but perhaps...;) if(fisherman->query_skill("fishing") + 30 > random(50)) { W("You feel a fish grab the hook and you pull it up. It lands on " + "the stone next to you.\nCongratulations! You caught a fish!\n"); S(fisherman->QN+" pulls a fish out of the water with "+fisherman->QPO+ " fishing pole!\n"); fish = make(NOBJECT+"fish"); fish->set_catcher(fisherman); ++fish_caught[fisherman]; } else { W("You feel a fish nibble the bait of the hook, but pull it up "+ "too late. Some fisherman you are! *heh* Perhaps you should try "+ "again.\n"); S(fisherman->QN+" pulls the hook out of the water, but apparently "+ "too late since there is no fish on it. Some fisherman, *heh*\n"); } } } fishermen -= ({fisherman}); } void threw_one_back(void) { if(fish_caught[TP] > 0) { --fish_caught[TP]; } } void reset_player(object player) { fish_caught[TP] = 0; } int query_fish_tale_quest_fishing_place(void) { return 1; }
33.195313
79
0.601553
[ "object" ]
3145c43fd8d24d5ec618a48a5961d18ffb4820de
10,578
c
C
tests/t524-operator.c
wence-/libCEED
c785ad36304ed34c5edefb75cf1a0fe5445db17b
[ "BSD-2-Clause" ]
null
null
null
tests/t524-operator.c
wence-/libCEED
c785ad36304ed34c5edefb75cf1a0fe5445db17b
[ "BSD-2-Clause" ]
null
null
null
tests/t524-operator.c
wence-/libCEED
c785ad36304ed34c5edefb75cf1a0fe5445db17b
[ "BSD-2-Clause" ]
null
null
null
/// @file /// Test CeedOperatorApplyAdd for composite operator /// \test CeedOperatorApplyAdd for composite operator #include <ceed.h> #include <stdlib.h> #include <math.h> #include "t320-basis.h" #include "t510-operator.h" /* The mesh comprises of two rows of 3 quadralaterals followed by one row of 6 triangles: _ _ _ |_|_|_| |_|_|_| |/|/|/| */ int main(int argc, char **argv) { Ceed ceed; CeedElemRestriction elem_restr_x_tet, elem_restr_u_tet, elem_restr_qd_i_tet, elem_restr_x_hex, elem_restr_u_hex, elem_restr_qd_i_hex; CeedBasis basis_x_tet, basis_u_tet, basis_x_hex, basis_u_hex; CeedQFunction qf_setup_tet, qf_mass_tet, qf_setup_hex, qf_mass_hex; CeedOperator op_setup_tet, op_mass_tet, op_setup_hex, op_mass_hex, op_setup, op_mass; CeedVector q_data_tet, q_data_hex, X, U, V; const CeedScalar *hv; CeedInt nelem_tet = 6, P_tet = 6, Q_tet = 4, nelem_hex = 6, P_hex = 3, Q_hex = 4, dim = 2; CeedInt nx = 3, ny = 3, nx_tet = 3, ny_tet = 1, nx_hex = 3; CeedInt row, col, offset; CeedInt num_dofs = (nx*2+1)*(ny*2+1), num_qpts_tet = nelem_tet*Q_tet, num_qpts_hex = nelem_hex*Q_hex*Q_hex; CeedInt ind_x_tet[nelem_tet*P_tet], ind_x_hex[nelem_hex*P_hex*P_hex]; CeedScalar x[dim*num_dofs]; CeedScalar q_ref[dim*Q_tet], q_weight[Q_tet]; CeedScalar interp[P_tet*Q_tet], grad[dim*P_tet*Q_tet]; CeedScalar sum; CeedInit(argv[1], &ceed); // DoF Coordinates for (CeedInt i=0; i<ny*2+1; i++) for (CeedInt j=0; j<nx*2+1; j++) { x[i+j*(ny*2+1)+0*num_dofs] = (CeedScalar) i / (2*ny); x[i+j*(ny*2+1)+1*num_dofs] = (CeedScalar) j / (2*nx); } CeedVectorCreate(ceed, dim*num_dofs, &X); CeedVectorSetArray(X, CEED_MEM_HOST, CEED_USE_POINTER, x); // Qdata Vectors CeedVectorCreate(ceed, num_qpts_tet, &q_data_tet); CeedVectorCreate(ceed, num_qpts_hex, &q_data_hex); // _tet Elements for (CeedInt i=0; i<nelem_tet/2; i++) { col = i % nx_tet; row = i / nx_tet; offset = col*2 + row*(nx_tet*2+1)*2; ind_x_tet[i*2*P_tet + 0] = 2 + offset; ind_x_tet[i*2*P_tet + 1] = 9 + offset; ind_x_tet[i*2*P_tet + 2] = 16 + offset; ind_x_tet[i*2*P_tet + 3] = 1 + offset; ind_x_tet[i*2*P_tet + 4] = 8 + offset; ind_x_tet[i*2*P_tet + 5] = 0 + offset; ind_x_tet[i*2*P_tet + 6] = 14 + offset; ind_x_tet[i*2*P_tet + 7] = 7 + offset; ind_x_tet[i*2*P_tet + 8] = 0 + offset; ind_x_tet[i*2*P_tet + 9] = 15 + offset; ind_x_tet[i*2*P_tet + 10] = 8 + offset; ind_x_tet[i*2*P_tet + 11] = 16 + offset; } // -- Restrictions CeedElemRestrictionCreate(ceed, nelem_tet, P_tet, dim, num_dofs, dim*num_dofs, CEED_MEM_HOST, CEED_USE_POINTER, ind_x_tet, &elem_restr_x_tet); CeedElemRestrictionCreate(ceed, nelem_tet, P_tet, 1, 1, num_dofs, CEED_MEM_HOST, CEED_USE_POINTER, ind_x_tet, &elem_restr_u_tet); CeedInt strides_qd_tet[3] = {1, Q_tet, Q_tet}; CeedElemRestrictionCreateStrided(ceed, nelem_tet, Q_tet, 1, num_qpts_tet, strides_qd_tet, &elem_restr_qd_i_tet); // -- Bases buildmats(q_ref, q_weight, interp, grad); CeedBasisCreateH1(ceed, CEED_TOPOLOGY_TRIANGLE, dim, P_tet, Q_tet, interp, grad, q_ref, q_weight, &basis_x_tet); buildmats(q_ref, q_weight, interp, grad); CeedBasisCreateH1(ceed, CEED_TOPOLOGY_TRIANGLE, 1, P_tet, Q_tet, interp, grad, q_ref, q_weight, &basis_u_tet); // -- QFunctions CeedQFunctionCreateInterior(ceed, 1, setup, setup_loc, &qf_setup_tet); CeedQFunctionAddInput(qf_setup_tet, "weight", 1, CEED_EVAL_WEIGHT); CeedQFunctionAddInput(qf_setup_tet, "dx", dim*dim, CEED_EVAL_GRAD); CeedQFunctionAddOutput(qf_setup_tet, "rho", 1, CEED_EVAL_NONE); CeedQFunctionCreateInterior(ceed, 1, mass, mass_loc, &qf_mass_tet); CeedQFunctionAddInput(qf_mass_tet, "rho", 1, CEED_EVAL_NONE); CeedQFunctionAddInput(qf_mass_tet, "u", 1, CEED_EVAL_INTERP); CeedQFunctionAddOutput(qf_mass_tet, "v", 1, CEED_EVAL_INTERP); // -- Operators // ---- Setup _tet CeedOperatorCreate(ceed, qf_setup_tet, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_setup_tet); CeedOperatorSetField(op_setup_tet, "weight", CEED_ELEMRESTRICTION_NONE, basis_x_tet, CEED_VECTOR_NONE); CeedOperatorSetField(op_setup_tet, "dx", elem_restr_x_tet, basis_x_tet, CEED_VECTOR_ACTIVE); CeedOperatorSetField(op_setup_tet, "rho", elem_restr_qd_i_tet, CEED_BASIS_COLLOCATED, q_data_tet); // ---- Mass _tet CeedOperatorCreate(ceed, qf_mass_tet, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_mass_tet); CeedOperatorSetField(op_mass_tet, "rho", elem_restr_qd_i_tet, CEED_BASIS_COLLOCATED, q_data_tet); CeedOperatorSetField(op_mass_tet, "u", elem_restr_u_tet, basis_u_tet, CEED_VECTOR_ACTIVE); CeedOperatorSetField(op_mass_tet, "v", elem_restr_u_tet, basis_u_tet, CEED_VECTOR_ACTIVE); // _hex Elements for (CeedInt i=0; i<nelem_hex; i++) { col = i % nx_hex; row = i / nx_hex; offset = (nx_tet*2+1)*(ny_tet*2)*(1+row) + col*2; for (CeedInt j=0; j<P_hex; j++) for (CeedInt k=0; k<P_hex; k++) ind_x_hex[P_hex*(P_hex*i+k)+j] = offset + k*(nx_hex*2+1) + j; } // -- Restrictions CeedElemRestrictionCreate(ceed, nelem_hex, P_hex*P_hex, dim, num_dofs, dim*num_dofs, CEED_MEM_HOST, CEED_USE_POINTER, ind_x_hex, &elem_restr_x_hex); CeedElemRestrictionCreate(ceed, nelem_hex, P_hex*P_hex, 1, 1, num_dofs, CEED_MEM_HOST, CEED_USE_POINTER, ind_x_hex, &elem_restr_u_hex); CeedInt strides_qd_hex[3] = {1, Q_hex*Q_hex, Q_hex*Q_hex}; CeedElemRestrictionCreateStrided(ceed, nelem_hex, Q_hex*Q_hex, 1, num_qpts_hex, strides_qd_hex, &elem_restr_qd_i_hex); // -- Bases CeedBasisCreateTensorH1Lagrange(ceed, dim, dim, P_hex, Q_hex, CEED_GAUSS, &basis_x_hex); CeedBasisCreateTensorH1Lagrange(ceed, dim, 1, P_hex, Q_hex, CEED_GAUSS, &basis_u_hex); // -- QFunctions CeedQFunctionCreateInterior(ceed, 1, setup, setup_loc, &qf_setup_hex); CeedQFunctionAddInput(qf_setup_hex, "weight", 1, CEED_EVAL_WEIGHT); CeedQFunctionAddInput(qf_setup_hex, "dx", dim*dim, CEED_EVAL_GRAD); CeedQFunctionAddOutput(qf_setup_hex, "rho", 1, CEED_EVAL_NONE); CeedQFunctionCreateInterior(ceed, 1, mass, mass_loc, &qf_mass_hex); CeedQFunctionAddInput(qf_mass_hex, "rho", 1, CEED_EVAL_NONE); CeedQFunctionAddInput(qf_mass_hex, "u", 1, CEED_EVAL_INTERP); CeedQFunctionAddOutput(qf_mass_hex, "v", 1, CEED_EVAL_INTERP); // -- Operators CeedOperatorCreate(ceed, qf_setup_hex, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_setup_hex); CeedOperatorSetField(op_setup_hex, "weight", CEED_ELEMRESTRICTION_NONE, basis_x_hex, CEED_VECTOR_NONE); CeedOperatorSetField(op_setup_hex, "dx", elem_restr_x_hex, basis_x_hex, CEED_VECTOR_ACTIVE); CeedOperatorSetField(op_setup_hex, "rho", elem_restr_qd_i_hex, CEED_BASIS_COLLOCATED, q_data_hex); CeedOperatorCreate(ceed, qf_mass_hex, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_mass_hex); CeedOperatorSetField(op_mass_hex, "rho", elem_restr_qd_i_hex, CEED_BASIS_COLLOCATED, q_data_hex); CeedOperatorSetField(op_mass_hex, "u", elem_restr_u_hex, basis_u_hex, CEED_VECTOR_ACTIVE); CeedOperatorSetField(op_mass_hex, "v", elem_restr_u_hex, basis_u_hex, CEED_VECTOR_ACTIVE); // Composite Operators CeedCompositeOperatorCreate(ceed, &op_setup); CeedCompositeOperatorAddSub(op_setup, op_setup_tet); CeedCompositeOperatorAddSub(op_setup, op_setup_hex); CeedCompositeOperatorCreate(ceed, &op_mass); CeedCompositeOperatorAddSub(op_mass, op_mass_tet); CeedCompositeOperatorAddSub(op_mass, op_mass_hex); // Apply Setup Operator CeedOperatorApply(op_setup, X, CEED_VECTOR_NONE, CEED_REQUEST_IMMEDIATE); // Apply Mass Operator CeedVectorCreate(ceed, num_dofs, &U); CeedVectorSetValue(U, 1.0); CeedVectorCreate(ceed, num_dofs, &V); CeedVectorSetValue(V, 0.0); // Apply CeedOperatorApplyAdd(op_mass, U, V, CEED_REQUEST_IMMEDIATE); // Check output CeedVectorGetArrayRead(V, CEED_MEM_HOST, &hv); sum = 0.; for (CeedInt i=0; i<num_dofs; i++) sum += hv[i]; if (fabs(sum-1.)>1000.*CEED_EPSILON) // LCOV_EXCL_START printf("Computed Area: %f != True Area: 1.0\n", sum); // LCOV_EXCL_STOP CeedVectorRestoreArrayRead(V, &hv); // Apply Add CeedVectorSetValue(V, 1.0); CeedOperatorApplyAdd(op_mass, U, V, CEED_REQUEST_IMMEDIATE); // Check output CeedVectorGetArrayRead(V, CEED_MEM_HOST, &hv); sum = -num_dofs; for (CeedInt i=0; i<num_dofs; i++) sum += hv[i]; if (fabs(sum-1.)>1000.*CEED_EPSILON) // LCOV_EXCL_START printf("Computed Area: %f != True Area: 1.0\n", sum); // LCOV_EXCL_STOP CeedVectorRestoreArrayRead(V, &hv); // Cleanup CeedQFunctionDestroy(&qf_setup_tet); CeedQFunctionDestroy(&qf_mass_tet); CeedOperatorDestroy(&op_setup_tet); CeedOperatorDestroy(&op_mass_tet); CeedQFunctionDestroy(&qf_setup_hex); CeedQFunctionDestroy(&qf_mass_hex); CeedOperatorDestroy(&op_setup_hex); CeedOperatorDestroy(&op_mass_hex); CeedOperatorDestroy(&op_setup); CeedOperatorDestroy(&op_mass); CeedElemRestrictionDestroy(&elem_restr_u_tet); CeedElemRestrictionDestroy(&elem_restr_x_tet); CeedElemRestrictionDestroy(&elem_restr_qd_i_tet); CeedElemRestrictionDestroy(&elem_restr_u_hex); CeedElemRestrictionDestroy(&elem_restr_x_hex); CeedElemRestrictionDestroy(&elem_restr_qd_i_hex); CeedBasisDestroy(&basis_u_tet); CeedBasisDestroy(&basis_x_tet); CeedBasisDestroy(&basis_u_hex); CeedBasisDestroy(&basis_x_hex); CeedVectorDestroy(&X); CeedVectorDestroy(&U); CeedVectorDestroy(&V); CeedVectorDestroy(&q_data_tet); CeedVectorDestroy(&q_data_hex); CeedDestroy(&ceed); return 0; }
38.326087
82
0.664303
[ "mesh" ]
3152629fbfb25d75aaadbcd5de41598a660b928b
2,703
h
C
oreore/oreore/cocos2d/utils/AssetLoader.h
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
4
2015-01-26T17:46:26.000Z
2018-12-28T09:09:19.000Z
oreore/oreore/cocos2d/utils/AssetLoader.h
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
null
null
null
oreore/oreore/cocos2d/utils/AssetLoader.h
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
null
null
null
#ifndef __OREORE_COCOS2D_ASSETLOADER_H__ #define __OREORE_COCOS2D_ASSETLOADER_H__ #include <functional> #include "cocos2d.h" namespace oreore { class AssetLoaderWorker; typedef void (cocos2d::CCObject::*SEL_AssetLoaded)(const std::string &filename, const std::size_t count, const std::size_t total); #define assetloaded_selector(_SELECTOR) (SEL_AssetLoaded)(&_SELECTOR) struct AssetData { enum AssetType { SpriteFrame, Texture }; AssetType type; std::string filename; AssetData(const std::string &filename, const AssetType type) : type(type), filename(filename) { } AssetData() : filename(""), type(Texture) { } }; class AssetLoaderWorkerChild : public cocos2d::Ref { friend class AssetLoaderWorker; private: AssetLoaderWorker *worker; AssetData data; AssetLoaderWorkerChild(AssetLoaderWorker *worker, const AssetData &data); AssetLoaderWorkerChild(const AssetLoaderWorkerChild &rhs) { } ~AssetLoaderWorkerChild() { CCLOG("AssetLoaderWorkerChild work finished!"); } void operator=(const AssetLoaderWorkerChild &rhs) { } }; class AssetLoaderWorker : public cocos2d::Ref { friend class AssetLoader; friend class AssetLoaderWorkerChild; typedef std::vector<AssetData> AssetList; private: std::size_t count; std::function<void(const std::string &filename, const std::size_t count, const std::size_t total)> assetLoadedCallback; std::function<void()> callback; AssetList assets; AssetLoaderWorker() : count(0) { } AssetLoaderWorker(const AssetLoaderWorker &rhs) { } ~AssetLoaderWorker() { CCLOG("AssetLoaderWorker work finished!"); } void operator=(const AssetLoaderWorker &rhs) { } void assetLoaded(const AssetData &data, cocos2d::Texture2D *tex); void load( const std::function<void()> &callback, const std::function<void(const std::string &filename, const std::size_t count, const std::size_t total)> &assetLoadedCallback ); void addAsset(const AssetData &data); public: }; class AssetLoader { private: AssetLoaderWorker *worker; public: AssetLoader(); void addTexture(const std::string &filename); void addSpriteFrame(const std::string &filename); void load( const std::function<void()> &callback, const std::function<void(const std::string &filename, const std::size_t count, const std::size_t total)> &assetLoadedCallback = nullptr ); }; } #endif
31.068966
147
0.649649
[ "vector" ]
3159ef92378f1c34ebcf6c6db08995316be6b582
9,690
h
C
engine/tests/utils/gdf/library/table.h
anniyanvr/blazingsql
3f9d26e8256a287924da761fd2216bdc43a29717
[ "Apache-2.0" ]
1
2020-01-11T15:43:22.000Z
2020-01-11T15:43:22.000Z
engine/tests/utils/gdf/library/table.h
anniyanvr/blazingsql
3f9d26e8256a287924da761fd2216bdc43a29717
[ "Apache-2.0" ]
3
2020-07-26T05:17:38.000Z
2021-03-22T16:36:11.000Z
engine/tests/utils/gdf/library/table.h
anniyanvr/blazingsql
3f9d26e8256a287924da761fd2216bdc43a29717
[ "Apache-2.0" ]
1
2021-03-22T15:59:39.000Z
2021-03-22T15:59:39.000Z
#pragma once #include <cassert> #include <cmath> #include <iomanip> #include <ios> #include <iostream> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "any.h" #include "column.h" #include "gdf_wrapper/gdf_wrapper.cuh" #include "hd.h" #include "vector.h" namespace gdf { namespace library { class Table { public: Table() = default; //! \deprecated Table & operator=(const Table &) = default; //! \deprecated Table(const std::string & name, std::vector<std::shared_ptr<Column>> && columns) : name_{name}, columns_{std::move(columns)} {} const Column & operator[](const std::size_t i) const { return *columns_[i]; } std::vector<gdf_column_cpp> ToGdfColumnCpps() const; bool operator==(const Table & other) const { if((name_ != other.name_) || (columns_.size() != other.columns_.size())) { std::cerr << "Table: name_ != other.name_ || (columns_.size() != other.columns_.size()" << "\n"; return false; } for(std::size_t i = 0; i < columns_.size(); i++) { if((*columns_[i]) != (*other.columns_[i])) { return false; } } return true; } std::string name() const { return name_; } size_t size() const { return columns_.size(); } std::vector<std::string> ColumnNames() const { std::vector<std::string> names; names.resize(size()); std::transform(columns_.cbegin(), columns_.cend(), names.begin(), [](const std::shared_ptr<Column> & column) { return column->name(); }); return names; } std::vector<std::shared_ptr<Column>>::iterator begin() { return columns_.begin(); } std::vector<std::shared_ptr<Column>>::iterator end() { return columns_.end(); } template <typename StreamType> void print(StreamType & stream) const { _size_columns(); unsigned int cell_padding = 1; // Start computing the total width // First - we will have size() + 1 "|" characters unsigned int total_width = size() + 1; // Now add in the size of each colum for(auto & col_size : column_sizes_) total_width += col_size + (2 * cell_padding); // Print out the top line stream << "## TABLE_NAME:" << this->name() << "\n"; stream << std::string(total_width, '-') << "\n"; std::vector<std::string> headers; for(unsigned int i = 0; i < size(); i++) headers.push_back(this->columns_[i]->name()); // Print out the headers stream << "|"; for(unsigned int i = 0; i < size(); i++) { // Must find the center of the column auto half = column_sizes_[i] / 2; half -= headers[i].size() / 2; stream << std::string(cell_padding, ' ') << std::setw(column_sizes_[i]) << std::left << std::string(half, ' ') + headers[i] << std::string(cell_padding, ' ') << "|"; } stream << "\n"; // Print out the line below the header stream << std::string(total_width, '-') << "\n"; // Now print the rows of the VTable for(size_t i = 0; i < _num_rows(); i++) { stream << "|"; for(size_t j = 0; j < size(); j++) { stream << std::string(cell_padding, ' ') << std::setw(column_sizes_[j]) << columns_[j]->get_as_str(i) << std::string(cell_padding, ' ') << "|"; } stream << "\n"; } // Print out the line below the header stream << std::string(total_width, '-') << "\n"; } protected: void _size_columns() const { column_sizes_.resize(size()); // Temporary for querying each row std::vector<unsigned int> column_sizes(size()); // Start with the size of the headers for(unsigned int i = 0; i < size(); i++) column_sizes_[i] = this->columns_[i]->name().size(); } size_t _num_rows() const { return size() == 0 ? 0 : columns_[0]->size(); //@todo check and assert this } private: std::string name_; std::vector<std::shared_ptr<Column>> columns_; mutable std::vector<unsigned int> column_sizes_; }; std::vector<gdf_column_cpp> Table::ToGdfColumnCpps() const { std::vector<gdf_column_cpp> gdfColumnsCpps; gdfColumnsCpps.resize(columns_.size()); std::transform( columns_.cbegin(), columns_.cend(), gdfColumnsCpps.begin(), [](const std::shared_ptr<Column> & column) { return column->ToGdfColumnCpp(); }); return gdfColumnsCpps; } class TableBuilder { public: TableBuilder(const std::string && name, std::vector<ColumnBuilder> builders) : name_{std::move(name)}, builders_{builders} {} Table Build(const std::size_t length) const { std::vector<std::shared_ptr<Column>> columns; columns.resize(builders_.size()); std::transform( std::begin(builders_), std::end(builders_), columns.begin(), [length](const ColumnBuilder & builder) { return std::move(builder.Build(length)); }); return Table(name_, std::move(columns)); } Table Build(const std::vector<std::size_t> & lengths) const { std::vector<std::shared_ptr<Column>> columns; columns.resize(builders_.size()); std::transform( builders_.cbegin(), builders_.cend(), columns.begin(), [this, lengths](const ColumnBuilder & builder) { return std::move(builder.Build(lengths[std::distance( builders_.cbegin(), static_cast<std::vector<ColumnBuilder>::const_iterator>(&builder))])); }); return Table(name_, std::move(columns)); } private: const std::string name_; std::vector<ColumnBuilder> builders_; }; class LiteralTableBuilder : public TableBuilder { public: LiteralTableBuilder(const std::string && name, std::vector<LiteralColumnBuilder> builders) : TableBuilder{std::forward<const std::string>(name), ColumnBuildersFrom(builders)}, builders_{builders} { lengths_.resize(builders.size()); std::transform( builders.begin(), builders.end(), lengths_.begin(), [](const LiteralColumnBuilder & literalBuilder) { return literalBuilder.length(); }); } Table Build(const std::size_t length = 0) const { return TableBuilder::Build(lengths_); } private: static std::vector<ColumnBuilder> ColumnBuildersFrom(std::vector<LiteralColumnBuilder> & literalBuilders) { std::vector<ColumnBuilder> builders; builders.resize(literalBuilders.size()); std::transform(literalBuilders.begin(), literalBuilders.end(), builders.begin(), [](const LiteralColumnBuilder & literalBuilder) { return literalBuilder; }); return builders; } std::vector<LiteralColumnBuilder> builders_; std::vector<std::size_t> lengths_; }; class GdfColumnCppsTableBuilder { public: GdfColumnCppsTableBuilder(const std::string & name, const std::vector<gdf_column_cpp> & column_cpps) : name_{name}, column_cpps_{column_cpps} {} Table Build() { return LiteralTableBuilder{std::move(name_), ColumnBuildersFrom(column_cpps_)}.Build(); } private: std::vector<LiteralColumnBuilder> ColumnBuildersFrom(const std::vector<gdf_column_cpp> & column_cpps) { std::vector<LiteralColumnBuilder> builders; builders.resize(column_cpps.size()); std::transform( column_cpps.cbegin(), column_cpps.cend(), builders.begin(), [](const gdf_column_cpp & column_cpp) { return static_cast<LiteralColumnBuilder>(GdfColumnCppColumnBuilder(column_cpp.name(), column_cpp)); }); return builders; } const std::string name_; const std::vector<gdf_column_cpp> column_cpps_; }; // helper function to tuple_each a tuple of any size template <class Tuple, typename Func, std::size_t N> struct TupleEach { static void tuple_each(Tuple & t, Func & f) { TupleEach<Tuple, Func, N - 1>::tuple_each(t, f); f(std::get<N - 1>(t)); } }; template <class Tuple, typename Func> struct TupleEach<Tuple, Func, 1> { static void tuple_each(Tuple & t, Func & f) { f(std::get<0>(t)); } }; template <typename Tuple, typename Func> void tuple_each(Tuple & t, Func && f) { TupleEach<Tuple, Func, std::tuple_size<Tuple>::value>::tuple_each(t, f); } // end helper function struct _GetValuesLambda { size_t & i; size_t & j; std::vector<std::vector<linb::any>> & values; template <typename T> void operator()(T && value) const { values[j][i] = value; j++; } }; struct _FillColumnLambda { std::vector<std::vector<linb::any>> & values; std::vector<ColumnFiller> & builders; std::vector<std::string> headers; mutable size_t i; _FillColumnLambda(std::vector<std::vector<linb::any>> & values, std::vector<ColumnFiller> & builders, std::vector<std::string> & headers) : values{values}, builders{builders}, headers{headers}, i{0} {} template <typename T> void operator()(T value) const { assert(i < headers.size()); auto name = headers[i]; std::vector<decltype(value)> column_values; for(auto && any_val : values[i]) { column_values.push_back(linb::any_cast<decltype(value)>(any_val)); } builders.push_back(ColumnFiller{name, column_values}); i++; } }; template <class... Ts> class TableRowBuilder { public: typedef std::tuple<Ts...> DataTuple; TableRowBuilder(const std::string & name, std::vector<std::string> headers, std::initializer_list<DataTuple> rows) : name_{name}, headers_(headers), rows_{rows}, ncols_{std::tuple_size<DataTuple>::value}, nrows_{rows.size()} {} Table Build() { size_t i = 0; std::vector<std::vector<linb::any>> values(ncols_, std::vector<linb::any>(nrows_)); for(DataTuple row : rows_) { size_t j = 0; tuple_each(row, _GetValuesLambda{i, j, values}); i++; } std::vector<ColumnFiller> builders; tuple_each(rows_[0], _FillColumnLambda{values, builders, this->headers_}); std::vector<std::shared_ptr<Column>> columns; columns.resize(builders.size()); std::transform(std::begin(builders), std::end(builders), columns.begin(), [](ColumnFiller & builder) { return std::move(builder.Build()); }); return Table(name_, std::move(columns)); } private: const std::string name_; const size_t nrows_; const size_t ncols_; std::vector<std::string> headers_; std::vector<DataTuple> rows_; }; } // namespace library } // namespace gdf
29.815385
115
0.678225
[ "vector", "transform" ]
315b6380e83865d19aa591ce1ef5e5cf6004b033
1,136
h
C
TrackingTools/TrackAssociator/plugins/EcalDetIdAssociator.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
TrackingTools/TrackAssociator/plugins/EcalDetIdAssociator.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
TrackingTools/TrackAssociator/plugins/EcalDetIdAssociator.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#ifndef TrackAssociator_EcalDetIdAssociator_h #define TrackAssociator_EcalDetIdAssociator_h 1 // -*- C++ -*- // // Package: TrackAssociator // Class: EcalDetIdAssociator // /* Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Dmytro Kovalskyi // Created: Fri Apr 21 10:59:41 PDT 2006 // // #include "CaloDetIdAssociator.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" class EcalDetIdAssociator: public CaloDetIdAssociator{ public: EcalDetIdAssociator():CaloDetIdAssociator(360,300,0.02){}; EcalDetIdAssociator(const edm::ParameterSet& pSet):CaloDetIdAssociator(pSet){}; const char* name() const override { return "ECAL"; } protected: const unsigned int getNumberOfSubdetectors() const override { return 2;} void getValidDetIds(unsigned int subDetectorIndex, std::vector<DetId>& validIds) const override{ if ( subDetectorIndex == 0 ) validIds = geometry_->getValidDetIds(DetId::Ecal, EcalBarrel);//EB else validIds = geometry_->getValidDetIds(DetId::Ecal, EcalEndcap);//EE }; }; #endif
26.418605
100
0.720951
[ "vector" ]
3170a0ca59c0eb9fa5f945476213bdeaf4da1213
11,942
h
C
include/image.h
delldu/NImage
90a92fc395fdb83110eb600e46667c6c107d534c
[ "Apache-2.0" ]
1
2020-10-10T12:16:13.000Z
2020-10-10T12:16:13.000Z
include/image.h
delldu/NImage
90a92fc395fdb83110eb600e46667c6c107d534c
[ "Apache-2.0" ]
null
null
null
include/image.h
delldu/NImage
90a92fc395fdb83110eb600e46667c6c107d534c
[ "Apache-2.0" ]
null
null
null
/************************************************************************************ *** *** Copyright 2010-2020 Dell Du(18588220928@163.com), All Rights Reserved. *** *** File Author: Dell, Sat Jul 31 14:19:59 HKT 2010 *** ************************************************************************************/ #ifndef __IMAGE_H #define __IMAGE_H #if defined(__cplusplus) extern "C" { #endif #include "common.h" #include "matrix.h" #include "nnmsg.h" #include "tensor.h" #include "vector.h" #define IMAGE_VERSION "1.1.0" typedef struct { BYTE r, g, b, a; } RGBA_8888; #define RGB_R(x) ((BYTE)((x) >> 16) & 0xff) #define RGB_G(x) ((BYTE)((x) >> 8) & 0xff) #define RGB_B(x) ((BYTE)((x)&0xff)) #define RGB_INT(r, g, b) ((r) << 16 | (g) << 8 | (b)) typedef struct { float L, a, b; } LAB; typedef struct { float L, u, v; } Luv; typedef struct { DWORD magic; // IMAGE_MAGIC WORD height, width, format; RGBA_8888 **ie, *base; // Extentend for cluster & color mask int K, KColors[256], KCounts[256], KRadius, KInstance; } IMAGE; #define IMAGE_RGBA 0 #define IMAGE_GRAY 1 #define IMAGE_RGB565 2 #define IMAGE_MASK 3 #define image_foreach(img, i, j) \ for (i = 0; i < img->height; i++) \ for (j = 0; j < img->width; j++) #define check_image(img) \ do { \ if (!image_valid(img)) { \ syslog_error("Bad image."); \ return RET_ERROR; \ } \ } while (0) #define CHECK_IMAGE(img) \ do { \ if (!image_valid(img)) { \ syslog_error("Bad image."); \ return NULL; \ } \ } while (0) #define image_rect(rect, img) \ do { \ (rect)->r = 0; \ (rect)->c = 0; \ (rect)->h = img->height; \ (rect)->w = img->width; \ } while (0) #define check_rgb(orgb) \ do { \ if (!strchr("ARGB", orgb)) { \ syslog_error("Bad color %c (ARGB).", orgb); \ return RET_ERROR; \ } \ } while (0) #define check_argb(orgb) \ do { \ if (!strchr("ARGB", orgb)) { \ syslog_error("Bad color %c (ARGB).", orgb); \ return RET_ERROR; \ } \ } while (0) #define CHECK_RGB(orgb) \ do { \ if (!strchr("RGB", orgb)) { \ syslog_error("Bad color %c (RGB).", orgb); \ return NULL; \ } \ } while (0) #define CHECK_ARGB(orgb) \ do { \ if (!strchr("ARGB", orgb)) { \ syslog_error("Bad color %c (ARGB).\n", orgb); \ return NULL; \ } \ } while (0) #define CHECK_ARGBH(orgb) \ do { \ if (!strchr("ARGBH", orgb)) { \ syslog_error("Bad color %c (ARGBH).", orgb); \ return NULL; \ } \ } while (0) #define RGB565_R(x) ((((x) >> 11) & 0x1f) << 3) #define RGB565_G(x) ((((x) >> 5) & 0x3f) << 2) #define RGB565_B(x) (((x)&0x1f) << 3) #define RGB565_NO(r, g, b) (((r)&0xf8) << 8 | ((g)&0xfc) << 3 | ((b)&0xf8) >> 3) IMAGE *image_create(WORD h, WORD w); IMAGE *image_load(char *fname); IMAGE *image_copy(IMAGE *img); IMAGE *image_zoom(IMAGE *img, int nh, int nw, int method); IMAGE *image_hmerge(IMAGE *image1, IMAGE *image2); int image_valid(IMAGE *img); int image_clear(IMAGE *img); int image_outdoor(IMAGE *img, int i, int di, int j, int dj); int image_rectclamp(IMAGE *img, RECT *rect); int image_save(IMAGE *img, const char *fname); int image_show(IMAGE *image, char *title); BYTE image_getvalue(IMAGE *img, char oargb, int r, int c); void image_setvalue(IMAGE *img, char oargb, int r, int c, BYTE x); MATRIX *image_getplane(IMAGE *img, char oargb); MATRIX *image_rect_plane(IMAGE *img, char oargb, RECT *rect); int image_setplane(IMAGE *img, char oargb, MATRIX *mat); void color_rgb2gray(BYTE r, BYTE g, BYTE b, BYTE *gray); int skin_detect(IMAGE *img); int skin_statics(IMAGE *img, RECT *rect); int color_cluster(IMAGE *image, int num); int color_picker(); int color_balance(IMAGE *img, int method, int debug); int color_correct(IMAGE *img, float gain_r, float gain_g, float gain_b); int color_togray(IMAGE *img); int color_torgb565(IMAGE *img); void color_rgb2lab(BYTE R, BYTE G, BYTE B, float *L, float *a, float *b); void color_lab2rgb(float L, float a, float b, BYTE *R, BYTE *G, BYTE *B); float color_distance(RGBA_8888 *c1, RGBA_8888 *c2); void color_rgb2ycbcr(BYTE R, BYTE G, BYTE B, BYTE *y, BYTE *cb, BYTE *cr); void color_ycbcr2rgb(BYTE y, BYTE cb, BYTE cr, BYTE *R, BYTE *G, BYTE *B); int image_drawline(IMAGE *img, int r1, int c1, int r2, int c2, int color); int image_drawrect(IMAGE *img, RECT *rect, int color, int fill); int image_drawtext(IMAGE *image, int r, int c, char *texts, int color); int image_drawkxb(IMAGE *image, float k, float b, int color); int image_psnr(char oargb, IMAGE *orig, IMAGE *now, float *psnr); int image_paste(IMAGE *img, int r, int c, IMAGE *small, float alpha); int image_rect_paste(IMAGE *bigimg, RECT *bigrect, IMAGE *smallimg, RECT *smallrect); int image_statistics(IMAGE *img, char orgb, float *avg, float *stdv); int image_rect_statistics(IMAGE *img, RECT *rect, char orgb, float *avg, float *stdv); void image_destroy(IMAGE *img); // Image Color ... int color_midval(IMAGE *img, char orgb); VECTOR *color_vector(IMAGE *img, RECT *rect, int ndim); float color_likeness(IMAGE *f, IMAGE *g, RECT *rect, int ndim); // Image Shape ... VECTOR *shape_vector(IMAGE *img, RECT *rect, int ndim); float shape_likeness(IMAGE *f, IMAGE *g, RECT *rect, int ndim); // Image Texture ... VECTOR *texture_vector(IMAGE *img, RECT *rect, int ndim); float texture_likeness(IMAGE *f, IMAGE *g, RECT *rect, int ndim); // Contour & Skeleton int image_contour(IMAGE *img); int image_skeleton(IMAGE *img); // Middle value edge & Canny edge int shape_midedge(IMAGE *img); int shape_bestedge(IMAGE *img); // Hough Transform int line_detect(IMAGE *img, int debug); int line_lsm(IMAGE *image, RECT *rect, float *k, float *b, int debug); int motion_updatebg(IMAGE *A, IMAGE *B, IMAGE *C, IMAGE *bg); int motion_detect(IMAGE *fg, IMAGE *bg, int debug); int object_fast_detect(IMAGE *fg); // Matter center int image_mcenter(IMAGE *img, char orgb, int *crow, int *ccol); int image_rect_mcenter(IMAGE *img, RECT *rect, char orgb, int *crow, int *ccol); IMAGE *image_subimg(IMAGE *img, RECT *rect); void image_drawrects(IMAGE *img); MATRIX *image_gstatics(IMAGE *img, int rows, int cols); // Blending int image_blend(IMAGE *src, IMAGE *mask, IMAGE *dst, int top, int left, int debug); // Seaming int *image_seampath(IMAGE *image_a, RECT *rect_a, IMAGE *image_b, RECT *rect_b, int mode); IMAGE *image_seammask(IMAGE *image_a, RECT *rect_a, IMAGE *image_b, RECT *rect_b, int mode); // Retinex int image_retinex(IMAGE *image, int nscale); int image_negative(IMAGE *image); int image_clahe(IMAGE *image, int grid_rows, int grid_cols, float limit); int image_niblack(IMAGE *image, int radius, float scale); // Filter int image_make_noise(IMAGE *img, char orgb, int rate); int image_delete_noise(IMAGE *img); int image_gauss_filter(IMAGE *image, float sigma); int image_guided_filter(IMAGE *img, IMAGE *guidance, int radius, float eps, int scale, int debug); int image_beeps_filter(IMAGE *img, float stdv, float dec, int debug); int image_lee_filter(IMAGE *img, int radius, float eps, int debug); int image_dehaze_filter(IMAGE *img, int radius, int debug); int image_medium_filter(IMAGE *img, int radius); int image_fast_filter(IMAGE *img, int n, int *kernel, int total); int image_gauss3x3_filter(IMAGE *img, RECT *rect); int image_gauss5x5_filter(IMAGE *img, RECT *rect); int image_dot_filter(IMAGE *img, int i, int j); int image_rect_filter(IMAGE *img, RECT *rect, int n, int *kernel, int total); // Hash HASH64 image_ahash(IMAGE *image, char oargb, RECT *rect); HASH64 image_phash(IMAGE *image, char oargb, RECT *rect); HASH64 shape_hash(IMAGE *image, RECT *rect); HASH64 texture_hash(IMAGE *image, RECT *rect); int hash_hamming(HASH64 f1, HASH64 f2); float hash_likeness(HASH64 f1, HASH64 f2); void hash_dump(char *title, HASH64 finger); // Histogram #define HISTOGRAM_MAX_COUNT 256 typedef struct { int total; int count[HISTOGRAM_MAX_COUNT]; float cdf[HISTOGRAM_MAX_COUNT]; int map[HISTOGRAM_MAX_COUNT]; } HISTOGRAM; void histogram_reset(HISTOGRAM *h); void histogram_add(HISTOGRAM *h, int c); void histogram_del(HISTOGRAM *h, int c); int histogram_middle(HISTOGRAM *h); int histogram_top(HISTOGRAM *h, float ratio); int histogram_clip(HISTOGRAM *h, int threshold); int histogram_cdf(HISTOGRAM *h); int histogram_map(HISTOGRAM *h, int max); float histogram_likeness(HISTOGRAM *h1, HISTOGRAM *h2); void histogram_sum(HISTOGRAM *sum, HISTOGRAM *sub); int histogram_rect(HISTOGRAM *hist, IMAGE *img, RECT *rect); void histogram_dump(HISTOGRAM *h); float image_entropy(IMAGE *img); // Return [0.0, 1.0] // Mask is all you need #define MASK IMAGE int color_instance(MASK *image, int KRadius); int mask_show(); // Tensor IMAGE *image_from_tensor(TENSOR *tensor, int k); TENSOR *tensor_from_image(IMAGE *image, int with_alpha); TENSOR *tensor_rgb2lab(IMAGE *image); IMAGE *tensor_lab2rgb(TENSOR *tensor, int k); int tensor_setmask(TENSOR *tensor, float mask); #if defined(__cplusplus) } #endif #endif // __IMAGE_H
39.282895
85
0.50829
[ "shape", "vector", "transform" ]
317237b99cb67ec01fe2a3d5e181554555e7a4a0
9,630
h
C
src/yb/rpc/connection.h
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
1
2021-06-11T10:23:00.000Z
2021-06-11T10:23:00.000Z
src/yb/rpc/connection.h
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
189
2021-02-19T01:23:31.000Z
2021-04-02T01:03:14.000Z
src/yb/rpc/connection.h
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
1
2020-12-30T00:43:38.000Z
2020-12-30T00:43:38.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #ifndef YB_RPC_CONNECTION_H_ #define YB_RPC_CONNECTION_H_ #include <atomic> #include <cstdint> #include <limits> #include <memory> #include <queue> #include <string> #include <unordered_map> #include <vector> #include <boost/container/small_vector.hpp> #include <ev++.h> #include "yb/gutil/gscoped_ptr.h" #include "yb/gutil/ref_counted.h" #include "yb/rpc/rpc_fwd.h" #include "yb/rpc/connection_context.h" #include "yb/rpc/server_event.h" #include "yb/rpc/stream.h" #include "yb/util/enums.h" #include "yb/util/ev_util.h" #include "yb/util/metrics.h" #include "yb/util/monotime.h" #include "yb/util/net/net_util.h" #include "yb/util/net/sockaddr.h" #include "yb/util/net/socket.h" #include "yb/util/object_pool.h" #include "yb/util/ref_cnt_buffer.h" #include "yb/util/status.h" #include "yb/util/strongly_typed_bool.h" namespace yb { namespace rpc { YB_DEFINE_ENUM(ConnectionDirection, (CLIENT)(SERVER)); typedef boost::container::small_vector_base<OutboundDataPtr> OutboundDataBatch; // // A connection between an endpoint and us. // // Inbound connections are created by AcceptorPools, which eventually schedule // RegisterConnection() to be called from the reactor thread. // // Outbound connections are created by the Reactor thread in order to service // outbound calls. // // Once a Connection is created, it can be used both for sending messages and // receiving them, but any given connection is explicitly a client or server. // If a pair of servers are making bidirectional RPCs, they will use two separate // TCP connections (and Connection objects). // // This class is not fully thread-safe. It is accessed only from the context of a // single Reactor except where otherwise specified. // class Connection final : public StreamContext, public std::enable_shared_from_this<Connection> { public: typedef ConnectionDirection Direction; // Create a new Connection. // reactor: the reactor that owns us. // remote: the address of the remote end // socket: the socket to take ownership of. // direction: whether we are the client or server side // context: context for this connection. Context is used by connection to handle // protocol specific actions, such as parsing of incoming data into calls. Connection(Reactor* reactor, std::unique_ptr<Stream> stream, Direction direction, RpcMetrics* rpc_metrics, std::unique_ptr<ConnectionContext> context); ~Connection(); CoarseTimePoint last_activity_time() const { return last_activity_time_; } void UpdateLastActivity() override; // Returns true if we are not in the process of receiving or sending a // message, and we have no outstanding calls. // When reason_not_idle is specified it contains reason why this connection is not idle. bool Idle(std::string* reason_not_idle = nullptr) const; // A human-readable reason why the connection is not idle. Empty string if connection is idle. std::string ReasonNotIdle() const; // Fail any calls which are currently queued or awaiting response. // Prohibits any future calls (they will be failed immediately with this // same Status). void Shutdown(const Status& status); // Queue a new call to be made. If the queueing fails, the call will be // marked failed. // Takes ownership of the 'call' object regardless of whether it succeeds or fails. // This may be called from a non-reactor thread. void QueueOutboundCall(const OutboundCallPtr& call); // The address of the remote end of the connection. const Endpoint& remote() const; const Protocol* protocol() const; // The address of the local end of the connection. const Endpoint& local() const; void HandleTimeout(ev::timer& watcher, int revents); // NOLINT // Safe to be called from other threads. std::string ToString() const; Direction direction() const { return direction_; } // Queue a call response back to the client on the server side. // // This is usually called by the IPC worker thread when the response is set, but in some // circumstances may also be called by the reactor thread (e.g. if the service has shut down). // In addition to this, its also called for processing events generated by the server. void QueueOutboundData(OutboundDataPtr outbound_data); void QueueOutboundDataBatch(const OutboundDataBatch& batch); Reactor* reactor() const { return reactor_; } CHECKED_STATUS DumpPB(const DumpRunningRpcsRequestPB& req, RpcConnectionPB* resp); // Do appropriate actions after adding outbound call. void OutboundQueued(); // An incoming packet has completed on the client side. This parses the // call response, looks up the CallAwaitingResponse, and calls the // client callback. CHECKED_STATUS HandleCallResponse(CallData* call_data); ConnectionContext& context() { return *context_; } void CallSent(OutboundCallPtr call); CHECKED_STATUS Start(ev::loop_ref* loop); // Try to parse already received data. void ParseReceived(); void Close(); RpcMetrics& rpc_metrics() { return *rpc_metrics_; } private: CHECKED_STATUS DoWrite(); // Does actual outbound data queueing. Invoked in appropriate reactor thread. size_t DoQueueOutboundData(OutboundDataPtr call, bool batch); void ProcessResponseQueue(); // Stream context implementation void UpdateLastRead() override; void UpdateLastWrite() override; void Transferred(const OutboundDataPtr& data, const Status& status) override; void Destroy(const Status& status) override; Result<ProcessDataResult> ProcessReceived( const IoVecs& data, ReadBufferFull read_buffer_full) override; void Connected() override; StreamReadBuffer& ReadBuffer() override; std::string LogPrefix() const; // The reactor thread that created this connection. Reactor* const reactor_; std::unique_ptr<Stream> stream_; // whether we are client or server Direction direction_; // The last time we read or wrote from the socket. CoarseTimePoint last_activity_time_; // Calls which have been sent and are now waiting for a response. std::unordered_map<int32_t, OutboundCallPtr> awaiting_response_; // Starts as Status::OK, gets set to a shutdown status upon Shutdown(). Guarded by // outbound_data_queue_lock_. Status shutdown_status_; // We instantiate and store this metric instance at the level of connection, but not at the level // of the class emitting metrics (OutboundTransfer) as recommended in metrics.h. This is on // purpose, because OutboundTransfer is instantiated each time we need to send payload over a // connection and creating a metric instance each time could be a performance hit, because // it involves spin lock and search in a metrics map. Therefore we prepare metric instances // at connection level. scoped_refptr<Histogram> handler_latency_outbound_transfer_; struct ExpirationEntry { CoarseTimePoint time; std::weak_ptr<OutboundCall> call; // See Stream::Send for details. size_t handle; }; struct CompareExpiration { bool operator()(const ExpirationEntry& lhs, const ExpirationEntry& rhs) const { return rhs.time < lhs.time; } }; std::priority_queue<ExpirationEntry, std::vector<ExpirationEntry>, CompareExpiration> expiration_queue_; EvTimerHolder timer_; simple_spinlock outbound_data_queue_lock_; // Responses we are going to process. std::vector<OutboundDataPtr> outbound_data_to_process_; // Responses that are currently being processed. // It could be in function variable, but declared as member for optimization. std::vector<OutboundDataPtr> outbound_data_being_processed_; std::shared_ptr<ReactorTask> process_response_queue_task_; // RPC related metrics. RpcMetrics* rpc_metrics_; // Connection is responsible for sending and receiving bytes. // Context is responsible for what to do with them. std::unique_ptr<ConnectionContext> context_; std::atomic<uint64_t> responded_call_count_{0}; }; } // namespace rpc } // namespace yb #endif // YB_RPC_CONNECTION_H_
34.392857
100
0.744029
[ "object", "vector" ]
317328ed8823f9f9e3593c0d8bbe292422481892
3,465
h
C
aslam_optimizer/sparse_block_matrix/include/sparse_block_matrix/marginal_covariance_cholesky.h
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
2,690
2015-01-07T03:50:23.000Z
2022-03-31T20:27:01.000Z
aslam_optimizer/sparse_block_matrix/include/sparse_block_matrix/marginal_covariance_cholesky.h
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
481
2015-01-27T10:21:00.000Z
2022-03-31T14:02:41.000Z
aslam_optimizer/sparse_block_matrix/include/sparse_block_matrix/marginal_covariance_cholesky.h
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
1,091
2015-01-26T21:21:13.000Z
2022-03-30T01:55:33.000Z
// g2o - General Graph Optimization // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard // // g2o 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 3 of the License, or // (at your option) any later version. // // g2o is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef SBM_MARGINAL_COVARIANCE_CHOLESKY_H #define SBM_MARGINAL_COVARIANCE_CHOLESKY_H //#include "optimizable_graph.h" #include "sparse_block_matrix.h" #include <cassert> #include <vector> #include <unordered_map> namespace sparse_block_matrix { /** * \brief computing the marginal covariance given a cholesky factor (lower triangle of the factor) */ class MarginalCovarianceCholesky { protected: /** * hash struct for storing the matrix elements needed to compute the covariance */ typedef std::unordered_map<int, double> LookupMap; public: MarginalCovarianceCholesky(); ~MarginalCovarianceCholesky(); /** * compute the covariance for the given vertices, directly store inside the uncertainty field of the vertex */ //void computeCovariance(const std::vector<OptimizableGraph::Vertex*>& vertices); /** * compute the marginal cov for the given block indices, write the result to the covBlocks memory (which has to * be provided by the caller). */ void computeCovariance(double** covBlocks, const std::vector<int>& blockIndices); /** * compute the marginal cov for the given block indices, write the result in spinv). */ void computeCovariance(SparseBlockMatrix<MatrixXd>& spinv, const std::vector<int>& rowBlockIndices, const std::vector< std::pair<int, int> >& blockIndices); /** * set the CCS representation of the cholesky factor along with the inverse permutation used to reduce the fill-in. * permInv might be 0, will then not permute the entries. */ void setCholeskyFactor(int n, int* Lp, int* Li, double* Lx, int* permInv); protected: // information about the cholesky factor (lower triangle) int _n; ///< L is an n X n matrix int* _Ap; ///< column pointer of the CCS storage int* _Ai; ///< row indices of the CCS storage double* _Ax; ///< values of the cholesky factor int* _perm; ///< permutation of the cholesky factor. Variable re-ordering for better fill-in LookupMap _map; ///< hash look up table for the already computed entries std::vector<double> _diag; ///< cache 1 / H_ii to avoid recalculations //! compute the index used for hashing int computeIndex(int r, int c) const { /*assert(r <= c);*/ return r*_n + c;} /** * compute one entry in the covariance, r and c are values after applying the permutation, and upper triangular. * May issue recursive calls to itself to compute the missing values. */ double computeEntry(int r, int c); }; } #endif
38.076923
162
0.678211
[ "vector" ]
3175a77c2f8e7f50e862ee285a1961b927168be3
9,535
c
C
src/dev/cpu/op/fc/fc_hcl_arm.c
ncnnnnn/Tengine
0a5a9637b0781686e9123690ee12b1c1f34bd05c
[ "Apache-2.0" ]
null
null
null
src/dev/cpu/op/fc/fc_hcl_arm.c
ncnnnnn/Tengine
0a5a9637b0781686e9123690ee12b1c1f34bd05c
[ "Apache-2.0" ]
null
null
null
src/dev/cpu/op/fc/fc_hcl_arm.c
ncnnnnn/Tengine
0a5a9637b0781686e9123690ee12b1c1f34bd05c
[ "Apache-2.0" ]
null
null
null
/* * 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. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: haoluo@openailab.com * update: qtang@openailab.com */ #include "sys_port.h" #include "module.h" #include "tengine_errno.h" #include "tengine_log.h" #include "tengine_ir.h" #include "../../cpu_node_ops.h" #include "tengine_op.h" #include "fc_param.h" #include "cortex_a/fc_kernel_arm.h" #include "cortex_a/fc_kernel_int8_arm.h" #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #include "cortex_a/fc_kernel_fp16_arm82.h" #endif static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); struct ir_tensor* filter_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[1]); struct ir_tensor* output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct fc_priv_info* priv_info = ( struct fc_priv_info* )exec_node->ops_priv; struct fc_param* fc_param = ( struct fc_param* )ir_node->op.param_mem; /* fp32 prerun */ if (exec_graph->mode == TENGINE_MODE_FP32) { if (fc_kernel_prerun(input_tensor, filter_tensor, output_tensor, priv_info, fc_param) < 0) { TLOG_ERR("hcl fc prerun failed\n"); set_tengine_errno(EFAULT); return -1; } } else if(exec_graph->mode == TENGINE_MODE_INT8){ if (int8_fc_kernel_prerun(input_tensor, filter_tensor, output_tensor, priv_info, fc_param) < 0) { TLOG_ERR("hcl fc prerun failed\n"); set_tengine_errno(EFAULT); return -1; } } /* fp16 prerun */ #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC else if (exec_graph->mode == TENGINE_MODE_FP16) { if(fp16_fc_kernel_prerun(input_tensor, filter_tensor, output_tensor, priv_info, fc_param) < 0) { TLOG_ERR("hcl fp16 fc prerun failed\n"); set_tengine_errno(EFAULT); return -1; } } #endif else { printf("Tengine work node not support %d\n", exec_graph->mode); return -1; } return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor; struct ir_tensor* weight_tensor; struct ir_tensor* bias_tensor = NULL; struct ir_tensor* output_tensor = NULL; int num_thread = exec_graph->num_thread; int cpu_affinity = exec_graph->cpu_affinity; /* set the input data and shape again, in case of reshape or dynamic shape */ input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); weight_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[1]); if (ir_node->input_num > 2) bias_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[2]); output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct fc_param* fc_param = ( struct fc_param* )ir_node->op.param_mem; struct fc_priv_info* priv_info = ( struct fc_priv_info* )exec_node->ops_priv; /* fp32 run */ if (exec_graph->mode == TENGINE_MODE_FP32) { if (fc_kernel_run(input_tensor, weight_tensor, bias_tensor, output_tensor, priv_info, fc_param, num_thread, cpu_affinity) < 0) { TLOG_ERR("hcl fc run failed\n"); set_tengine_errno(EFAULT); return -1; } } else if (exec_graph->mode == TENGINE_MODE_INT8) { if (int8_fc_kernel_run(input_tensor, weight_tensor, bias_tensor, output_tensor, priv_info,fc_param,num_thread,cpu_affinity) < 0) { TLOG_ERR("hcl fc run failed\n"); set_tengine_errno(EFAULT); return -1; } } /* fp16 run */ #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC else if (exec_graph->mode == TENGINE_MODE_FP16) { if (fp16_fc_kernel_run(input_tensor, weight_tensor, bias_tensor, output_tensor, priv_info, fc_param, num_thread, cpu_affinity) < 0) { TLOG_ERR("hcl fp16 fc run failed\n"); set_tengine_errno(EFAULT); return -1; } } #endif else { printf("Tengine work node not support %d\n", exec_graph->mode); return -1; } return 0; } static int reshape(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* node = exec_node->ir_node; struct ir_graph* graph = node->graph; struct ir_tensor* input = get_ir_graph_tensor(graph, node->input_tensors[0]); struct ir_tensor* weight = get_ir_graph_tensor(graph, node->input_tensors[1]); struct ir_tensor* output = get_ir_graph_tensor(graph, node->output_tensors[0]); int dim[4]; int n = weight->dims[0]; int k = weight->dims[1]; int m = input->dims[0]; int input_k = input->dims[1]; if (input->dim_num == 2) { dim[0] = m; dim[1] = n; } else if (input->dim_num == 3) { input_k *= input->dims[2]; if (graph->graph_layout == TENGINE_LAYOUT_NHWC) { dim[0] = m; dim[1] = 1; dim[2] = n; } else { dim[0] = m; dim[1] = n; dim[2] = 1; } } else if (input->dim_num == 4) { if (input->dims[2] * input->dims[3] != 0) input_k *= input->dims[2] * input->dims[3]; if (graph->graph_layout == TENGINE_LAYOUT_NHWC) { dim[0] = m; dim[1] = 1; dim[2] = 1; dim[3] = n; } else { dim[0] = m; dim[1] = n; dim[2] = 1; dim[3] = 1; } } else return -1; if (k != input_k) { TLOG_ERR("fc: input tensor and weight tensor shape does not match, hidden_number: %d\n", k); set_tengine_errno(EFAULT); return -1; } int ret = set_ir_tensor_shape(output, dim, input->dim_num); return ret; } static int postrun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct fc_priv_info* priv_info = ( struct fc_priv_info* )exec_node->ops_priv; if (fc_kernel_postrun(priv_info) < 0) { TLOG_ERR("hcl fc prerun failed\n"); set_tengine_errno(EFAULT); return -1; } return 0; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { /* init the private info data of convolution op */ struct fc_priv_info* priv_info = ( struct fc_priv_info* )sys_malloc(sizeof(struct fc_priv_info)); if (priv_info == NULL) { set_tengine_errno(ENOMEM); return -1; } memset(priv_info, 0, sizeof(struct fc_priv_info)); exec_node->ops_priv = priv_info; return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct fc_priv_info* priv_info = ( struct fc_priv_info* )exec_node->ops_priv; sys_free(priv_info); exec_node->ops_priv = NULL; return 0; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct ir_node* exec_node) { struct ir_node* ir_node = exec_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); /* todo support uint8 */ #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC if (input_tensor->data_type != TENGINE_DT_FP32 && input_tensor->data_type != TENGINE_DT_FP16) return 0; #else if (input_tensor->data_type == TENGINE_DT_INT8){ return OPS_SCORE_BEST; } if (input_tensor->data_type != TENGINE_DT_FP32) return 0; #endif return OPS_SCORE_BEST; } static struct node_ops hcl_node_ops = {.prerun = prerun, .run = run, .reshape = reshape, .postrun = postrun, .init_node = init_node, .release_node = release_node, .score = score}; static int reg_fc_hcl_ops(void* arg) { return register_builtin_node_ops(OP_FC, &hcl_node_ops); } static int unreg_fc_hcl_ops(void* arg) { unregister_builtin_node_ops(OP_FC, &hcl_node_ops); return 0; } AUTO_REGISTER_OPS(reg_fc_hcl_ops); AUTO_UNREGISTER_OPS(unreg_fc_hcl_ops);
31.783333
139
0.636602
[ "shape" ]
317af89467489fcad6dc139e840016865f336399
10,841
c
C
k10/mp.c
0intro/9k
0925f1d8163cb2a3eecbc179b0a884000f084921
[ "MIT" ]
12
2020-11-12T09:44:44.000Z
2021-10-19T00:44:56.000Z
k10/mp.c
0intro/9k
0925f1d8163cb2a3eecbc179b0a884000f084921
[ "MIT" ]
null
null
null
k10/mp.c
0intro/9k
0925f1d8163cb2a3eecbc179b0a884000f084921
[ "MIT" ]
null
null
null
#include "u.h" #include "../port/lib.h" #include "mem.h" #include "dat.h" #include "fns.h" #include "apic.h" /* * MultiProcessor Specification Version 1.[14]. */ typedef struct { /* MP Floating Pointer */ u8int signature[4]; /* "_MP_" */ u8int addr[4]; /* PCMP */ u8int length; /* 1 */ u8int revision; /* [14] */ u8int checksum; u8int feature[5]; } _MP_; typedef struct { /* MP Configuration Table */ u8int signature[4]; /* "PCMP" */ u8int length[2]; u8int revision; /* [14] */ u8int checksum; u8int string[20]; /* OEM + Product ID */ u8int oaddr[4]; /* OEM table pointer */ u8int olength[2]; /* OEM table length */ u8int entry[2]; /* entry count */ u8int apicpa[4]; /* local APIC address */ u8int xlength[2]; /* extended table length */ u8int xchecksum; /* extended table checksum */ u8int reserved; u8int entries[]; } PCMP; typedef struct { char type[6]; int polarity; /* default for this bus */ int trigger; /* default for this bus */ } Mpbus; static Mpbus mpbusdef[] = { { "PCI ", IPlow, TMlevel, }, { "ISA ", IPhigh, TMedge, }, }; static Mpbus* mpbus[Nbus]; int mpisabusno = -1; static void mpintrprint(char* s, u8int* p) { char buf[128], *b, *e; char format[] = " type %d flags %#ux bus %d IRQ %d APIC %d INTIN %d\n"; b = buf; e = b + sizeof(buf); b = seprint(b, e, "mpparse: intr:"); if(s != nil) b = seprint(b, e, " %s:", s); seprint(b, e, format, p[1], l16get(p+2), p[4], p[5], p[6], p[7]); print(buf); } static u32int mpmkintr(u8int* p) { u32int v; Apic *apic; int n, polarity, trigger; /* * Check valid bus, interrupt input pin polarity * and trigger mode. If the APIC ID is 0xff it means * all APICs of this type so those checks for useable * APIC and valid INTIN must also be done later in * the appropriate init routine in that case. It's hard * to imagine routing a signal to all IOAPICs, the * usual case is routing NMI and ExtINT to all LAPICs. */ if(mpbus[p[4]] == nil){ mpintrprint("no source bus", p); return 0; } if(p[6] != 0xff){ if(Napic < 256 && p[6] >= Napic){ mpintrprint("APIC ID out of range", p); return 0; } switch(p[0]){ default: mpintrprint("INTIN botch", p); return 0; case 3: /* IOINTR */ apic = &ioapic[p[6]]; if(!apic->useable){ mpintrprint("unuseable APIC", p); return 0; } if(p[7] >= apic->nrdt){ mpintrprint("IO INTIN out of range", p); return 0; } break; case 4: /* LINTR */ apic = &xapic[p[6]]; if(!apic->useable){ mpintrprint("unuseable APIC", p); return 0; } if(p[7] >= nelem(apic->lvt)){ mpintrprint("LOCAL INTIN out of range", p); return 0; } break; } } n = l16get(p+2); if((polarity = (n & 0x03)) == 2 || (trigger = ((n>>2) & 0x03)) == 2){ mpintrprint("invalid polarity/trigger", p); return 0; } /* * Create the low half of the vector table entry (LVT or RDT). * For the NMI, SMI and ExtINT cases, the polarity and trigger * are fixed (but are not always consistent over IA-32 generations). * For the INT case, either the polarity/trigger are given or * it defaults to that of the source bus; * whether INT is Fixed or Lowest Priority is left until later. */ v = Im; switch(p[1]){ default: mpintrprint("invalid type", p); return 0; case 0: /* INT */ switch(polarity){ case 0: v |= mpbus[p[4]]->polarity; break; case 1: v |= IPhigh; break; case 3: v |= IPlow; break; } switch(trigger){ case 0: v |= mpbus[p[4]]->trigger; break; case 1: v |= TMedge; break; case 3: v |= TMlevel; break; } break; case 1: /* NMI */ v |= TMedge|IPhigh|MTnmi; break; case 2: /* SMI */ v |= TMedge|IPhigh|MTsmi; break; case 3: /* ExtINT */ v |= TMedge|IPhigh|MTei; break; } return v; } static void mpparse(PCMP* pcmp) { u32int lo; u8int *e, *p; int devno, i, n; p = pcmp->entries; e = ((uchar*)pcmp)+l16get(pcmp->length); while(p < e) switch(*p){ default: print("mpparse: unknown PCMP type %d (e-p %#ld)\n", *p, e-p); for(i = 0; p < e; i++){ if(i && ((i & 0x0f) == 0)) print("\n"); print(" %#2.2ux", *p); p++; } print("\n"); break; case 0: /* processor */ /* * Initialise the APIC if it is enabled (p[3] & 0x01). * p[1] is the APIC ID, the memory mapped address comes * from the PCMP structure as the addess is local to the * CPU and identical for all. Indicate whether this is * the bootstrap processor (p[3] & 0x02). */ DBG("mpparse: APIC %d pa %#ux useable %d\n", p[1], l32get(pcmp->apicpa), p[3] & 0x01); if(p[3] & 0x01) apicinit(p[1], l32get(pcmp->apicpa), p[3] & 0x02); p += 20; break; case 1: /* bus */ DBG("mpparse: bus: %d type %6.6s\n", p[1], (char*)p+2); if(mpbus[p[1]] != nil){ print("mpparse: bus %d already allocated\n", p[1]); p += 8; break; } for(i = 0; i < nelem(mpbusdef); i++){ if(memcmp(p+2, mpbusdef[i].type, 6) != 0) continue; if(memcmp(p+2, "ISA ", 6) == 0){ if(mpisabusno != -1){ print("mpparse: bus %d already have ISA bus %d\n", p[1], mpisabusno); continue; } mpisabusno = p[1]; } mpbus[p[1]] = &mpbusdef[i]; break; } if(mpbus[p[1]] == nil) print("mpparse: bus %d type %6.6s unknown\n", p[1], (char*)p+2); p += 8; break; case 2: /* IOAPIC */ /* * Initialise the IOAPIC if it is enabled (p[3] & 0x01). * p[1] is the APIC ID, p[4-7] is the memory mapped address. */ DBG("mpparse: IOAPIC %d pa %#ux useable %d\n", p[1], l32get(p+4), p[3] & 0x01); if(p[3] & 0x01) ioapicinit(p[1], l32get(p+4)); p += 8; break; case 3: /* IOINTR */ /* * p[1] is the interrupt type; * p[2-3] contains the polarity and trigger mode; * p[4] is the source bus; * p[5] is the IRQ on the source bus; * p[6] is the destination APIC; * p[7] is the INITIN pin on the destination APIC. */ if(p[6] == 0xff){ mpintrprint("routed to all IOAPICs", p); p += 8; break; } if((lo = mpmkintr(p)) == 0){ p += 8; break; } if(DBGFLG) mpintrprint(nil, p); /* * Always present the device number in the style * of a PCI Interrupt Assignment Entry. For the ISA * bus the IRQ is the device number but unencoded. * May need to handle other buses here in the future * (but unlikely). */ devno = p[5]; if(memcmp(mpbus[p[4]]->type, "PCI ", 6) != 0) devno <<= 2; ioapicintrinit(p[4], p[6], p[7], devno, lo); p += 8; break; case 4: /* LINTR */ /* * Format is the same as IOINTR above. */ if((lo = mpmkintr(p)) == 0){ p += 8; break; } if(DBGFLG) mpintrprint(nil, p); /* * Everything was checked in mpmkintr above. */ if(p[6] == 0xff){ for(i = 0; i < Napic; i++){ if(!ioapic[i].useable || ioapic[i].addr != nil) continue; ioapic[i].lvt[p[7]] = lo; } } else ioapic[p[6]].lvt[p[7]] = lo; p += 8; break; } /* * There's nothing of real interest in the extended table, * should just move along, but check it for consistency. */ p = e; e = p + l16get(pcmp->xlength); while(p < e) switch(*p){ default: n = p[1]; print("mpparse: unknown extended entry %d length %d\n", *p, n); for(i = 0; i < n; i++){ if(i && ((i & 0x0f) == 0)) print("\n"); print(" %#2.2ux", *p); p++; } print("\n"); break; case 128: DBG("address space mapping\n"); DBG(" bus %d type %d base %#llux length %#llux\n", p[2], p[3], l64get(p+4), l64get(p+12)); p += p[1]; break; case 129: DBG("bus hierarchy descriptor\n"); DBG(" bus %d sd %d parent bus %d\n", p[2], p[3], p[4]); p += p[1]; break; case 130: DBG("compatibility bus address space modifier\n"); DBG(" bus %d pr %d range list %d\n", p[2], p[3], l32get(p+4)); p += p[1]; break; } } static int sigchecksum(void* address, int length) { u8int *p, sum; sum = 0; for(p = address; length-- > 0; p++) sum += *p; return sum; } static void* sigscan(u8int* address, int length, char* signature) { u8int *e, *p; int siglength; DBG("check for %s in system base memory @ %#p\n", signature, address); e = address+length; siglength = strlen(signature); for(p = address; p+siglength < e; p += 16){ if(memcmp(p, signature, siglength)) continue; return p; } return nil; } static void* sigsearch(char* signature) { uintptr p; u8int *bda; void *r; /* * Search for the data structure: * 1) within the first KiB of the Extended BIOS Data Area (EBDA), or * 2) within the last KiB of system base memory if the EBDA segment * is undefined, or * 3) within the BIOS ROM address space between 0xf0000 and 0xfffff * (but will actually check 0xe0000 to 0xfffff). */ bda = BIOSSEG(0x40); if(memcmp(KADDR(0xfffd9), "EISA", 4) == 0){ if((p = (bda[0x0f]<<8)|bda[0x0e]) != 0){ if((r = sigscan(BIOSSEG(p), 1024, signature)) != nil) return r; } } if((p = ((bda[0x14]<<8)|bda[0x13])*1024) != 0){ if((r = sigscan(KADDR(p-1024), 1024, signature)) != nil) return r; } if((r = sigscan(KADDR(0xa0000-1024), 1024, signature)) != nil) return r; return sigscan(BIOSSEG(0xe000), 0x20000, signature); } void mpsinit(void) { u8int *p; int i, n; _MP_ *mp; PCMP *pcmp; if((mp = sigsearch("_MP_")) == nil) return; if(DBGFLG){ DBG("_MP_ @ %#p, addr %#ux length %ud rev %d", mp, l32get(mp->addr), mp->length, mp->revision); for(i = 0; i < sizeof(mp->feature); i++) DBG(" %2.2#ux", mp->feature[i]); DBG("\n"); } if(mp->revision != 1 && mp->revision != 4) return; if(sigchecksum(mp, mp->length*16) != 0) return; if((pcmp = vmap(l32get(mp->addr), sizeof(PCMP))) == nil) return; if(pcmp->revision != 1 && pcmp->revision != 4){ vunmap(pcmp, sizeof(PCMP)); return; } n = l16get(pcmp->length) + l16get(pcmp->xlength); vunmap(pcmp, sizeof(PCMP)); if((pcmp = vmap(l32get(mp->addr), n)) == nil) return; if(sigchecksum(pcmp, l16get(pcmp->length)) != 0){ vunmap(pcmp, n); return; } if(DBGFLG){ DBG("PCMP @ %#p length %#ux revision %d\n", pcmp, l16get(pcmp->length), pcmp->revision); DBG(" %20.20s oaddr %#ux olength %#ux\n", (char*)pcmp->string, l32get(pcmp->oaddr), l16get(pcmp->olength)); DBG(" entry %d apicpa %#ux\n", l16get(pcmp->entry), l32get(pcmp->apicpa)); DBG(" xlength %#ux xchecksum %#ux\n", l16get(pcmp->xlength), pcmp->xchecksum); } if(pcmp->xchecksum != 0){ p = ((u8int*)pcmp) + l16get(pcmp->length); i = sigchecksum(p, l16get(pcmp->xlength)); if(((i+pcmp->xchecksum) & 0xff) != 0){ print("extended table checksums to %#ux\n", i); vunmap(pcmp, n); return; } } /* * Parse the PCMP table and set up the datastructures * for later interrupt enabling and application processor * startup. */ mpparse(pcmp); apicdump(); ioapicdump(); }
22.491701
72
0.57753
[ "vector" ]
317d7d6e79a4902d0fb1d01a049df94b21af91b7
1,285
h
C
src/CryptoNoteCore/ITransactionPool.h
bitcoinectcoin/criptonitacoin
48631dea833d333ebc3449e47eeefabfa002bdad
[ "MIT" ]
null
null
null
src/CryptoNoteCore/ITransactionPool.h
bitcoinectcoin/criptonitacoin
48631dea833d333ebc3449e47eeefabfa002bdad
[ "MIT" ]
null
null
null
src/CryptoNoteCore/ITransactionPool.h
bitcoinectcoin/criptonitacoin
48631dea833d333ebc3449e47eeefabfa002bdad
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018, The bitcoin2network developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of bitcoin2network. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #pragma once #include "CachedTransaction.h" namespace CryptoNote { struct TransactionValidatorState; class ITransactionPool { public: virtual bool pushTransaction(CachedTransaction&& tx, TransactionValidatorState&& transactionState) = 0; virtual const CachedTransaction& getTransaction(const Crypto::Hash& hash) const = 0; virtual bool removeTransaction(const Crypto::Hash& hash) = 0; virtual size_t getTransactionCount() const = 0; virtual std::vector<Crypto::Hash> getTransactionHashes() const = 0; virtual bool checkIfTransactionPresent(const Crypto::Hash& hash) const = 0; virtual const TransactionValidatorState& getPoolTransactionValidationState() const = 0; virtual std::vector<CachedTransaction> getPoolTransactions() const = 0; virtual uint64_t getTransactionReceiveTime(const Crypto::Hash& hash) const = 0; virtual std::vector<Crypto::Hash> getTransactionHashesByPaymentId(const Crypto::Hash& paymentId) const = 0; }; }
35.694444
109
0.771984
[ "vector" ]
31822d0489ed5538cb0774b7911b794425157c4b
25,307
c
C
Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/unitim.c
gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5
11d81127dd296595bca30cb1565ff3b813210230
[ "MIT" ]
6
2022-01-21T19:58:08.000Z
2022-03-28T12:32:24.000Z
Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/unitim.c
gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5
11d81127dd296595bca30cb1565ff3b813210230
[ "MIT" ]
null
null
null
Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/unitim.c
gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5
11d81127dd296595bca30cb1565ff3b813210230
[ "MIT" ]
4
2022-02-12T10:01:40.000Z
2022-03-28T14:28:52.000Z
/* unitim.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Table of constant values */ static integer c__5 = 5; static integer c__4 = 4; static integer c__9 = 9; static integer c__1 = 1; static integer c__2 = 2; static integer c__7 = 7; /* $Procedure UNITIM ( Uniform time scale transformation ) */ doublereal unitim_(doublereal *epoch, char *insys, char *outsys, ftnlen insys_len, ftnlen outsys_len) { /* Initialized data */ static logical first = TRUE_; static char missed[20*4] = "DELTET/DELTA_T_A, # " "DELTET/K, # " "DELTET/EB, # " "DELTET/M, # "; static logical nodata = TRUE_; static char vars__[16*4] = "DELTET/DELTA_T_A" "DELTET/K " "DELTET" "/EB " "DELTET/M "; /* System generated locals */ address a__1[7]; integer i__1[7], i__2; doublereal ret_val; char ch__1[466]; /* Builtin functions */ /* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen), s_cat(char *, char **, integer *, integer *, ftnlen); integer s_rnge(char *, integer, char *, integer), s_cmp(char *, char *, ftnlen, ftnlen); double sin(doublereal); /* Local variables */ extern logical setc_(char *, char *, char *, ftnlen, ftnlen, ftnlen); char myin[8]; extern /* Subroutine */ int zzcvpool_(char *, integer *, logical *, ftnlen), zzctruin_(integer *); integer i__; static doublereal k, m[2]; integer n; extern logical elemc_(char *, char *, ftnlen, ftnlen); extern /* Subroutine */ int chkin_(char *, ftnlen); static char recog[8*15]; logical intdb; extern /* Subroutine */ int ucase_(char *, char *, ftnlen, ftnlen), errch_(char *, char *, ftnlen, ftnlen); logical found[4], intdt; char types[8*8], myout[8]; static doublereal eb; extern logical failed_(void); extern /* Subroutine */ int validc_(integer *, integer *, char *, ftnlen); static char bslash[1]; static doublereal secspd; logical update; extern /* Subroutine */ int gdpool_(char *, integer *, integer *, integer *, doublereal *, logical *, ftnlen), unionc_(char *, char *, char *, ftnlen, ftnlen, ftnlen), sigerr_(char *, ftnlen), chkout_(char *, ftnlen), ssizec_(integer *, char *, ftnlen); logical outtdb; extern /* Subroutine */ int setmsg_(char *, ftnlen); extern logical somfls_(logical *, integer *); doublereal mytime; static char typtdb[8*10]; extern /* Subroutine */ int insrtc_(char *, char *, ftnlen, ftnlen); extern logical return_(void); static integer usrctr[2]; logical outtdt; extern /* Subroutine */ int swpool_(char *, integer *, char *, ftnlen, ftnlen); static char typtdt[8*11]; extern doublereal j2000_(void); static doublereal dta; doublereal tdb; extern doublereal spd_(void); doublereal tdt; static doublereal jd2000; /* $ Abstract */ /* Transform time from one uniform scale to another. The uniform */ /* time scales are TAI, GPS, TT, TDT, TDB, ET, JED, JDTDB, JDTDT. */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Required_Reading */ /* TIME */ /* $ Keywords */ /* CONVERSION */ /* TIME */ /* UTILITY */ /* $ Declarations */ /* $ Abstract */ /* This include file defines the dimension of the counter */ /* array used by various SPICE subsystems to uniquely identify */ /* changes in their states. */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Parameters */ /* CTRSIZ is the dimension of the counter array used by */ /* various SPICE subsystems to uniquely identify */ /* changes in their states. */ /* $ Author_and_Institution */ /* B.V. Semenov (JPL) */ /* $ Literature_References */ /* None. */ /* $ Version */ /* - SPICELIB Version 1.0.0, 29-JUL-2013 (BVS) */ /* -& */ /* End of include file. */ /* $ Brief_I/O */ /* VARIABLE I/O DESCRIPTION */ /* -------- --- -------------------------------------------------- */ /* EPOCH I An epoch. */ /* INSYS I The time scale associated with the input EPOCH. */ /* OUTSYS I The time scale associated with the function value. */ /* The function returns the d.p. in OUTSYS that is equivalent to the */ /* EPOCH on the INSYS time scale. */ /* $ Detailed_Input */ /* EPOCH is an epoch relative to the INSYS time scale. */ /* INSYS is a time scale. Acceptable values are: */ /* 'TAI' International Atomic Time. */ /* 'TDB' Barycentric Dynamical Time. */ /* 'TDT' Terrestrial Dynamical Time. */ /* 'TT' Terrestrial Time, identical to TDT. */ /* 'ET' Ephemeris time (in the SPICE system, this is */ /* equivalent to TDB). */ /* 'JDTDB' Julian Date relative to TDB. */ /* 'JDTDT' Julian Date relative to TDT. */ /* 'JED' Julian Ephemeris date (in the SPICE system */ /* this is equivalent to JDTDB). */ /* 'GPS' Global Positioning System Time. */ /* The routine is not sensitive to the case of the */ /* characters in INSYS; 'tai' 'Tai' and 'TAI' are all */ /* equivalent from the point of view of this routine. */ /* OUTSYS is the time scale to which EPOCH should be converted. */ /* Acceptable values are the same as for INSYS. The */ /* routine is not sensitive to the case of OUTSYS. */ /* $ Detailed_Output */ /* The function returns the time in the system specified by OUTSYS */ /* that is equivalent to the EPOCH in the INSYS time scale. */ /* $ Parameters */ /* None. */ /* $ Exceptions */ /* 1) The kernel pool must contain the variables: */ /* 'DELTET/DELTA_T_A' */ /* 'DELTET/K' */ /* 'DELTET/EB' */ /* 'DELTET/M' */ /* If these are not present, the error SPICE(MISSINGTIMEINFO) is */ /* signaled. (These variables are typically inserted into the */ /* kernel pool by loading a leapseconds kernel with the SPICE */ /* routine FURNSH.) */ /* 2) If the names of either the input or output time types are */ /* unrecognized, the error SPICE(BADTIMETYPE) is signaled. */ /* $ Files */ /* None. */ /* $ Particulars */ /* We use the term uniform time scale to refer to those */ /* representations of time that are numeric (each epoch is */ /* represented by a number) and additive. A numeric time system is */ /* additive if given the representations, E1 and E2, of any pair of */ /* successive epochs, the time elapsed between the epochs is given by */ /* E2 - E1. */ /* Given an epoch in one of the uniform time scales specified by */ /* INSYS, the function returns the equivalent representation in the */ /* scale specified by OUTSYS. A list of the recognized uniform time */ /* scales is given in the detailed input for INSYS. */ /* $ Examples */ /* To convert an epoch with respect to the International Atomic */ /* Time (TAI) scale to ET (Barycentric Dynamical Time), make the */ /* following assignment. */ /* ET = UNITIM ( TAI, 'TAI', 'ET' ) */ /* $ Restrictions */ /* 1) The appropriate variable must be loaded into the SPICE kernel */ /* pool (normally by loading a leapseconds kernel with FURNSH) */ /* prior to calling this routine. */ /* $ Literature_References */ /* None. */ /* $ Author_and_Institution */ /* N.J. Bachman (JPL) */ /* J. Diaz del Rio (ODC Space) */ /* H.A. Neilan (JPL) */ /* B.V. Semenov (JPL) */ /* W.L. Taber (JPL) */ /* E.D. Wright (JPL) */ /* $ Version */ /* - SPICELIB Version 1.5.0, 05-SEP-2020 (EDW) (JDR) */ /* Added time system name 'TT' (Terrestrial Time) as alternate */ /* assignment of 'TDT' (Terrestrial Dynamical Time). */ /* Included GPS time system mapping. */ /* Edited the header to comply with NAIF standard. */ /* Removed references to FURNSH, CLPOOL, KCLEAR, UNLOAD, and */ /* Required Reading documents and tutorials from the "variables */ /* not present" long error message. */ /* - SPICELIB Version 1.4.0, 09-SEP-2013 (BVS) */ /* Updated to keep track of the POOL counter and call ZZCVPOOL. */ /* - SPICELIB Version 1.3.0, 05-MAR-2009 (NJB) */ /* This routine now keeps track of whether its kernel pool */ /* look-up failed. If so, a kernel pool lookup is attempted on */ /* the next call to this routine. This change is an enhancement, */ /* not a bug fix (unlike similar modifications in SCLK routines). */ /* - SPICELIB Version 1.2.1, 15-NOV-2006 (EDW) (NJB) */ /* Replaced references to LDPOOL with references to FURNSH. */ /* Replaced references to RTPOOL with references to GDPOOL. */ /* Enhanced long error message associated with missing kernel */ /* variables. */ /* - SPICELIB Version 1.2.0, 17-FEB-1999 (WLT) */ /* Added a second call to SWPOOL in the event some required */ /* kernel pool variable is not supplied. */ /* - SPICELIB Version 1.1.0, 17-MAY-1994 (HAN) */ /* If the value of the function RETURN is .TRUE. upon execution of */ /* this module, this function is assigned a default value of */ /* either 0, 0.0D0, .FALSE., or blank depending on the type of */ /* the function. */ /* - SPICELIB Version 1.0.0, 28-MAR-1992 (WLT) */ /* -& */ /* $ Index_Entries */ /* Transform between two uniform numeric time systems */ /* Transform between two additive numeric time systems */ /* Convert one uniform numeric time system to another */ /* Convert one additive numeric time system to another */ /* -& */ /* SPICELIB functions */ /* Local parameters */ /* LBCELL is the bottom slot of a cell. */ /* NEEDED is the number of kernel pool variables needed by this */ /* routine. */ /* LNGVAR is the length of the longest kernel pool variable name */ /* that is used by this routine. */ /* MISLEN is the length required by the MISSED array of strings */ /* used for error messages. */ /* TYPLEN is the maximum length allowed for names of uniform */ /* time types. */ /* NTDT is the number of time types based on terrestrial dynamical */ /* time (TDT). */ /* NTDB is the number of time types base on barycentric dynamical */ /* time (TDB). */ /* NRECOG is the total number of recognized types. */ /* Constant shift between GPS time system and TAI time system. */ /* Local variables */ /* Saved variables */ /* Initial values */ /* Standard SPICE error handling. */ if (return_()) { ret_val = 0.; return ret_val; } chkin_("UNITIM", (ftnlen)6); if (first) { first = FALSE_; /* Initialize the backslash character. We use this for error */ /* message construction. */ *(unsigned char *)bslash = '\\'; /* Set up the parameters that we are going to need often. */ secspd = spd_(); jd2000 = j2000_(); /* Initialize the sets that we will use. */ s_copy(typtdt + 48, "JDTDT", (ftnlen)8, (ftnlen)5); s_copy(typtdt + 56, "TAI", (ftnlen)8, (ftnlen)3); s_copy(typtdt + 64, "TDT", (ftnlen)8, (ftnlen)3); s_copy(typtdt + 72, "GPS", (ftnlen)8, (ftnlen)3); s_copy(typtdt + 80, "TT", (ftnlen)8, (ftnlen)2); s_copy(typtdb + 48, "ET", (ftnlen)8, (ftnlen)2); s_copy(typtdb + 56, "JDTDB", (ftnlen)8, (ftnlen)5); s_copy(typtdb + 64, "JED", (ftnlen)8, (ftnlen)3); s_copy(typtdb + 72, "TDB", (ftnlen)8, (ftnlen)3); validc_(&c__5, &c__5, typtdt, (ftnlen)8); validc_(&c__4, &c__4, typtdb, (ftnlen)8); ssizec_(&c__9, recog, (ftnlen)8); unionc_(typtdt, typtdb, recog, (ftnlen)8, (ftnlen)8, (ftnlen)8); /* Initialize the local POOL counter to user value. */ zzctruin_(usrctr); /* Set up the kernel pool watchers */ swpool_("UNITIM", &c__4, vars__, (ftnlen)6, (ftnlen)16); } /* Check to see if any of the kernel items required by this */ /* routine have been updated since the last call to this */ /* entry point. */ zzcvpool_("UNITIM", usrctr, &update, (ftnlen)6); if (update || nodata) { /* Fetch all of the time parameters from the kernel pool. */ gdpool_("DELTET/DELTA_T_A", &c__1, &c__1, &n, &dta, found, (ftnlen)16) ; gdpool_("DELTET/K", &c__1, &c__1, &n, &k, &found[1], (ftnlen)8); gdpool_("DELTET/EB", &c__1, &c__1, &n, &eb, &found[2], (ftnlen)9); gdpool_("DELTET/M", &c__1, &c__2, &n, m, &found[3], (ftnlen)8); if (failed_()) { nodata = TRUE_; ret_val = 0.; chkout_("UNITIM", (ftnlen)6); return ret_val; } /* If anything wasn't found, it's an error dude. */ if (somfls_(found, &c__4)) { nodata = TRUE_; /* If we didn't get all of the things we needed for time */ /* conversion, we need to reset the watch. Otherwise */ /* subsequent calls to this routine will never have the */ /* needed data. */ swpool_("UNITIM", &c__4, vars__, (ftnlen)6, (ftnlen)16); /* Writing concatenation */ i__1[0] = 290, a__1[0] = "The following variables, needed to con" "vert between the input uniform time scales, were not fou" "nd in the kernel pool: # Your program may have failed to" " load a leapseconds kernel. Other possible causes of thi" "s problem include loading an invalid leapseconds kernel-" "--one that lacks an initial "; i__1[1] = 1, a__1[1] = bslash; i__1[2] = 10, a__1[2] = "begindata "; i__1[3] = 41, a__1[3] = "marker or final newline character, or i" "s "; i__1[4] = 42, a__1[4] = "otherwise corrupted---or deleting previ" "ous"; i__1[5] = 42, a__1[5] = "ly loaded kernel pool variables via cal" "ls "; i__1[6] = 40, a__1[6] = "to routines that clear the kernel pool. " ; s_cat(ch__1, a__1, i__1, &c__7, (ftnlen)466); setmsg_(ch__1, (ftnlen)466); for (i__ = 1; i__ <= 4; ++i__) { if (! found[(i__2 = i__ - 1) < 4 && 0 <= i__2 ? i__2 : s_rnge( "found", i__2, "unitim_", (ftnlen)485)]) { errch_("#", missed + ((i__2 = i__ - 1) < 4 && 0 <= i__2 ? i__2 : s_rnge("missed", i__2, "unitim_", (ftnlen) 486)) * 20, (ftnlen)1, (ftnlen)20); } } errch_(", #", ".", (ftnlen)3, (ftnlen)1); sigerr_("SPICE(MISSINGTIMEINFO)", (ftnlen)22); chkout_("UNITIM", (ftnlen)6); ret_val = *epoch; return ret_val; } /* At this point the kernel data checks are done. */ nodata = FALSE_; } /* Normalize the IN and OUT scale variables */ ucase_(insys, myin, insys_len, (ftnlen)8); ucase_(outsys, myout, outsys_len, (ftnlen)8); ssizec_(&c__2, types, (ftnlen)8); insrtc_(myin, types, (ftnlen)8, (ftnlen)8); insrtc_(myout, types, (ftnlen)8, (ftnlen)8); /* We will work with a local copy of EPOCH. */ mytime = *epoch; /* First make sure both types are recognized. */ if (! setc_(types, "<", recog, (ftnlen)8, (ftnlen)1, (ftnlen)8)) { setmsg_("The time types recognized by UNITIM are: TAI, GPS, TT, TDT," " JDTDT, TDB, ET, JED, JDTDB. At least one of the inputs (#, " "#) was not in the list of recognized types. ", (ftnlen)163); errch_("#", myin, (ftnlen)1, (ftnlen)8); errch_("#", myout, (ftnlen)1, (ftnlen)8); sigerr_("SPICE(BADTIMETYPE)", (ftnlen)18); chkout_("UNITIM", (ftnlen)6); ret_val = *epoch; return ret_val; } /* If the input and output types are the same, just copy the input */ /* epoch to the output and call it quits. */ if (s_cmp(myin, myout, (ftnlen)8, (ftnlen)8) == 0) { ret_val = mytime; chkout_("UNITIM", (ftnlen)6); return ret_val; } /* Determine the base types of the input and output types. */ intdt = elemc_(myin, typtdt, (ftnlen)8, (ftnlen)8); outtdt = elemc_(myout, typtdt, (ftnlen)8, (ftnlen)8); intdb = ! intdt; outtdb = ! outtdt; /* The two types, TDT and TDB, will be used as the fundamental */ /* base used in conversions. */ /* TAI, GPS, and JDTDT will be converted to TDT */ /* JED and JDTDB will be converted to TDB. */ /* ET means TDB; TT means TDT. */ if (s_cmp(myin, "TAI", (ftnlen)8, (ftnlen)3) == 0) { mytime += dta; } else if (s_cmp(myin, "GPS", (ftnlen)8, (ftnlen)3) == 0) { mytime += dta + 19.; } else if (s_cmp(myin, "JDTDT", (ftnlen)8, (ftnlen)5) == 0) { mytime = (mytime - jd2000) * secspd; } else if (s_cmp(myin, "JED", (ftnlen)8, (ftnlen)3) == 0) { mytime = (mytime - jd2000) * secspd; } else if (s_cmp(myin, "JDTDB", (ftnlen)8, (ftnlen)5) == 0) { mytime = (mytime - jd2000) * secspd; } /* At this point, MYTIME has been converted from its input */ /* to one of the base types. */ /* Next change type from TDB to TDT or vice versa, if */ /* required. (The time is already in TDT or TDB). */ if (intdt && outtdb) { tdt = mytime; tdb = tdt + k * sin(m[0] + m[1] * tdt + eb * sin(m[0] + m[1] * tdt)); mytime = tdb; } else if (intdb && outtdt) { /* What we have to do here is invert the formula used to get */ /* TDB from TDT that was used above. */ /* Of course solving the equation */ /* TDB = TDT + K*SIN { M0 + M1*TDT + EB*SIN( MO + M1*TDT ) } */ /* analytically for TDT if given TDB is no piece of cake. */ /* However, we can get as close as we want to TDT if */ /* we notice a few tricks. First, let's let f(t) denote the */ /* function */ /* f(t) = SIN( M0 + M1*t + EB*SIN( M0 + M1*t ) ) */ /* With this simpler notation we can rewrite our problem */ /* as that of solving the equation */ /* y = t + K*f(t) */ /* for t given y. Whichever t satisfies this equation will be */ /* unique. The uniqueness of the solution is ensured because the */ /* expression on the right-hand side of the equation is */ /* monotone increasing in t. */ /* Let's suppose that t is the solution, then the following */ /* is true. */ /* t = y - K*f(t) */ /* but we can also replace the t on the right hand side of the */ /* equation by y - K*f(t). Thus */ /* t = y - K*f( y - K*f(t)) */ /* = y - K*f( y - K*f( y - K*f(t))) */ /* = y - K*f( y - K*f( y - K*f( y - K*f(t)))) */ /* = y - K*f( y - K*f( y - K*f( y - K*f( y - K*f(t))))) */ /* . */ /* . */ /* . */ /* = y - K*f( y - K*f( y - K*f( y - K*f( y - K*f(y - ... ))) */ /* and so on, for as long as we have patience to perform the */ /* substitutions. */ /* The point of doing this recursive substitution is that we */ /* hope to move t to an insignificant part of the computation. */ /* This would seem to have a reasonable chance of success since */ /* K is a small number and f is bounded by 1. */ /* Following this idea, we will attempt to solve for t using */ /* the recursive method outlined below. */ /* We will make our first guess at t, call it t_0. */ /* t_0 = y */ /* Our next guess, t_1, is given by: */ /* t_1 = y - K*f(t_0) */ /* And so on: */ /* t_2 = y - K*f(t_1) [ = y - K*f(y - K*f(y)) ] */ /* t_3 = y - K*f(t_2) [ = y - K*f(y - K*f(y - K*f(y))) ] */ /* . */ /* . */ /* . */ /* t_n = y - K*f(t_(n-1)) [ = y - K*f(y - K*f(y - K*f(y...)))] */ /* The questions to ask at this point are: */ /* 1) Do the t_i's converge? */ /* 2) If they converge, do they converge to t? */ /* 3) If they converge to t, how fast do they get there? */ /* 1) The sequence of approximations converges. */ /* | t_n - t_(n-1) | = [ y - K*f( t_(n-1) ) ] */ /* - [ y - K*f( t_(n-2) ) ] */ /* = K*[ f( t_(n-2) ) - f( t_(n-1) ) ] */ /* The function f has an important property. The absolute */ /* value of its derivative is always less than M1*(1+EB). */ /* This means that for any pair of real numbers s,t */ /* | f(t) - f(s) | < M1*(1+EB)*| t - s |. */ /* From this observation, we can see that */ /* | t_n - t_(n-1) | < K*M1*(1+EB)*| t_(n-1) - t_(n-2) | */ /* With this fact available, we could (with a bit more work) */ /* conclude that the sequence of t_i's converges and that */ /* it converges at a rate that is at least as fast as the */ /* sequence L, L**2, L**3, .... */ /* Where L = K*M1*(1+EB) << 1. */ /* 2) If we let t be the limit of the t_i's then it follows */ /* that */ /* t = y - K*f(t). */ /* or that */ /* y = t + K*f(t). */ /* 3) As we already pointed out, the sequence of t_i's */ /* converges at least as fast as the geometric series */ /* L, L**2, ... */ /* Since K*M1*(1+EB) is quite small (on the order of 10**-9) */ /* 3 iterations should get us as close as we can get to the */ /* solution for TDT */ tdb = mytime; tdt = tdb; for (i__ = 1; i__ <= 3; ++i__) { tdt = tdb - k * sin(m[0] + m[1] * tdt + eb * sin(m[0] + m[1] * tdt)); } mytime = tdt; } /* Now MYTIME is in the base type of the requested output. */ /* If further conversion is required, we do it here. */ if (s_cmp(myout, "TAI", (ftnlen)8, (ftnlen)3) == 0) { mytime -= dta; } else if (s_cmp(myout, "GPS", (ftnlen)8, (ftnlen)3) == 0) { mytime -= dta + 19.; } else if (s_cmp(myout, "JDTDT", (ftnlen)8, (ftnlen)5) == 0) { mytime = mytime / secspd + jd2000; } else if (s_cmp(myout, "JED", (ftnlen)8, (ftnlen)3) == 0) { mytime = mytime / secspd + jd2000; } else if (s_cmp(myout, "JDTDB", (ftnlen)8, (ftnlen)5) == 0) { mytime = mytime / secspd + jd2000; } ret_val = mytime; chkout_("UNITIM", (ftnlen)6); return ret_val; } /* unitim_ */
34.525239
78
0.576915
[ "object", "transform" ]
31844a71475704661d96d8948ce14ae12bba50e1
16,540
h
C
platform/gucefCORE/include/gucefCORE_CTLinkedCloneable.h
alexakuzin/GUCEF-1
436035c4266c5d90cd8716c1d0fad519c7059e34
[ "Apache-2.0" ]
5
2016-04-18T23:12:51.000Z
2022-03-06T05:12:07.000Z
platform/gucefCORE/include/gucefCORE_CTLinkedCloneable.h
alexakuzin/GUCEF-1
436035c4266c5d90cd8716c1d0fad519c7059e34
[ "Apache-2.0" ]
2
2015-10-09T19:13:25.000Z
2018-12-25T17:16:54.000Z
platform/gucefCORE/include/gucefCORE_CTLinkedCloneable.h
alexakuzin/GUCEF-1
436035c4266c5d90cd8716c1d0fad519c7059e34
[ "Apache-2.0" ]
15
2015-02-23T16:35:28.000Z
2022-03-25T13:40:33.000Z
/* * gucefCOMCORE: GUCEF module providing basic communication facilities * * Copyright (C) 1998 - 2020. Dinand Vanvelzen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GUCEF_CORE_CTLINKEDCLONEABLE_H #define GUCEF_CORE_CTLINKEDCLONEABLE_H /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #include <assert.h> #ifndef GUCEF_CORE_CICLONEABLE_H #include "CICloneable.h" #define GUCEF_CORE_CICLONEABLE_H #endif /* GUCEF_CORE_CICLONEABLE_H ? */ #ifndef GUCEF_CORE_EXCEPTIONCLASSMACROS_H #include "ExceptionClassMacros.h" #define GUCEF_CORE_EXCEPTIONCLASSMACROS_H #endif /* GUCEF_CORE_EXCEPTIONCLASSMACROS_H ? */ #ifndef GUCEF_CORE_EXCEPTIONTHROWMACROS_H #include "ExceptionThrowMacros.h" #define GUCEF_CORE_EXCEPTIONTHROWMACROS_H #endif /* GUCEF_CORE_EXCEPTIONTHROWMACROS_H ? */ #ifndef GUCEF_CORE_LOGGING_H #include "gucefCORE_Logging.h" #define GUCEF_CORE_LOGGING_H #endif /* GUCEF_CORE_LOGGING_H ? */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace CORE { /*-------------------------------------------------------------------------// // // // TEMPLATES // // // //-------------------------------------------------------------------------*/ /** * Contrary to the CTCloneableObj ans CTLinkedCloneable templates this one * does not use T as a non-cloning-capable object but instead acts as a * cloning capable pointer to the cloneable. * * Please note that this is distinct from a Shared pointer which is about * delegating lifecycle management of the object. * This template is intended to be used as light weight references to avoid * costly creation of objects needlessly, such as internal buffer, where we do NOT want * to delegate lifecycle management. We'd want to reuse the buffer after say * an event notification referencing the buffer contents. In this example * scenario it may be needed to store the referenced data in a queue for * processing by another thread in which case the data can be auto-cloned * upon queue insertion. */ template< typename T > class CTConstLinkedCloneable : public CICloneable { public: CTConstLinkedCloneable( void ); // preserves the link, does not copy the wrapped object explicit CTConstLinkedCloneable( const T* data ); // creates a copy of the wrapped object CTConstLinkedCloneable( const CTConstLinkedCloneable& src ); virtual ~CTConstLinkedCloneable() GUCEF_VIRTUAL_OVERRIDE; CTConstLinkedCloneable& operator=( const CTConstLinkedCloneable& src ); virtual CICloneable* Clone( void ) const GUCEF_VIRTUAL_OVERRIDE; inline operator bool() const; inline bool operator<( const CTConstLinkedCloneable& other ) const; inline const T* operator->( void ) const; /** * Because const linkage is mandated using this will cause a private copy to be created */ inline T* operator->( void ); inline bool IsNULL( void ) const; void LinkTo( const T* data ); const T& GetData( void ) const; /** * Because const linkage is mandated using this will cause a private copy to be created */ T& GetData( void ); void Clear( void ); inline operator const T*() const; /** * Because const linkage is mandated using this will cause a private copy to be created */ inline operator T*(); GUCEF_DEFINE_INLINED_MSGEXCEPTION( ENULLPointer ); protected: const T* m_ptr; bool m_linked; }; /*-------------------------------------------------------------------------*/ template< typename T > class CTLinkedCloneable : public CICloneable { public: CTLinkedCloneable( void ); // preserves the link, does not copy the wrapped object explicit CTLinkedCloneable( T* data ); // creates a copy of the wrapped object CTLinkedCloneable( const CTLinkedCloneable& src ); virtual ~CTLinkedCloneable() GUCEF_VIRTUAL_OVERRIDE; CTLinkedCloneable& operator=( const CTLinkedCloneable& src ); virtual CICloneable* Clone( void ) const GUCEF_VIRTUAL_OVERRIDE; inline operator bool() const; inline bool operator<( const CTLinkedCloneable& other ) const; inline const T* operator->( void ) const; inline bool IsNULL( void ) const; void LinkTo( T* data ); const T& GetData( void ) const; T& GetData( void ); void Clear( void ); inline operator const T*() const; inline operator T*(); GUCEF_DEFINE_INLINED_MSGEXCEPTION( ENULLPointer ); protected: T* m_ptr; bool m_linked; }; /*-------------------------------------------------------------------------// // // // UTILITIES // // // //-------------------------------------------------------------------------*/ template< typename T > CTConstLinkedCloneable< T >::CTConstLinkedCloneable( void ) : m_ptr( GUCEF_NULL ) , m_linked( false ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ template< typename T > CTConstLinkedCloneable< T >::CTConstLinkedCloneable( const T* data ) : m_ptr( data ) , m_linked( GUCEF_NULL != m_ptr ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ template< typename T > CTConstLinkedCloneable< T >::CTConstLinkedCloneable( const CTConstLinkedCloneable< T >& src ) : m_ptr( GUCEF_NULL ) , m_linked( false ) {GUCEF_TRACE; if ( GUCEF_NULL != src.m_ptr ) { m_ptr = static_cast< T* >( src.m_ptr->Clone() ); } } /*-------------------------------------------------------------------------*/ template< typename T > CTConstLinkedCloneable< T >::~CTConstLinkedCloneable() {GUCEF_TRACE; Clear(); } /*-------------------------------------------------------------------------*/ template< typename T > void CTConstLinkedCloneable< T >::Clear( void ) {GUCEF_TRACE; if ( !m_linked ) { delete m_ptr; } m_ptr = GUCEF_NULL; } /*-------------------------------------------------------------------------*/ template< typename T > CTConstLinkedCloneable< T >& CTConstLinkedCloneable< T >::operator=( const CTConstLinkedCloneable< T >& src ) {GUCEF_TRACE; if ( this != &src ) { Clear(); if ( GUCEF_NULL != src.m_ptr ) m_ptr = static_cast< T* >( src.m_ptr->Clone() ); } return *this; } /*-------------------------------------------------------------------------*/ template< typename T > void CTConstLinkedCloneable< T >::LinkTo( const T* ptr ) {GUCEF_TRACE; Clear(); m_ptr = ptr; m_linked = GUCEF_NULL != ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline const T* CTConstLinkedCloneable< T >::operator->( void ) const {GUCEF_TRACE; return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline T* CTConstLinkedCloneable< T >::operator->( void ) {GUCEF_TRACE; // mutable access requires a private copy if ( GUCEF_NULL != m_ptr && m_linked ) { m_ptr = static_cast< T* >( m_ptr->Clone() ); m_linked = false; } return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline bool CTConstLinkedCloneable< T >::operator<( const CTConstLinkedCloneable< T >& other ) const {GUCEF_TRACE; return m_ptr < other.m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTConstLinkedCloneable< T >::operator bool() const {GUCEF_TRACE; return GUCEF_NULL != m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTConstLinkedCloneable< T >::operator const T*() const {GUCEF_TRACE; return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTConstLinkedCloneable< T >::operator T*() {GUCEF_TRACE; // mutable access requires a private copy if ( GUCEF_NULL != m_ptr && m_linked ) { m_ptr = static_cast< T* >( m_ptr->Clone() ); m_linked = false; } return const_cast< T* >( m_ptr ); } /*-------------------------------------------------------------------------*/ template< typename T > inline bool CTConstLinkedCloneable< T >::IsNULL() const {GUCEF_TRACE; return GUCEF_NULL == m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > CICloneable* CTConstLinkedCloneable< T >::Clone( void ) const {GUCEF_TRACE; return new CTConstLinkedCloneable< T >( *this ); } /*-------------------------------------------------------------------------*/ template< typename T > const T& CTConstLinkedCloneable< T >::GetData( void ) const {GUCEF_TRACE; if ( GUCEF_NULL != m_ptr ) { return *m_ptr; } GUCEF_EMSGTHROW( ENULLPointer, "CTConstLinkedCloneable::GetData(): This operation is impossible without a valid object" ); } /*-------------------------------------------------------------------------*/ template< typename T > T& CTConstLinkedCloneable< T >::GetData( void ) {GUCEF_TRACE; if ( GUCEF_NULL != m_ptr ) { // mutable access requires a private copy if ( m_linked ) { m_ptr = static_cast< T* >( m_ptr->Clone() ); m_linked = false; } return const_cast< T& >( *m_ptr ); } GUCEF_EMSGTHROW( ENULLPointer, "CTConstLinkedCloneable::GetData(): This operation is impossible without a valid object" ); } /*-------------------------------------------------------------------------*/ template< typename T > CTLinkedCloneable< T >::CTLinkedCloneable( void ) : m_ptr( GUCEF_NULL ) , m_linked( false ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ template< typename T > CTLinkedCloneable< T >::CTLinkedCloneable( T* data ) : m_ptr( data ) , m_linked( GUCEF_NULL != m_ptr ) {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ template< typename T > CTLinkedCloneable< T >::CTLinkedCloneable( const CTLinkedCloneable< T >& src ) : m_ptr( GUCEF_NULL ) , m_linked( false ) {GUCEF_TRACE; if ( GUCEF_NULL != src.m_ptr ) { m_ptr = static_cast< T* >( src.m_ptr->Clone() ); } } /*-------------------------------------------------------------------------*/ template< typename T > CTLinkedCloneable< T >::~CTLinkedCloneable() {GUCEF_TRACE; Clear(); } /*-------------------------------------------------------------------------*/ template< typename T > void CTLinkedCloneable< T >::Clear( void ) {GUCEF_TRACE; if ( !m_linked ) { delete m_ptr; } m_ptr = GUCEF_NULL; } /*-------------------------------------------------------------------------*/ template< typename T > CTLinkedCloneable< T >& CTLinkedCloneable< T >::operator=( const CTLinkedCloneable< T >& src ) {GUCEF_TRACE; if ( this != &src ) { Clear(); if ( GUCEF_NULL != src.m_ptr ) m_ptr = static_cast< T* >( src.m_ptr->Clone() ); } return *this; } /*-------------------------------------------------------------------------*/ template< typename T > void CTLinkedCloneable< T >::LinkTo( T* ptr ) {GUCEF_TRACE; Clear(); m_ptr = ptr; m_linked = GUCEF_NULL != ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline const T* CTLinkedCloneable< T >::operator->( void ) const {GUCEF_TRACE; return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline bool CTLinkedCloneable< T >::operator<( const CTLinkedCloneable< T >& other ) const {GUCEF_TRACE; return m_ptr < other.m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTLinkedCloneable< T >::operator bool() const {GUCEF_TRACE; return GUCEF_NULL != m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTLinkedCloneable< T >::operator const T*() const {GUCEF_TRACE; return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline CTLinkedCloneable< T >::operator T*() {GUCEF_TRACE; return m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > inline bool CTLinkedCloneable< T >::IsNULL() const {GUCEF_TRACE; return GUCEF_NULL == m_ptr; } /*-------------------------------------------------------------------------*/ template< typename T > CICloneable* CTLinkedCloneable< T >::Clone( void ) const {GUCEF_TRACE; return new CTLinkedCloneable< T >( *this ); } /*-------------------------------------------------------------------------*/ template< typename T > const T& CTLinkedCloneable< T >::GetData( void ) const {GUCEF_TRACE; if ( GUCEF_NULL != m_ptr ) { return *m_ptr; } GUCEF_EMSGTHROW( ENULLPointer, "CTLinkedCloneable::GetData(): This operation is impossible without a valid object" ); } /*-------------------------------------------------------------------------*/ template< typename T > T& CTLinkedCloneable< T >::GetData( void ) {GUCEF_TRACE; if ( GUCEF_NULL != m_ptr ) { return *m_ptr; } GUCEF_EMSGTHROW( ENULLPointer, "CTLinkedCloneable::GetData(): This operation is impossible without a valid object" ); } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace CORE */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/ #endif /* GUCEF_CORE_CTLINKEDCLONEABLE_H ? */
27.520799
127
0.461487
[ "object" ]
3184511d950d520cea7451718b145e5b8f3fd25f
1,430
h
C
Sources/Internal/Render/Highlevel/StaticOcclusionRenderPass.h
typicalMoves/dava.engine
31625a6ae5f66c372089cbc436ed850102366154
[ "BSD-3-Clause" ]
4
2021-04-22T05:41:59.000Z
2021-12-07T20:16:20.000Z
Sources/Internal/Render/Highlevel/StaticOcclusionRenderPass.h
typicalMoves/dava.engine
31625a6ae5f66c372089cbc436ed850102366154
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Render/Highlevel/StaticOcclusionRenderPass.h
typicalMoves/dava.engine
31625a6ae5f66c372089cbc436ed850102366154
[ "BSD-3-Clause" ]
1
2021-10-01T05:17:23.000Z
2021-10-01T05:17:23.000Z
#ifndef __DAVAENGINE_STATIC_OCCLUSION_RENDER_PASS__ #define __DAVAENGINE_STATIC_OCCLUSION_RENDER_PASS__ #include "Base/BaseTypes.h" #include "Base/BaseObject.h" #include "Base/BaseMath.h" #include "Render/Highlevel/RenderPass.h" #include "Render/RenderBase.h" #include "Render/Texture.h" namespace DAVA { // use only for debug purposes // enabling this will save each rendered frame to documents folder #define SAVE_OCCLUSION_IMAGES 0 struct StaticOcclusionFrameResult; class StaticOcclusionData; class StaticOcclusionRenderPass : public RenderPass { public: StaticOcclusionRenderPass(const FastName& name); ~StaticOcclusionRenderPass(); void DrawOcclusionFrame(RenderSystem* renderSystem, Camera* occlusionCamera, StaticOcclusionFrameResult& target, const StaticOcclusionData&, uint32 blockIndex); private: bool ShouldDisableDepthWrite(RenderBatch*); private: enum RenderBatchOption : uint32 { OPTION_DISABLE_DEPTH = 1 << 0, }; using BatchWithOptions = std::pair<RenderBatch*, uint32>; rhi::HTexture colorBuffer; rhi::HTexture depthBuffer; rhi::HDepthStencilState stateDisabledDepthWrite; Vector<RenderBatch*> terrainBatches; Vector<BatchWithOptions> meshRenderBatches; UnorderedSet<RenderBatch*> batchesWithoutDepth; UnorderedSet<RenderBatch*> processedBatches; }; }; #endif //__DAVAENGINE_STATIC_OCCLUSION_RENDER_PASS__
27.5
111
0.772028
[ "render", "vector" ]
318921002d3ba513f7a7cceca680ea9595e7d079
608
h
C
src/zcbenchmarks.h
j-cimb-barker/komodo
e484d0960da0c00abfe09cbb79a3366c45c60f5e
[ "MIT" ]
null
null
null
src/zcbenchmarks.h
j-cimb-barker/komodo
e484d0960da0c00abfe09cbb79a3366c45c60f5e
[ "MIT" ]
null
null
null
src/zcbenchmarks.h
j-cimb-barker/komodo
e484d0960da0c00abfe09cbb79a3366c45c60f5e
[ "MIT" ]
null
null
null
#ifndef BENCHMARKS_H #define BENCHMARKS_H #include <sys/time.h> #include <stdlib.h> extern double benchmark_sleep(); extern double benchmark_parameter_loading(); extern double benchmark_create_joinsplit(); extern double benchmark_solve_equihash(); extern std::vector<double> benchmark_solve_equihash_threaded(int nThreads); extern double benchmark_verify_joinsplit(const JSDescription &joinsplit); extern double benchmark_verify_equihash(); extern double benchmark_large_tx(); extern double benchmark_try_decrypt_notes(size_t nAddrs); extern double benchmark_increment_note_witnesses(size_t nTxs); #endif
32
75
0.845395
[ "vector" ]
318ce5cba4d0127d1ef385a397953ce2f5f0f22c
1,034
h
C
vendor/libgit2/src/commit.h
EricAtORS/p4-fusion
db3b52310d3a24f850026dd4aa3a39a2dee2968e
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
312
2019-09-08T18:18:43.000Z
2022-03-31T08:13:30.000Z
vendor/libgit2/src/commit.h
EricAtORS/p4-fusion
db3b52310d3a24f850026dd4aa3a39a2dee2968e
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
85
2019-10-06T16:03:26.000Z
2022-02-24T06:41:13.000Z
vendor/libgit2/src/commit.h
EricAtORS/p4-fusion
db3b52310d3a24f850026dd4aa3a39a2dee2968e
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
36
2019-10-06T16:06:09.000Z
2022-01-23T12:29:14.000Z
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_commit_h__ #define INCLUDE_commit_h__ #include "common.h" #include "git2/commit.h" #include "tree.h" #include "repository.h" #include "array.h" #include <time.h> struct git_commit { git_object object; git_array_t(git_oid) parent_ids; git_oid tree_id; git_signature *author; git_signature *committer; char *message_encoding; char *raw_message; char *raw_header; char *summary; char *body; }; void git_commit__free(void *commit); int git_commit__parse(void *commit, git_odb_object *obj); int git_commit__parse_raw(void *commit, const char *data, size_t size); typedef enum { GIT_COMMIT_PARSE_QUICK = (1 << 0), /**< Only parse parents and committer info */ } git_commit__parse_flags; int git_commit__parse_ext(git_commit *commit, git_odb_object *odb_obj, unsigned int flags); #endif
22
91
0.755319
[ "object" ]
31922cf29280f4dd269fe30c1be6697c1456ffeb
1,177
h
C
deps/src/gropt/incl/TestLRMatrixCompletion.h
pnavaro/ElasticFDA.jl
0ed8c3f483c3a62f4215a6b65894da34e77eefc1
[ "MIT" ]
7
2017-02-05T23:39:14.000Z
2021-06-03T06:41:47.000Z
deps/src/gropt/incl/TestLRMatrixCompletion.h
pnavaro/ElasticFDA.jl
0ed8c3f483c3a62f4215a6b65894da34e77eefc1
[ "MIT" ]
3
2016-08-31T20:48:32.000Z
2021-12-15T02:18:36.000Z
deps/src/gropt/incl/TestLRMatrixCompletion.h
pnavaro/ElasticFDA.jl
0ed8c3f483c3a62f4215a6b65894da34e77eefc1
[ "MIT" ]
6
2016-07-12T02:13:16.000Z
2020-09-22T17:42:16.000Z
/* This is the test file to run the problem defined in LRMatrixCompletion.h and LRMatrixCompletion.cpp. ---- WH */ #ifndef TESTLRMATRIXCOMPLETION_H #define TESTLRMATRIXCOMPLETION_H #include <iostream> #include "Others/randgen.h" #include "Manifolds/Manifold.h" #include "Problems/Problem.h" #include "Solvers/SolversLS.h" #include <ctime> #include "test/DriverMexProb.h" #include "Problems/LRMatrixCompletion/LRMatrixCompletion.h" #include "Manifolds/LowRank/LowRank.h" #include "Manifolds/LowRank/LowRankVariable.h" #include "Solvers/RSD.h" #include "Solvers/RNewton.h" #include "Solvers/RCG.h" #include "Solvers/RBroydenFamily.h" #include "Solvers/RWRBFGS.h" #include "Solvers/RBFGS.h" #include "Solvers/LRBFGS.h" #include "Solvers/SolversTR.h" #include "Solvers/RTRSD.h" #include "Solvers/RTRNewton.h" #include "Solvers/RTRSR1.h" #include "Solvers/LRTRSR1.h" #include "Others/def.h" using namespace ROPTLIB; void testLRMatrixCompletion(void); void testLRMatrixCompletionMore(void); double LRMatrixCompletionLinesearchInput(integer iter, Variable *x1, Vector *eta1, double initialstepsize, double initialslope, const Problem *prob, const Solvers *solver); #endif
25.042553
172
0.785047
[ "vector" ]
3195ecab73f192be930222460fffb52d1cb8ea48
954
h
C
src/platforms/cuda/CudaFactory.h
yongdd/langevin-fts
ae342e3d62c1fe87973d4168a61e208153cc8a3a
[ "MIT" ]
null
null
null
src/platforms/cuda/CudaFactory.h
yongdd/langevin-fts
ae342e3d62c1fe87973d4168a61e208153cc8a3a
[ "MIT" ]
null
null
null
src/platforms/cuda/CudaFactory.h
yongdd/langevin-fts
ae342e3d62c1fe87973d4168a61e208153cc8a3a
[ "MIT" ]
null
null
null
/*---------------------------------------------------------- * class CudaFactory *-----------------------------------------------------------*/ #ifndef CUDA_FACTORY_H_ #define CUDA_FACTORY_H_ #include "PolymerChain.h" #include "SimulationBox.h" #include "Pseudo.h" #include "AndersonMixing.h" #include "AbstractFactory.h" class CudaFactory : public AbstractFactory { public : PolymerChain* create_polymer_chain( double f, int n_segment, double chi_n, std::string model_name, double epsilon=1.0) override; SimulationBox* create_simulation_box( std::vector<int> nx, std::vector<double> lx) override; Pseudo* create_pseudo( SimulationBox *sb, PolymerChain *pc) override; AndersonMixing* create_anderson_mixing( int n_var, int max_hist, double start_error, double mix_min, double mix_init) override; void display_info() override; }; #endif
29.8125
63
0.597484
[ "vector" ]
3197d950f2d704b0945bdebf95aab7fbb47b5b00
3,156
h
C
demo/desktop/desktop_window_manager.h
JoKaWare/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
19
2015-03-30T09:49:58.000Z
2020-01-17T20:05:12.000Z
demo/desktop/desktop_window_manager.h
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
1
2015-12-31T06:08:27.000Z
2015-12-31T06:08:27.000Z
demo/desktop/desktop_window_manager.h
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
11
2015-06-01T06:18:03.000Z
2020-05-10T07:18:53.000Z
#ifndef __desktop_window_manager_h__ #define __desktop_window_manager_h__ #pragma once #include <vector> #include "base/memory/scoped_ptr.h" #include "ui/views/widget/widget.h" #include "window_manager.h" namespace gfx { class Point; } namespace views { namespace desktop { class WindowController; // A tentative window manager for views destktop until we have *right* // implementation based on aura/layer API. This is minimum // implmenetation and complicated actio like moving transformed window // doesn't work. class DesktopWindowManager : public views::WindowManager, public Widget::Observer { public: DesktopWindowManager(Widget* desktop); virtual ~DesktopWindowManager(); void UpdateWindowsAfterScreenSizeChanged(const gfx::Rect& new_size); // view::WindowManager implementations: virtual void StartMoveDrag(views::Widget* widget, const gfx::Point& point); virtual void StartResizeDrag(views::Widget* widget, const gfx::Point& point, int hittest_code); virtual bool SetMouseCapture(views::Widget* widget); virtual bool ReleaseMouseCapture(views::Widget* widget); virtual bool HasMouseCapture(const views::Widget* widget) const; virtual bool HandleKeyEvent(views::Widget* widget, const views::KeyEvent& event); virtual bool HandleMouseEvent(views::Widget* widget, const views::MouseEvent& event); virtual void Register(Widget* widget); private: // Overridden from Widget::Observer. virtual void OnWidgetClosing(Widget* widget); virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible); virtual void OnWidgetActivationChanged(Widget* widget, bool active); void SetMouseCapture(); void ReleaseMouseCapture(); bool HasMouseCapture() const; void Activate(Widget* widget); // Returns true if a deactivated widget at the location was activated. Returns // false otherwise. bool ActivateWidgetAtLocation(Widget* widget, const gfx::Point& point); views::Widget* desktop_; views::Widget* mouse_capture_; views::Widget* active_widget_; // An unordered list of all the top-level Widgets. std::vector<views::Widget*> toplevels_; scoped_ptr<WindowController> window_controller_; DISALLOW_COPY_AND_ASSIGN(DesktopWindowManager); }; // An behavioral interface for objects implements window resize/movement. class WindowController { public: WindowController(); virtual ~WindowController(); virtual bool OnMouseEvent(const views::MouseEvent& event) = 0; private: DISALLOW_COPY_AND_ASSIGN(WindowController); }; } //namespace desktop } //namespace view #endif //__desktop_window_manager_h__
32.536082
90
0.635615
[ "vector" ]
319c4e5d2f2ed120ea131cbe5ce2384fb8ba636d
12,183
c
C
src/biopack/psglib/gnoesyChsqc_CNfilt.c
timburrow/ovj-private
5b84ff1ac51ef387d5073352f9c604e28150d6d2
[ "Apache-2.0" ]
1
2019-03-23T08:33:44.000Z
2019-03-23T08:33:44.000Z
src/biopack/psglib/gnoesyChsqc_CNfilt.c
timburrow/openvnmrj-source
f5e65eb2db4bded3437701f0fa91abd41928579c
[ "Apache-2.0" ]
null
null
null
src/biopack/psglib/gnoesyChsqc_CNfilt.c
timburrow/openvnmrj-source
f5e65eb2db4bded3437701f0fa91abd41928579c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* gnoesyChsqc_CNfilt.c Sequence for F1 13C,15N-filtered NOESY-HSQC(13C) experiment, with option for carbonyl and 15N decoupling during t2. Created: as mf_f13c_noe_hsqc_s13c.c 11/19/2003 by M. Rance, U.Cincinnati Modified for BioPack, added "autocal" option for automatic creation of carbonyl decoupling pulse, GG, Varian, November 2005 Uses isotope-filtering element invented by Stuart et al., J.Am.Chem.Soc. 121, 5346-5347 (1999) Set: d2 = 0 tauxh = 1/(4Jxh) satmode = 'y' for presat satdly = length of presaturation period satpwr = power level for presat gstab = gradient recovery delay NOTE: the parameter dof_t1 sets the C13 frequency during t1, not dof. dof is the C13 frequency during the HSQC and decoupling period. Filter Gradients: gt2 = cleaning gradient gt3 = gradient pulse during initial IzSz period gt4 = gradient pulse during second IzSz period gt5 = cleaning gradient For gt2=gt3=gt4=gt5, gzlvl2-gzlvl3+gzlvl4+gzlvl5 must =0. Half-dwell time delay standard in t1 and t2. Use lp1=-180 rp1=90; lp2=-180 rp2=90 for proper phasing. To permit adjustment of the filter gradients' strength, the parameter gscale can be used. It will multiply gzlvl2,gzlvl3, gzlvl4 and gzlvl5 by the same factor. The ratio must be maintained, however. */ #include <standard.h> #include "Pbox_bio.h" /* Pbox Bio Pack Pulse Shaping Utilities */ static shape co180; static int phi1[16]= {0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2}, phi2[2] = {0,2}, phi3[8] = {0,0,0,0,2,2,2,2}, phi4[4] = {0,0,2,2}, phi5[1] = {0}, phi6[1] = {0}, phir[16]= {0,0,2,2,2,2,0,0,2,2,0,0,0,0,2,2}; pulsesequence() { /* Declare variables */ char autocal[MAXSTR], satmode[MAXSTR], co_dec[MAXSTR], dec_co[MAXSTR], dec_15n[MAXSTR]; int t1_counter = 0, t2_counter = 0, ni = getval("ni"), ni2 = getval("ni2"), phase = getval("phase"), phase2 = getval("phase2"); float aphase; double pi = 3.1415926, rg1 = 2.0e-6, rg2 = 2.0e-6, d0 = getval("d0"), d2_init = 0.0, d3_init = 0.0, satdly = getval("satdly"), satpwr = getval("satpwr"), satfrq = getval("satfrq"), mix = getval("mix"), tauch = getval("tauch"), taunh = getval("taunh"), tauxh = getval("tauxh"), bw, ofs, ppm, /* temporary Pbox parameters */ taua, taua0, taub, tauc, tauc0, taug, dtau, tau1, tau2, tau2b, gb1, phi_nr, dof_t1 = getval("dof_t1"), compC = getval("compC"), pwC = getval("pwC"), pwco180 = getval("pwco180"), pwN = getval("pwN"), offco = getval("offco"), pwClvl = getval("pwClvl"), dpwr_cod= getval("dpwr_cod"), dpwrf_cod = getval("dpwrf_cod"), pwNlvl = getval("pwNlvl"), gt1 = getval("gt1"), gt2 = getval("gt2"), gt3 = getval("gt3"), gt4 = getval("gt4"), gt5 = getval("gt5"), gt6 = getval("gt6"), gt7 = getval("gt7"), gt8 = getval("gt8"), gt9 = getval("gt9"), gt10 = getval("gt10"), gt11 = getval("gt11"), gzlvl1 = getval("gzlvl1"), gzlvl2 = getval("gzlvl2"), gzlvl3 = getval("gzlvl3"), gzlvl4 = getval("gzlvl4"), gzlvl5 = getval("gzlvl5"), gzlvl6 = getval("gzlvl6"), gzlvl7 = getval("gzlvl7"), gzlvl8 = getval("gzlvl8"), gzlvl9 = getval("gzlvl9"), gzlvl10 = getval("gzlvl10"), gzlvl11 = getval("gzlvl11"), gscale = getval("gscale"), gstab= getval("gstab"); getstr("autocal",autocal); getstr("satmode",satmode); getstr("co_dec",co_dec); getstr("dec_co",dec_co); getstr("dec_15n",dec_15n); gzlvl2=gscale*gzlvl2; gzlvl3=gscale*gzlvl3; gzlvl4=gscale*gzlvl4; gzlvl5=gscale*gzlvl5; if ( ni > 0 ) tau1 = d2 + 1.0/(2.0*sw1); else tau1 = d2; tau2 = d3 + 1.0/(2.0*sw2) - 4.0*pwC/pi - 2.0*pw - 4.0e-6; if ( dec_co[0] == 'y' ) { tau2b = d3 + 1.0/(2.0*sw2) - 4.0*pwC/pi - pwco180 - SAPS_DELAY - 4.0*POWER_DELAY - WFG_START_DELAY - 6.0e-6; } else { tau2b = d3 + 1.0/(2.0*sw2) - 4.0*pwC/pi - 2.0*pw - 6.0e-6; } /* Parameter checks */ if ( pw > 20e-6 ) { printf( "your pw seems too long !!! "); printf( " pw must be <= 20 usec \n"); psg_abort(1); } if ( pwC > 30e-6 ) { printf( "your pwC seems too long !!! "); printf( " pwC must be <= 30 usec \n"); psg_abort(1); } if ( pwN > 50e-6 ) { printf( "your pwN seems too long !!! "); printf( " pwN must be <= 50 usec \n"); psg_abort(1); } if ( dm[C] == 'y' ) { if ( at > 0.21 ) { printf( " acquisition time is too long for decoupling !!!\n" ); psg_abort(1); } if ( dpwr > 45 ) { printf( "incorrect power for dpwr !!! " ); printf( " must limit dpwr <= 45 \n"); psg_abort(1); } } if ( ( dm[A] == 'y' ) || ( dm[B] == 'y' ) ) { printf( "no decoupling should be done during status periods A or B !!!\n" ); psg_abort(1); } if ( gt1 > 1.5e-3 ) { printf( "gt1 is too long !!!\n" ); psg_abort(1); } if ( gt2 > 1e-3 ) { printf( "gt2 is too long !!!\n" ); psg_abort(1); } if ( gt3 > 1e-3 ) { printf( "gt3 is too long !!!\n" ); psg_abort(1); } if ( gt4 > 1e-3 ) { printf( "gt4 is too long !!!\n" ); psg_abort(1); } if ( gt5 > 1e-3 ) { printf( "gt5 is too long !!!\n" ); psg_abort(1); } if ( gt6 > 1e-3 ) { printf( "gt6 is too long !!!\n" ); psg_abort(1); } if ( gt7 > 1e-3 ) { printf( "gt7 is too long !!!\n" ); psg_abort(1); } if ( gt8 > 1e-3 ) { printf( "gt8 is too long !!!\n" ); psg_abort(1); } if ( gt9 > 1.5e-3 ) { printf( "gt9 is too long !!!\n" ); psg_abort(1); } if ( gt10 > 1.5e-3 ) { printf( "gt10 is too long !!!\n" ); psg_abort(1); } if ( gt11 > 1e-3 ) { printf( "gt11 is too long !!!\n" ); psg_abort(1); } /* Set variables */ settable(t1, 16, phi1); settable(t2, 2, phi2); settable(t3, 8, phi3); settable(t4, 4, phi4); settable(t5, 1, phi5); settable(t6, 1, phi6); settable(t60, 16, phir); /* Phase incrementation for hypercomplex data */ if ( phase == 2 ) { tsadd(t1,1,4); } if ( phase2 == 2 ) { tsadd(t4,1,4); } if( ix == 1) d2_init = d2; t1_counter = (int) ( (d2-d2_init)*sw1 + 0.5 ); if(t1_counter % 2) { tsadd(t1,2,4); tsadd(t60,2,4); } if( ix == 1) d3_init = d3; t2_counter = (int) ( (d3-d3_init)*sw2 + 0.5 ); if(t2_counter % 2) { tsadd(t4,2,4); tsadd(t60,2,4); } /* Calculate delay values for initial filter period. */ taua0 = 600.0e-6; tauc0 = 2.0*pwC+gt5+102.0e-6+SAPS_DELAY+2.0*GRADIENT_DELAY+rg1+rg2+2.0*pw/pi; if ( ni > 2) dtau = (taunh - taua0)/((double)(ni*2-1)); else dtau = 0.00; taua = 1.5*tauch + 0.5*tauc0 - t1_counter*dtau; taub = 0.5*(tauch - tauc0) + t1_counter*dtau; tauc = tauc0 + tau1 - 2.0*t1_counter*dtau; taug = 0.5*(taunh + taub - taua); /* Calculate the phase shift caused by the Bloch-Seigert effect of the sinc 180 pulse on the carbonyl spins. */ gb1 = 2.0 * pi * 1.69 / (2.0* pwco180); phi_nr = (180.0 / pi) * 0.45141167 * gb1 * gb1 * pwco180 / (4.0 * pi * offco * dfrq); aphase = (360.0 - phi_nr) * 4.0; initval(aphase,v1); /* Determine real-time variable v3 to use in the event that ni2=0 */ mod4(ct,v2); hlv(v2,v3); /* if ( ni > 0 ) initval(1.0,v6); else */ initval(0.0,v6); setautocal(); if (autocal[A] == 'y') { if (FIRST_FID) /* call Pbox */ { ppm = getval("dfrq"); bw = 118.0 * ppm; ofs = offco; co180 = pbox_make("co180", "sinc180n", bw, ofs, compC * pwC, pwClvl); } dpwrf_cod = co180.pwrf; dpwr_cod = pwClvl; pwco180 = co180.pw; } /* Begin the actual pulse sequence */ status(A); delay(d0); txphase(zero); obsstepsize(45.0); decoffset(dof_t1); decstepsize(0.25); decphase(zero); decpower(pwClvl); dec2phase(zero); dec2power(pwNlvl); if ( satmode[A] == 'y' ) { obspower(satpwr); obsoffset(satfrq); rgpulse(satdly,zero,rg1,rg2); obspower(tpwr); obsoffset(tof); delay(1.0e-3); } else { delay(d1); } status(B); decrgpulse(pwC,zero,rg1,rg2); zgradpulse(gzlvl1,gt1); delay(gstab); rgpulse(pw,t1,20.0e-6,rg2); zgradpulse(gzlvl2,gt2); delay(tauch-pwN-pw-gt2-2.0*GRADIENT_DELAY-2.0*(rg1+rg2)-2.0*pw/pi); dec2rgpulse(pwN,zero,rg1,rg2); simpulse(2.0*pw,0.666*pwC,zero,zero,rg1,rg2); zgradpulse(gzlvl3,gt3); delay(taua-pw-2.333*pwC-gt3-2.0*GRADIENT_DELAY-rg1-rg2-1.0e-6); decrgpulse(pwC,zero,rg1,0.); simpulse(2.0*pw,2.666*pwC,zero,one,1.0e-6,0.); decrgpulse(pwC,zero,1.0e-6,rg2); zgradpulse(gzlvl4,gt4); delay(taub-taug-2.333*pwC-pwN-gt4-2.0*GRADIENT_DELAY-rg1-rg2-1.0e-6); dec2rgpulse(2.0*pwN,zero,rg1,rg2); delay(taug-2.0*pwN-rg1-2.0*rg2); dec2rgpulse(pwN,t2,rg1,rg2); decrgpulse(pwC,t2,rg1,0.); decrgpulse(pwC,one,1.0e-6,rg2); xmtrphase(v6); delay(tauc-2.0*pwC-gt5 -101.0e-6-SAPS_DELAY-2.0*GRADIENT_DELAY-rg1-rg2-2.0*pw/pi); zgradpulse(gzlvl5,gt5); delay(100.0e-6-rg1); rgpulse(pw,t3,rg1,rg2); xmtrphase(zero); zgradpulse(gzlvl6,gt6); decoffset(dof); delay(0.5*mix-2.0*pw-gt6-rg1-rg2-SAPS_DELAY-2.0*GRADIENT_DELAY-OFFSET_DELAY); rgpulse(pw,zero,rg1,1.0e-6); rgpulse(2.0*pw,one,1.0e-6,1.0e-6); rgpulse(pw,zero,1.0e-6,rg2); delay(0.5*mix-2.0*pw-pwN-pwC-gt7-1.0e-3-3.0*(rg1+rg2)-2.0*GRADIENT_DELAY); dec2rgpulse(pwN,zero,rg1,rg2); decrgpulse(pwC,zero,rg1,rg2); zgradpulse(gzlvl7,gt7); delay(1.0e-3); rgpulse(pw,zero,rg1,rg2); zgradpulse(gzlvl8,gt8); txphase(zero); delay(tauxh-gt8-2.333*pwC-rg1-rg2-2.0e-6); /* delay 1/(4J) */ decrgpulse(pwC,zero,rg1,1.0e-6); simpulse(2.0*pw,2.667*pwC,zero,one,1.0e-6,1.0e-6); decrgpulse(pwC,zero,1.0e-6,rg2); zgradpulse(gzlvl8,gt8); txphase(one); delay(tauxh-gt8-2.333*pwC-rg1-rg2-2.0e-6); /* delay 1/(4J) */ rgpulse(pw,one,rg1,rg2); zgradpulse(gzlvl9,gt9); /* IzSz state */ txphase(t5); decphase(t4); delay(gstab); if ( ni2 == 0 ) { ifzero(v3); delay(4.0*pwC+8.0e-6); elsenz(v3); decrgpulse(pwC,zero,2.0e-6,1.0e-6); decrgpulse(2.0*pwC,one,1.0e-6,1.0e-6); decrgpulse(pwC,zero,1.0e-6,2.0e-6); endif(v3); } else { decrgpulse(pwC,t4,rg1,2.0e-6); if ( ((0.5*tau2b) > (2.0*pwN+2.0e-6)) && (dec_15n[0] == 'y') ) { if ( dec_co[0] == 'y' ) { decpower(dpwr_cod); decpwrf(dpwrf_cod); } delay(0.5*tau2b-2.0*pwN-2.0e-6); dec2rgpulse(2.0*pwN,zero,1.0e-6,1.0e-6); if ( dec_co[0] == 'y' ) { if (autocal[A] == 'y') simshaped_pulse("","co180",2.0*pw,pwco180,t5,zero,2.0e-6,2.0e-6); else simshaped_pulse("",co_dec,2.0*pw,pwco180,t5,zero,2.0e-6,2.0e-6); decpower(pwClvl); decpwrf(4095.); dcplrphase(v1); } else { rgpulse(2.0*pw,t5,2.0e-6,2.0e-6); } decphase(t6); delay(0.5*tau2b); } else if ( (tau2b > 4.0e-7) && (dec_co[0] == 'y') ) { decpower(dpwr_cod); decpwrf(dpwrf_cod); delay(0.5*tau2b); if (autocal[A] == 'y') simshaped_pulse("","co180",2.0*pw,pwco180,t5,zero,2.0e-6,2.0e-6); else simshaped_pulse("",co_dec,2.0*pw,pwco180,t5,zero,2.0e-6,2.0e-6); decpower(pwClvl); decpwrf(4095.0); decphase(t6); dcplrphase(v1); delay(0.5*tau2b); } else { decphase(t6); delay(0.5*tau2); rgpulse(2.0*pw,t5,1.0e-6,1.0e-6); delay(0.5*tau2); } decrgpulse(pwC,t6,1.0e-6,rg2); } if ( ni2 > 0 ) zgradpulse(gzlvl10,gt10); else zgradpulse(-gzlvl10,gt10); dcplrphase(zero); txphase(zero); decphase(zero); delay(gstab); rgpulse(pw,zero,rg1,rg2); zgradpulse(gzlvl11,gt11); delay(tauxh-gt11-2.333*pwC-rg1-rg2-2.0e-6); decrgpulse(pwC,zero,rg1,1.0e-6); simpulse(2.0*pw,2.667*pwC,zero,one,1.0e-6,1.0e-6); decrgpulse(pwC,zero,1.0e-6,rg2); zgradpulse(gzlvl11,gt11); decpower(dpwr); delay(tauxh-gt11-2.333*pwC-rg1-rof2-POWER_DELAY-2.0e-6); rgpulse(pw,two,rg1,rof2); /* Acquire the FID */ status(C); setreceiver(t60); }
21.716578
85
0.590495
[ "shape" ]
2e611788421ad6f2dccdbf56ddfe7f0554068c40
995
h
C
Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkWeightedRoundRobinSchedulingAlgorithm_h #define mitkWeightedRoundRobinSchedulingAlgorithm_h #include "mitkSchedulingAlgorithmBase.h" namespace mitk { class WeightedRoundRobinSchedulingAlgorithm : public SchedulingAlgorithmBase { public: WeightedRoundRobinSchedulingAlgorithm(); ~WeightedRoundRobinSchedulingAlgorithm(); SchedulableProcess* GetNextProcess(std::vector<SchedulableProcess*>& processQueue) override; }; } #endif
28.428571
97
0.675377
[ "vector" ]
2e62e7b0e1cf54033362214dc512ed17e4038170
8,202
c
C
tcopf/PFReadData.c
alexWerner/REUHPCSDSU
cfec8b7326b7acd3342f091968e1f22969b8abcd
[ "BSD-2-Clause" ]
null
null
null
tcopf/PFReadData.c
alexWerner/REUHPCSDSU
cfec8b7326b7acd3342f091968e1f22969b8abcd
[ "BSD-2-Clause" ]
null
null
null
tcopf/PFReadData.c
alexWerner/REUHPCSDSU
cfec8b7326b7acd3342f091968e1f22969b8abcd
[ "BSD-2-Clause" ]
null
null
null
#include "petscmat.h" #include "power.h" #include <string.h> #include <ctype.h> PetscErrorCode PFReadMatPowerData(PFDATA *pf,char *filename) { FILE *fp; PetscErrorCode ierr; VERTEX_Power Bus; LOAD Load; GEN Gen; EDGE_Power Branch; PetscInt line_counter=0; PetscInt bus_start_line=-1,bus_end_line=-1; /* xx_end_line points to the next line after the record ends */ PetscInt gen_start_line=-1,gen_end_line=-1; PetscInt br_start_line=-1,br_end_line=-1; PetscInt cost_start_line=-1,cost_end_line=-1; char line[MAXLINE]; PetscInt loadi=0,geni=0,bri=0,busi=0,costi=0,limi=0,i,j; int extbusnum,bustype_i; double Pd,Qd; PetscInt maxbusnum=-1,intbusnum,*busext2intmap,genj,loadj; GEN newgen; LOAD newload; PetscFunctionBegin; fp = fopen(filename,"r"); /* Check for valid file */ if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Can't open Matpower data file %s",filename); pf->nload=0; while(fgets(line,MAXLINE,fp)) { if (strstr(line,"mpc.bus = [")) bus_start_line = line_counter+1; /* Bus data starts from next line */ if (strstr(line,"mpc.gen ") && gen_start_line == -1) gen_start_line = line_counter+1; /* Generator data starts from next line */ if (strstr(line,"mpc.branch ")) br_start_line = line_counter+1; /* Branch data starts from next line */ if (strstr(line,"mpc.gencost ") && cost_start_line == -1) cost_start_line = line_counter+1; /* Generator data starts from next line */ if (strstr(line,"];")) { if (bus_start_line != -1 && bus_end_line == -1) bus_end_line = line_counter; if (gen_start_line != -1 && gen_end_line == -1) gen_end_line = line_counter; if (br_start_line != -1 && br_end_line == -1) br_end_line = line_counter; if (cost_start_line != -1 && cost_end_line == -1) cost_end_line = line_counter; } /* Count the number of pq loads */ if (bus_start_line != -1 && line_counter >= bus_start_line && bus_end_line == -1) { sscanf(line,"%d %d %lf %lf",&extbusnum,&bustype_i,&Pd,&Qd); if (!((Pd == 0.0) && (Qd == 0.0))) pf->nload++; if (extbusnum > maxbusnum) maxbusnum = extbusnum; } line_counter++; } fclose(fp); pf->nbus = bus_end_line - bus_start_line; pf->ngen = gen_end_line - gen_start_line; pf->nbranch = br_end_line - br_start_line; ierr = PetscPrintf(PETSC_COMM_SELF,"nb = %D, ngen = %D, nload = %D, nbranch = %D\n",pf->nbus,pf->ngen,pf->nload,pf->nbranch);CHKERRQ(ierr); ierr = PetscCalloc1(pf->nbus,&pf->bus);CHKERRQ(ierr); ierr = PetscCalloc1(pf->ngen,&pf->gen);CHKERRQ(ierr); ierr = PetscCalloc1(pf->nload,&pf->load);CHKERRQ(ierr); ierr = PetscCalloc1(pf->nbranch,&pf->branch);CHKERRQ(ierr); Bus = pf->bus; Gen = pf->gen; Load = pf->load; Branch = pf->branch; for(i=0; i < pf->nbus; i++) { pf->bus[i].ngen = pf->bus[i].nload = 0; } /* Setting pf->sbase to 100 */ pf->sbase = 100.0; ierr = PetscMalloc1(maxbusnum+1,&busext2intmap);CHKERRQ(ierr); for (i=0; i < maxbusnum+1; i++) busext2intmap[i] = -1; fp = fopen(filename,"r"); /* Reading data */ for (i=0;i<line_counter;i++) { if (!fgets(line,MAXLINE,fp)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"File is incorrectly formatted"); if ((i >= bus_start_line) && (i < bus_end_line)) { double gl,bl,vm,va,basekV; int bus_i,ide,area; /* Bus data */ sscanf(line,"%d %d %lf %lf %lf %lf %d %lf %lf %lf",&bus_i,&ide,&Pd,&Qd,&gl,&bl,&area,&vm,&va,&basekV); Bus[busi].bus_i = bus_i; Bus[busi].ide = ide; Bus[busi].area = area; Bus[busi].gl = gl; Bus[busi].bl = bl; //PetscPrintf(PETSC_COMM_WORLD, "bl|%f\n", Bus[busi].bl); Bus[busi].vm = vm; Bus[busi].va = va; Bus[busi].basekV = basekV; Bus[busi].internal_i = busi; busext2intmap[Bus[busi].bus_i] = busi; if (!((Pd == 0.0) && (Qd == 0.0))) { Load[loadi].bus_i = Bus[busi].bus_i; Load[loadi].status = 1; Load[loadi].pl = Pd; Load[loadi].ql = Qd; Load[loadi].area = Bus[busi].area; Load[loadi].internal_i = busi; Bus[busi].lidx[Bus[busi].nload++] = loadi; if (Bus[busi].nload > NLOAD_AT_BUS_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Exceeded maximum number of loads allowed at bus"); loadi++; } busi++; } /* Read generator data */ if (i >= gen_start_line && i < gen_end_line) { double pg,qg,qt,qb,vs,mbase,pt,pb; int bus_i,status; sscanf(line,"%d %lf %lf %lf %lf %lf %lf %d %lf %lf",&bus_i,&pg,&qg,&qt,&qb,&vs,&mbase,&status,&pt,&pb); Gen[geni].bus_i = bus_i; Gen[geni].status = status; Gen[geni].pg = pg; Gen[geni].qg = qg; Gen[geni].qt = qt; Gen[geni].qb = qb; Gen[geni].vs = vs; Gen[geni].mbase = mbase; Gen[geni].pt = pt; Gen[geni].pb = pb; Gen[geni].idx = geni; intbusnum = busext2intmap[Gen[geni].bus_i]; Gen[geni].internal_i = intbusnum; Bus[intbusnum].gidx[Bus[intbusnum].ngen++] = geni; Bus[intbusnum].vm = Gen[geni].vs; if (Bus[intbusnum].ngen > NGEN_AT_BUS_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Exceeded maximum number of generators allowed at bus"); geni++; } if (i >= cost_start_line && i < cost_end_line) { double startup, shutdown, c1, c2, c3; int model, coefs; sscanf(line,"%d %lf %lf %d %lf %lf %lf",&model,&startup,&shutdown,&coefs,&c1,&c2,&c3); Gen[costi].model = model; Gen[costi].startup = startup; Gen[costi].shutdown = shutdown; Gen[costi].ncost = coefs; Gen[costi].cost[0] = c1; Gen[costi].cost[1] = c2; Gen[costi].cost[2] = c3; costi++; } if (i >= br_start_line && i < br_end_line) { PetscScalar R,X,Bc,Ys; double r,x,b,rateA,rateB,rateC,tapratio,phaseshift; int fbus,tbus,status; sscanf(line,"%d %d %lf %lf %lf %lf %lf %lf %lf %lf %d",&fbus,&tbus,&r,&x,&b,&rateA,&rateB,&rateC,&tapratio,&phaseshift,&status); Branch[bri].fbus = fbus; Branch[bri].tbus = tbus; Branch[bri].status = status; Branch[bri].r = r; Branch[bri].x = x; Branch[bri].b = b; Branch[bri].rateA = rateA; Branch[bri].rateB = rateB; Branch[bri].rateC = rateC; Branch[bri].tapratio = tapratio; Branch[bri].phaseshift = phaseshift; Branch[bri].idx = bri; if(rateA != 0) Branch[bri].limitIdx = limi++; else Branch[bri].limitIdx = -1; if(Branch[bri].tapratio == 0.0) Branch[bri].tapratio = 1.0; Branch[bri].phaseshift *= PETSC_i * PETSC_PI/180.0; Branch[bri].tapratio *= PetscExpComplex(Branch[bri].phaseshift); PetscScalar tapconj = PetscConjComplex(Branch[bri].tapratio); intbusnum = busext2intmap[Branch[bri].fbus]; Branch[bri].internal_i = intbusnum; intbusnum = busext2intmap[Branch[bri].tbus]; Branch[bri].internal_j = intbusnum; /* Compute self and transfer admittances */ R = Branch[bri].r; X = Branch[bri].x; Bc = Branch[bri].b; Ys = 1 / (R + PETSC_i * X); Branch[bri].ytt = Ys + PETSC_i * Bc / 2; Branch[bri].yft = -1 * Ys / tapconj; Branch[bri].ytf = -1 * Ys / Branch[bri].tapratio; Branch[bri].yff = Branch[bri].ytt / (Branch[bri].tapratio * tapconj); bri++; } } fclose(fp); /* Reorder the generator data structure according to bus numbers */ genj=0; loadj=0; ierr = PetscMalloc1(pf->ngen,&newgen);CHKERRQ(ierr); ierr = PetscMalloc1(pf->nload,&newload);CHKERRQ(ierr); for (i = 0; i < pf->nbus; i++) { for (j = 0; j < pf->bus[i].ngen; j++) { ierr = PetscMemcpy(&newgen[genj++],&pf->gen[pf->bus[i].gidx[j]],sizeof(struct _p_GEN));CHKERRQ(ierr); } for (j = 0; j < pf->bus[i].nload; j++) { ierr = PetscMemcpy(&newload[loadj++],&pf->load[pf->bus[i].lidx[j]],sizeof(struct _p_LOAD));CHKERRQ(ierr); } } ierr = PetscFree(pf->gen);CHKERRQ(ierr); ierr = PetscFree(pf->load);CHKERRQ(ierr); pf->gen = newgen; pf->load = newload; ierr = PetscFree(busext2intmap);CHKERRQ(ierr); PetscFunctionReturn(0); }
37.452055
143
0.60278
[ "model" ]
2e64a507a97c001d57e78326d38af2a381a4f350
496
h
C
include/hub/storage/dropboxstorage.h
tfrec-kalcsits/SensorSystem-Hub
c74849cab6e7a58af318a8538a3931af60b406c5
[ "MIT" ]
null
null
null
include/hub/storage/dropboxstorage.h
tfrec-kalcsits/SensorSystem-Hub
c74849cab6e7a58af318a8538a3931af60b406c5
[ "MIT" ]
null
null
null
include/hub/storage/dropboxstorage.h
tfrec-kalcsits/SensorSystem-Hub
c74849cab6e7a58af318a8538a3931af60b406c5
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <hub/compatibility.h> #include "remotestorage.h" namespace sensorsystem { class DropboxStorage : public RemoteStorage { public: DropboxStorage(std::string oauth_access_token, std::string upload_path, std::string prefix_path); bool syncFiles() override; private: const std::string oauth_access_token; const std::string upload_path; const std::string prefix_path; }; std::vector<char> readFileBinary(sv::string_view path); }
20.666667
101
0.741935
[ "vector" ]